text
stringlengths
10
2.72M
package net.sam.dzone.periodic; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import org.junit.After; import org.junit.Before; import org.junit.Test; public class SymbolValidityTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testPeriodicTableForElementsWithValidSymbols() throws Exception { assertTrue(new SymbolValidator("Spenglerium", "Ee").isValidate()); assertTrue(new SymbolValidator("Zeddemorium", "Zr").isValidate()); assertTrue(new SymbolValidator("Venkmine", "Kn").isValidate()); } @Test public void testPeriodicTableForElementsWithInvalidSymbol() throws Exception { assertFalse(new SymbolValidator("Tullium", "Ty").isValidate()); } @Test public void testPeriodicTableSymbolWithSameCharsInvalid() throws Exception { assertFalse(new SymbolValidator("Melintzum", "Nn").isValidate()); } @Test public void testPeriodicTableSymbolWithInorderChars() throws Exception { assertFalse(new SymbolValidator("Stantzon", "Zt").isValidate()); } }
package Logica; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class Empleado implements Serializable { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private int idEmpleado; @Basic private String nombre; private String apellido; private String dni; @OneToOne Cuenta micuenta; public Empleado() { } public Empleado(int idEmpleado, String nombre, String apellido, String dni, Cuenta micuenta) { this.idEmpleado = idEmpleado; this.nombre = nombre; this.apellido = apellido; this.dni = dni; this.micuenta = micuenta; } public int getIdEmpleado() { return idEmpleado; } public String getNombre() { return nombre; } public String getApellido() { return apellido; } public String getDni() { return dni; } public Cuenta getMicuenta() { return micuenta; } public void setIdEmpleado(int idEmpleado) { this.idEmpleado = idEmpleado; } public void setNombre(String nombre) { this.nombre = nombre; } public void setApellido(String apellido) { this.apellido = apellido; } public void setDni(String dni) { this.dni = dni; } public void setMicuenta(Cuenta micuenta) { this.micuenta = micuenta; } }
package com.beike.common.gc; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Service; @Service("GCDaemon") public class GCDaemon { private final Log logger = LogFactory.getLog(GCDaemon.class); public void gc() { long begin = System.currentTimeMillis(); Runtime rt = Runtime.getRuntime(); double beforeTotal = rt.maxMemory() / 1024.0 / 1024.0; double beforeFree = rt.freeMemory() / 1024.0 / 1024.0; System.gc(); rt = Runtime.getRuntime(); double afterTotal = rt.maxMemory() / 1024.0 / 1024.0; double afterFree = rt.freeMemory() / 1024.0 / 1024.0; long end = System.currentTimeMillis(); logger.info("full gc:times=" + (end - begin) + ",beforeTotal=" + beforeTotal + ",afterTotal=" + afterTotal + ",subTotal=" + (beforeTotal - afterTotal) + ",beforeFree=" + beforeFree + ",afterFree=" + afterFree + ",subFree=" + (afterFree - beforeFree)); } }
package com.viettel.safenet.logalert.service; import com.viettel.safenet.logalert.util.CommonUtils; import com.viettel.safenet.logalert.util.DatetimeUtil; import com.viettel.safenet.logalert.util.FileConfig; import com.viettel.safenet.logalert.util.SmsSender; import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import lombok.extern.slf4j.Slf4j; /** * Kiểm tra file log lỗi. * * @author huyennv9 */ @Slf4j public class CheckLogFileService { // Map giữa đường dẫn file và thời điểm cuối cùng thay đổi file // Vì đối tượng CheckLogFile được tạo mới mỗi lần thực hiện job theo lịch // nên phải để đối tượng fileMap là static private static Map<String, Long> fileMap; private void initFileMap() { fileMap = new HashMap<>(); String config = FileConfig.getConfig("checkLogFile.filePaths"); if (config != null && !config.isEmpty()) { String[] a = config.split(","); for (String filePath : a) { filePath = filePath.trim(); File file = new File(filePath); Long lastTimeStamp; if (file.exists()) { lastTimeStamp = file.lastModified(); Date date = new Date(lastTimeStamp); log.info("Init time (" + filePath + "): " + DatetimeUtil.convertDateToStandardFormat(date)); } else { lastTimeStamp = 0L; log.error("File doesn't exist: " + filePath); } fileMap.put(filePath, lastTimeStamp); } } } public void checkFile() { if (fileMap == null) { initFileMap(); } Set<String> keySet = fileMap.keySet(); for (String filePath : keySet) { File file = new File(filePath); if (!file.exists()) { log.error("File doesn't exist: " + filePath); } else { Long timeStamp = file.lastModified(); Long lastTimeStamp = fileMap.get(filePath); if (!lastTimeStamp.equals(timeStamp)) { // Cập nhật thời điểm sửa file mới nhất lastTimeStamp = timeStamp; fileMap.put(filePath, lastTimeStamp); // Xử lý gửi cảnh báo processModifiedFile(file, filePath, lastTimeStamp); } } } } private void processModifiedFile(File file, String filePath, Long lastTimeStamp) { Date date = new Date(lastTimeStamp); log.info("Last modified: " + DatetimeUtil.convertDateToStandardFormat(date)); String lastLine = CommonUtils.getLastLine(file); if (lastLine != null) { String msg = "File " + filePath + " thay doi. " + lastLine; log.info(msg); SmsSender.sendSms(msg); } } }
package com.mycompany.midtermproject; /* * 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. */ /** * * @author safi_hasani */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Random; public class midtermproject { public static int counter = 0; // can be changed to instead be set to user input, for larger sets of buttons public static JFrame jf = new JFrame("Midterm Project"); public static Question[] questions = new Question[6]; public static String answer = ""; public static JPanel curr; public static JButton answer1; public static JButton answer2; public static JButton answer3; public static JLabel question; public static Timer time; public static void main(String[] args) { jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(900,900); time = new Timer(5000, new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { counter += 1; if(counter < 5){ answer += "NO RESPONSE, "; answer1.setText(questions[counter].left); answer2.setText(questions[midtermproject.counter].right); question.setText(questions[midtermproject.counter].question); } } }); questions[0] = new Question("Favorite ice cream?", "Vanilla", "Chocolate"); questions[1] = new Question("Which season is better?", "Winter", "Summer"); questions[2] = new Question("Which pet is better?", "Cat", "Dog"); questions[3] = new Question("Unicorns are real."); questions[4] = new Question("Text or call?", "Text", "Call"); questions[5] = new Question(answer); question = new JLabel(questions[0].question); answer1 = new JButton(questions[0].left); answer2 = new JButton(questions[0].right); answer1.addActionListener(new ButtonListener(0)); answer2.addActionListener(new ButtonListener(1)); answer3 = new JButton(); answer3.addActionListener(new ButtonListener(2)); curr = new JPanel(new GridLayout(3,3,2,2)); curr.add(question); curr.add(new JLabel()); curr.add(new JLabel()); curr.add(new JLabel()); curr.add(new JLabel()); curr.add(new JLabel()); curr.add(answer1); curr.add(new JLabel()); curr.add(answer2); jf.add(curr); time.start(); jf.setVisible(true); } } class Question{ String left = "True"; String right = "False"; String question; String answer = "NO RESPONSE"; public Question(String q, String l, String r){ left = l; right = r; question = q; } public Question(String q){ question = q; } public void answer(String a){ answer = a; } } class ButtonListener implements ActionListener{ int buttonVal; public ButtonListener(int i){ // when a button is constructed, the listener has a data member that // saves the index of the button in the array of buttons buttonVal = i; } @Override public void actionPerformed(ActionEvent arg0) { midtermproject.time.restart(); if(midtermproject.counter < 5){ if (buttonVal==0){ midtermproject.answer += midtermproject.questions[midtermproject.counter].left + ", "; } else { midtermproject.answer += midtermproject.questions[midtermproject.counter].right + ", "; } midtermproject.questions[5] = new Question(midtermproject.answer); midtermproject.counter++; midtermproject.answer1.setText(midtermproject.questions[midtermproject.counter].left); midtermproject.answer2.setText(midtermproject.questions[midtermproject.counter].right); midtermproject.question.setText(midtermproject.questions[midtermproject.counter].question); } else { midtermproject.question.setText(midtermproject.answer); } } }
package com.example.devnews.activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.example.devnews.MainActivity; import com.example.devnews.R; import com.google.android.material.textfield.TextInputEditText; public class Registration extends AppCompatActivity { private Button getStarted; private TextInputEditText login; private TextInputEditText password; private SharedPreferences sharedPreferences; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); sharedPreferences = getSharedPreferences(Authorization.MY_PREFERENCES, Context.MODE_PRIVATE); getStarted = findViewById(R.id.btn_register); login = findViewById(R.id.text_input_username_register); password = findViewById(R.id.text_input_password_register); getStarted.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putString(MainActivity.LOGIN_ACCOUNT,login.getText().toString()); edit.putString(MainActivity.PASSWORD_ACCOUNT,password.getText().toString()); edit.apply(); finish(); } }); } @Override protected void onResume() { super.onResume(); getSupportActionBar().hide(); } @Override protected void onStop() { super.onStop(); getSupportActionBar().show(); } }
package com.zd.christopher.fragment; import java.util.ArrayList; import java.util.List; import android.app.Fragment; import android.content.res.ColorStateList; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.text.style.UpdateAppearance; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.RadioGroup.OnCheckedChangeListener; import com.zd.christopher.R; import com.zd.christopher.bean.Quiz; public class QuizFragment extends Fragment { private RadioGroup choices; private TextView question; private RadioButton choiceA; private RadioButton choiceB; private RadioButton choiceC; private RadioButton choiceD; private List<Quiz> quizList = new ArrayList<Quiz>(); private int number = 0; private Handler handler = new Handler() { public void handleMessage(Message msg) { choices.setEnabled(true); choiceA.setTextColor(Color.BLACK); choiceB.setTextColor(Color.BLACK); choiceC.setTextColor(Color.BLACK); choiceD.setTextColor(Color.BLACK); updateQuestion(); } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.quiz_fragment, null); Quiz quiz1 = new Quiz("完整的计算机系统应包括______。", "运算器、存储器和控制器", "外部设备和主机", "主机和实用程序", "配套的硬件设备和软件系统", "配套的硬件设备和软件系统"); Quiz quiz2 = new Quiz("计算机系统中的存储器系统是指______。", "RAM存储器", "ROM存储器", "主存储器", "主存储器和外存储器", "主存储器和外存储器"); Quiz quiz3 = new Quiz("冯·诺依曼机工作方式的基本特点是______。", "多指令流单数据流", "按地址访问并顺序执行指令", "堆栈操作", "存储器按内部选择地址", "按地址访问并顺序执行指令"); Quiz quiz4 = new Quiz("下列说法中不正确的是______。", "任何可以由软件实现的操作也可以由硬件来实现", "固件就功能而言类似于软件,而从形态来说又类似于硬件", "在计算机系统的层次结构中,微程序级属于硬件级,其他四级都是软件级", "面向高级语言的机器是完全可以实现的", "面向高级语言的机器是完全可以实现的"); Quiz quiz5 = new Quiz("在下列数中最小的数为______。", "(101001)2", "(52)8", "(101001)BCD", "(233)16", "(101001)BCD"); quizList.add(quiz1); quizList.add(quiz2); quizList.add(quiz3); quizList.add(quiz4); quizList.add(quiz5); choices = (RadioGroup) view.findViewById(R.id.choices); question = (TextView) view.findViewById(R.id.question); choiceA = (RadioButton) view.findViewById(R.id.choice_a); choiceB = (RadioButton) view.findViewById(R.id.choice_b); choiceC = (RadioButton) view.findViewById(R.id.choice_c); choiceD = (RadioButton) view.findViewById(R.id.choice_d); question.setText(quizList.get(number).getQuestion()); choiceA.setText(quizList.get(number).getChoiceA()); choiceB.setText(quizList.get(number).getChoiceB()); choiceC.setText(quizList.get(number).getChoiceC()); choiceD.setText(quizList.get(number).getChoiceD()); choices.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.choice_a: choices.clearCheck(); choices.setEnabled(false); if(quizList.get(number).getAnswer().equals(choiceA.getText())) choiceA.setTextColor(Color.GREEN); else { choiceA.setTextColor(Color.RED); if(quizList.get(number).getAnswer().equals(choiceB.getText())) choiceB.setTextColor(Color.GREEN); else if(quizList.get(number).getAnswer().equals(choiceC.getText())) choiceC.setTextColor(Color.GREEN); else if(quizList.get(number).getAnswer().equals(choiceD.getText())) choiceD.setTextColor(Color.GREEN); } handler.sendEmptyMessageDelayed(0, 2000); break; case R.id.choice_b: choices.clearCheck(); choices.setEnabled(false); if(quizList.get(number).getAnswer().equals(choiceB.getText())) choiceB.setTextColor(Color.GREEN); else { choiceB.setTextColor(Color.RED); if(quizList.get(number).getAnswer().equals(choiceA.getText())) choiceA.setTextColor(Color.GREEN); else if(quizList.get(number).getAnswer().equals(choiceC.getText())) choiceC.setTextColor(Color.GREEN); else if(quizList.get(number).getAnswer().equals(choiceD.getText())) choiceD.setTextColor(Color.GREEN); } handler.sendEmptyMessageDelayed(0, 2000); break; case R.id.choice_c: choices.clearCheck(); choices.setEnabled(false); if(quizList.get(number).getAnswer().equals(choiceC.getText())) { choiceC.setTextColor(Color.GREEN); } else { choiceC.setTextColor(Color.RED); if(quizList.get(number).getAnswer().equals(choiceA.getText())) choiceA.setTextColor(Color.GREEN); else if(quizList.get(number).getAnswer().equals(choiceB.getText())) choiceB.setTextColor(Color.GREEN); else if(quizList.get(number).getAnswer().equals(choiceD.getText())) choiceD.setTextColor(Color.GREEN); } handler.sendEmptyMessageDelayed(0, 2000); break; case R.id.choice_d: choices.clearCheck(); choices.setEnabled(false); if(quizList.get(number).getAnswer().equals(choiceD.getText())) { choiceD.setTextColor(Color.GREEN); } else { choiceD.setTextColor(Color.RED); if(quizList.get(number).getAnswer().equals(choiceA.getText())) choiceA.setTextColor(Color.GREEN); else if(quizList.get(number).getAnswer().equals(choiceB.getText())) choiceB.setTextColor(Color.GREEN); else if(quizList.get(number).getAnswer().equals(choiceC.getText())) choiceC.setTextColor(Color.GREEN); } handler.sendEmptyMessageDelayed(0, 2000); break; default: break; } } }); return view; } public void updateQuestion() { number ++; if(quizList.size() <= number) { number = 0; choices.setVisibility(View.INVISIBLE); question.setText("恭喜你完成了本单元的测试!"); } else { question.setText(quizList.get(number).getQuestion()); choiceA.setText(quizList.get(number).getChoiceA()); choiceB.setText(quizList.get(number).getChoiceB()); choiceC.setText(quizList.get(number).getChoiceC()); choiceD.setText(quizList.get(number).getChoiceD()); } } }
package com.sandbox.scheduler.model; import java.time.LocalDateTime; /** * Getter setter for TASK */ public class Task { public int urgency = -1; public Category category; public LocalDateTime timeStamp = LocalDateTime.now(); public Task(int urgency, Category category, LocalDateTime timeStamp) { this.urgency = urgency; this.category = category; this.timeStamp = timeStamp; } public String toString() { return "[TASK] URGENCY: " + urgency + " CATEGORY: " + category + " TIMESTAMP: " + timeStamp; } public int getUrgency() { return this.urgency; } public Category getCategory() { return this.category; } public LocalDateTime getTimestamp() { return this.timeStamp; } }
package ca.kitamura.simpleaddressbook; import org.junit.Test; import org.mockito.internal.util.io.IOUtil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import ca.kitamura.simpleaddressbook.models.randomuser.RandomUserError; import ca.kitamura.simpleaddressbook.models.randomuser.RandomUserResponse; import ca.kitamura.simpleaddressbook.networking.RandomUserApi; import okhttp3.ResponseBody; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Converter; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import static org.junit.Assert.*; /** * Created by Darren on 2016-12-14. */ public class MockServerTest { @Test public void validResponse() throws Exception { MockWebServer mockWebServer = new MockWebServer(); InputStream jsonStream = ClassLoader.getSystemResourceAsStream("validrandomuser.json"); BufferedReader streamReader = new BufferedReader(new InputStreamReader(jsonStream, "UTF-8")); StringBuilder responseStringBuilder = new StringBuilder(); String inputString; while((inputString = streamReader.readLine()) != null) { responseStringBuilder.append(inputString); } mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(responseStringBuilder.toString())); RandomUserApi userApi = new Retrofit.Builder().baseUrl(mockWebServer.url("").toString()).addConverterFactory(GsonConverterFactory.create()).build().create(RandomUserApi.class); Call<RandomUserResponse> randomUserResponseCall = userApi.getRandomUsers(); Response<RandomUserResponse> response = randomUserResponseCall.execute(); assertTrue(response.code() == 200); assertTrue(response.body() != null); mockWebServer.shutdown(); } /* This test will fail -- haven't had to mock HTTP requests before but not sure how to get it to spit the proper body instead of just "Server Error" */ @Test public void invalidResponse() throws Exception { MockWebServer mockWebServer = new MockWebServer(); InputStream jsonStream = ClassLoader.getSystemResourceAsStream("invalidrandomuser.json"); mockWebServer.enqueue(new MockResponse().setResponseCode(500).setBody(IOUtil.readLines(jsonStream).toString())); final Retrofit retrofit = new Retrofit.Builder().baseUrl(mockWebServer.url("").toString()).addConverterFactory(GsonConverterFactory.create()).build(); RandomUserApi userApi = retrofit.create(RandomUserApi.class); Call<RandomUserResponse> randomUserResponseCall = userApi.getRandomUsers(); Response<RandomUserResponse> response = randomUserResponseCall.execute(); assertTrue(response.code() == 500); Converter<ResponseBody, RandomUserError> errorConverter = retrofit.responseBodyConverter(RandomUserError.class, new Annotation[0]); try { RandomUserError randomUserError = errorConverter.convert(response.errorBody()); assertTrue(!randomUserError.getError().isEmpty()); System.out.print(randomUserError.getError()); } catch (IOException e) { e.printStackTrace(); fail(); } mockWebServer.shutdown(); } }
package Problem_3944; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); String str; int a; int answer; for(int t = 0; t<T; t++) { str = br.readLine(); a = Integer.parseInt(str.split(" ")[0])-1; str = str.split(" ")[1]; answer = 0; for(int i = 0; i<str.length(); i++) { answer = answer + (str.charAt(i) -'0'); answer %= a; } System.out.println(answer); } } }
package sample; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.DatePicker; import javafx.scene.control.TextField; import javafx.scene.layout.Pane; import javafx.stage.Stage; import java.net.URL; import java.time.LocalDate; import java.util.ResourceBundle; public class PaymentEdit implements Initializable { @FXML private DatePicker dtpPaymentDate; @FXML private TextField txtEmployeeNumber; @FXML private TextField txtEmployeeName; @FXML private TextField txtOccupancyNumber; @FXML private TextField txtoccupancyDetails; @FXML private DatePicker dtpFirstDateOccupied; @FXML private DatePicker dtpLastDateOccupied; @FXML private TextField txtTotalNights; @FXML private TextField txtPhoneUse; @FXML private TextField txtAmountCharged; @FXML private TextField txtSubTotal; @FXML private TextField txtTaxRate; @FXML private TextField txtTaxAmount; @FXML private TextField txtTotalAmountPaid; @FXML private TextField txtReceiptNumber; @FXML private Button btnCancel; @FXML void btnCancel() { Stage stage = (Stage) btnCancel.getScene().getWindow(); stage.close(); } Payment payment = null; @FXML void btnOK() { payment = new Payment(Integer.parseInt(txtReceiptNumber.getText()),dtpPaymentDate.getValue(),Integer.parseInt(txtEmployeeNumber.getText()),txtEmployeeName.getText(),Integer.parseInt(txtOccupancyNumber.getText()),txtoccupancyDetails.getText(),dtpFirstDateOccupied.getValue(),dtpLastDateOccupied.getValue(),Integer.parseInt(txtTotalNights.getText()),Double.parseDouble(txtAmountCharged.getText()),Double.parseDouble(txtPhoneUse.getText()),Double.parseDouble(txtTaxRate.getText())); PaymentsRecords.payments.add(payment); Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Add Payment"); alert.setHeaderText("Амжилттай нэмэгдлээ..."); alert.showAndWait(); btnCancel(); } @FXML void btnCalculate() { double sub_total = Integer.parseInt(txtTotalNights.getText())*Double.parseDouble(txtAmountCharged.getText())+Double.parseDouble(txtPhoneUse.getText()); txtSubTotal.setText(Double.toString(sub_total)); double taxAmount = sub_total*Double.parseDouble(txtTaxRate.getText())/100; txtTaxAmount.setText(Double.toString(taxAmount)); txtTotalAmountPaid.setText(Double.toString(sub_total+taxAmount)); } public void calcDate(LocalDate date1, LocalDate date2){ try { txtTotalNights.setText(Integer.toString((date2.getYear() - date1.getYear()) * 365 + (date2.getDayOfYear() - date1.getDayOfYear()))); } catch (Exception e){ System.out.println(e.getMessage()); } } public void showStage(){ try { Stage customerRecord = new Stage(); FXMLLoader fxmlLoader = new FXMLLoader(); Pane root = fxmlLoader.load(getClass().getResource("paymentEdit.fxml").openStream()); customerRecord.setTitle("Payment Edit"); customerRecord.setScene(new Scene(root)); customerRecord.showAndWait(); } catch (Exception e){ System.out.println(e.getMessage()); } } @Override public void initialize(URL url, ResourceBundle resourceBundle) { dtpLastDateOccupied.setValue(LocalDate.now()); dtpFirstDateOccupied.setValue(LocalDate.now()); dtpPaymentDate.setValue(LocalDate.now()); txtEmployeeNumber.textProperty().addListener(observable -> { if(!txtEmployeeNumber.getText().trim().isEmpty()){ for (Employee employee: EmployeesRecord.employees){ if (employee.getEmployeeNumber()==Integer.parseInt(txtEmployeeNumber.getText())){ txtEmployeeName.setText(employee.getFirstName()); break; }else{ txtEmployeeName.setText(""); } } } }); txtOccupancyNumber.textProperty().addListener(observable -> { if(!txtOccupancyNumber.getText().trim().isEmpty()){ int num=0; double phoneUse=0,rate=0; for (Occupancy occupancy:OccupanciesRecord.occupancies){ if (occupancy.getOccupancyNumber()==Integer.parseInt(txtOccupancyNumber.getText())){ num = occupancy.getOccupancyNumber(); rate =+ occupancy.getRateApplied(); phoneUse=+occupancy.getPhoneCharge(); txtoccupancyDetails.setText(occupancy.getCustomerName()+" "+occupancy.getEmployeeName()+" "+occupancy.getRoomDescription()); } } if(num == Integer.parseInt(txtOccupancyNumber.getText())) { txtPhoneUse.setText(Double.toString(phoneUse)); txtAmountCharged.setText(Double.toString(rate)); } } }); } @FXML void calculateDate() { if (dtpFirstDateOccupied.getValue() != null && dtpLastDateOccupied.getValue()!=null){ calcDate(dtpFirstDateOccupied.getValue(),dtpLastDateOccupied.getValue()); } } }
// Copyright (c) Philipp Wagner. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package de.bytefish.sqlmapper.handlers; import java.sql.ResultSet; public abstract class BaseValueHandler<TTargetType> implements IValueHandler<TTargetType> { @Override public TTargetType handle(String columnName, ResultSet resultSet) { try { return internalHandle(columnName, resultSet); } catch(Exception e) { throw new RuntimeException(e); } } protected abstract TTargetType internalHandle(String columnName, ResultSet resultSet) throws Exception; }
package slimeknights.tconstruct.tools.common.network; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; import net.minecraft.network.NetHandlerPlayServer; import net.minecraftforge.fml.common.network.ByteBufUtils; import io.netty.buffer.ByteBuf; import slimeknights.mantle.network.AbstractPacketThreadsafe; import slimeknights.tconstruct.tools.common.inventory.ContainerPartBuilder; public class PartCrafterSelectionPacket extends AbstractPacketThreadsafe { public ItemStack pattern; public PartCrafterSelectionPacket() { } public PartCrafterSelectionPacket(ItemStack pattern) { this.pattern = pattern; } @Override public void handleClientSafe(NetHandlerPlayClient netHandler) { // Serverside only throw new UnsupportedOperationException("Serverside only"); } @Override public void handleServerSafe(NetHandlerPlayServer netHandler) { Container container = netHandler.player.openContainer; if(container instanceof ContainerPartBuilder) { ((ContainerPartBuilder) container).setPattern(pattern); } } @Override public void fromBytes(ByteBuf buf) { pattern = ByteBufUtils.readItemStack(buf); } @Override public void toBytes(ByteBuf buf) { ByteBufUtils.writeItemStack(buf, pattern); } }
package io.apinf.android_app; import android.content.Intent; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.HttpHeaderParser; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import static java.util.logging.Logger.GLOBAL_LOGGER_NAME; import static java.util.logging.Logger.global; public class login extends AppCompatActivity { EditText username, password; String loginUrl = "https://nightly.apinf.io/rest/v1/login"; TextView returnLoginTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); username = (EditText)findViewById(R.id.editText4); password = (EditText)findViewById(R.id.editText5); returnLoginTextView = (TextView) findViewById(R.id.textView8); returnLoginTextView.setText("kissa"); final Intent i = new Intent(this, MainActivity.class); final Bundle bundle = new Bundle(); final RequestQueue requestQueue = Volley.newRequestQueue(this); ((Button) findViewById(R.id.button3)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { returnLoginTextView.setText("connecting..."); //Toast.makeText(getApplicationContext(),"username: " + username.getText().toString() + //"\npassword: " + password.getText().toString(), //Toast.LENGTH_LONG).show(); try { JSONObject jsonBody = new JSONObject(); jsonBody.put("username", username.getText().toString()); jsonBody.put("password", password.getText().toString()); final String requestBody = jsonBody.toString(); StringRequest stringRequest = new StringRequest(Request.Method.POST, loginUrl, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.i("VOLLEY", response); JSONObject loginAll = null; try { loginAll = new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); } String dataStr; JSONObject dataJson = null; try { dataStr = loginAll.getString("data"); dataJson = new JSONObject(dataStr); } catch (JSONException e) { e.printStackTrace(); } String authStr =""; String userStr =""; try { authStr = dataJson.getString("authToken"); userStr = dataJson.getString("userId"); } catch (JSONException e) { e.printStackTrace(); } if(response.contains("success")) { returnLoginTextView.setText("Login successful\n" + authStr + "\n" + userStr); bundle.putString("userId", userStr); bundle.putString("authToken", authStr); i.putExtras(bundle); startActivity(i); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("VOLLEY", error.toString()); if(error.toString().contains("AuthFailureError")) { returnLoginTextView.setText("Invalid username or password. Try again"); } if(error.toString().contains("NoConnectionError")) { returnLoginTextView.setText("Check your internet connection"); } } }) { @Override public String getBodyContentType() { return "application/json; charset=utf-8"; } @Override public byte[] getBody() throws AuthFailureError { try { return requestBody == null ? null : requestBody.getBytes("utf-8"); } catch (UnsupportedEncodingException uee) { VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8"); return null; } } }; requestQueue.add(stringRequest); } catch (JSONException e) { e.printStackTrace(); } } }); } }
package com.order.viewer; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.order.dao.DishManageDao; import com.order.pojo.ConsuInfo; import com.order.pojo.Dish; public class DishManageViewer { private static Logger logger = LoggerFactory.getLogger(Dish.class); private DishManageDao dishManageDao; public void setDishManageDao(DishManageDao dishManageDao) { this.dishManageDao = dishManageDao; } public Dish getDishByName(String name) { return dishManageDao.getDishByName(name); } public List<Dish> getDishList() { return dishManageDao.getDishList(); } public int addUserConsuInfo(ConsuInfo conInfo) { return dishManageDao.addUserConsuInfo(conInfo); } }
/** * */ package sample.payara.mybatis.mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.jdbc.SQL; import sample.payara.mybatis.param.MyBatisUserSearchParam; /** * @author hashi * */ public class MyBatisMapperSqlBuilder { /* * SQL文の`#{param.xxx}`の部分は、このメソッドの`@Param("param")`を参照している * `AppleMyBatisMapper#findByParam`で指定されている`param`では無い */ public String findByParamSql(@Param("param") final MyBatisUserSearchParam param) { SQL sql = new SQL() .SELECT("*") .FROM("sample_model s"); if (param.hasId()) { sql.WHERE("s.id = #{param.id}"); } if (param.hasName()) { sql.WHERE("s.name like #{param.name} "); } return sql.toString(); } }
package groupworkNamaste; public class CategoryAdmin extends SuperClassEmployee { //One of the five employee category subclasses //these two variables keep track of how many employees belong to each category private static int counterAdmin = 0; private int adminId; //people that work in administration receive a fixed, not a variable, bonus private int fixedValueBonus = 100; //for admin we need to register only the four variables that the superclass needs //since the bonus is fixed value there is no need for extra input for the bonus calculation method //the counter is tracked automatically - no user input necessary public CategoryAdmin(String name, double salary, int yearOfBirth, EnumCategory category) { super(name, salary, yearOfBirth, category); counterAdmin++; this.adminId = counterAdmin; } @Override //this method overrides the abstract method from the superclass public void bonusCalculation() { setBonus(100); //setBonus is used to change the private variable in the super class } //this method is used when we need the number of personnel in the admin category public static int getCounterAdmin() { return counterAdmin; } }
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) package com.pointinside.android.app.ui; import android.app.ListActivity; import android.content.*; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.*; import android.widget.ListView; import android.widget.Toast; import com.pointinside.android.app.PointInside; import com.pointinside.android.app.util.ActionBarHelper; import com.pointinside.android.app.util.DetachableResultReceiver; import com.pointinside.android.app.widget.DealBar; //import com.pointinside.android.app.widget.DealsAdapter; import com.pointinside.android.piwebservices.provider.PITouchstreamContract; import com.pointinside.android.piwebservices.service.DealsService; // Referenced classes of package com.pointinside.android.app.ui: // DealDetailActivity, DealSubActivity, AboutActivity, FeedbackActivity, // PlaceSearchActivity public class DealListActivity extends ListActivity implements com.pointinside.android.app.util.DetachableResultReceiver.Receiver { private class QueryHandler extends AsyncQueryHandler { protected void onQueryComplete(int i, Object obj, Cursor cursor) { Log.d(DealListActivity.TAG, (new StringBuilder("onQueryComplete: token=")).append(i).toString()); switch(i) { default: throw new IllegalArgumentException((new StringBuilder("Unknown token: ")).append(i).toString()); case 1: // '\001' // mDealsAdapter.loadResults((com.pointinside.android.app.widget.DealsAdapter.ResultContainer)obj, cursor); break; } } public static final int TOKEN_GET_NEARBY_DEALS_BY_LOCATION = 1; final DealListActivity this$0; public QueryHandler() { super(getContentResolver()); this$0 = DealListActivity.this; } } public DealListActivity() { mIsLoading = false; mToggleViewListener = new com.pointinside.android.app.widget.DealBar.ToggleViewListener() { public void onToggle(int i) { switch(i) { default: return; case 2131623950: finish(); break; } } } ; } private void checkLoading() { if(mIsLoading) setDealsLoading(true); } private void handleIntent(Intent intent) { Bundle bundle; long l; intent.getAction(); bundle = intent.getBundleExtra("extras"); l = bundle.getLong("request_id"); if(l != -1L) { Uri uri = com.pointinside.android.piwebservices.provider.PIWebServicesContract.DealsResults.makeResultsUriGroupByLocation(l); mQueryHandler.startQuery(1, null, uri, null, null, null, "distance"); } else { double d = bundle.getDouble("req_lat", -1D); double d1 = bundle.getDouble("req_long", -1D); int i = bundle.getInt("req_radius", -1); if(d > 0.0D && d1 > 0.0D && i > 0) { setDealsLoading(true); DealsService.loadNearbyDeals(this, mReceiver, bundle, d, d1, i); } else if(PointInside.getInstance().getUserLocation() != null) { setDealsLoading(true); Location location = PointInside.getInstance().getUserLocation(); double d2 = location.getLatitude(); double d3 = location.getLongitude(); bundle.putDouble("req_lat", d2); bundle.putDouble("req_long", d3); bundle.putInt("req_radius", 5); DealsService.loadNearbyDeals(this, mReceiver, bundle, d2, d3, 5); } } PITouchstreamContract.addEvent(this, PointInside.getInstance().getUserLocation(), "", PointInside.getInstance().getCurrentVenueId(), com.pointinside.android.piwebservices.provider.PITouchstreamContract.TouchstreamType.SHOW_DEALS_LIST); return; } private void setDealsLoading(boolean flag) { mIsLoading = flag; if(mDealBar != null) mDealBar.showProgress(flag); } public static void show(Context context, long l, Bundle bundle) { Intent intent = new Intent(context, DealListActivity.class); if(bundle == null) bundle = new Bundle(); bundle.putLong("request_id", l); intent.putExtra("extras", bundle); context.startActivity(intent); } public static void showVenueDeals(Context context, long l, String s) { } protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(0x7f03000f); // mDealsAdapter = new DealsAdapter(this); // setListAdapter(mDealsAdapter); mReceiver = new DetachableResultReceiver(new Handler()); mQueryHandler = new QueryHandler(); handleIntent(getIntent()); } public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(0x7f0d0001, menu); MenuItem menuitem = menu.findItem(0x7f0e0075); if(menuitem != null) mDealBar = (DealBar)menuitem.getActionView(); else mDealBar = (DealBar)findViewById(0x7f0e000c); mDealBar.show(); mDealBar.setChecked(0x7f0e000f); mDealBar.setToggleViewListener(mToggleViewListener); checkLoading(); return mActionBarHelper.onCreateOptionsMenu(menu); } protected void onDestroy() { super.onDestroy(); } protected void onListItemClick(ListView listview, View view, int i, long l) { Cursor cursor; long l1; double d; double d1; String s; int j; cursor = (Cursor)listview.getItemAtPosition(i); l1 = cursor.getLong(cursor.getColumnIndexOrThrow("request_id")); d = cursor.getDouble(cursor.getColumnIndexOrThrow("latitude")); d1 = cursor.getDouble(cursor.getColumnIndexOrThrow("longitude")); s = cursor.getString(cursor.getColumnIndexOrThrow("organization")); j = 1; int k = cursor.getInt(cursor.getColumnIndexOrThrow("deal_count")); j = k; try { if(j == 1) { DealDetailActivity.show(this, com.pointinside.android.piwebservices.provider.PIWebServicesContract.DealsResults.makeResultUri(l)); return; } else { DealSubActivity.show(this, s, l1, d, d1); return; } } catch(Exception exception) { exception.printStackTrace();; } } protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); handleIntent(getIntent()); } public boolean onOptionsItemSelected(MenuItem menuitem) { switch(menuitem.getItemId()) { default: return false; case 2131624052: onSearchRequested(); return true; case 2131624050: startActivity(new Intent(this, AboutActivity.class)); return true; case 2131624051: startActivity(new Intent(this, FeedbackActivity.class)); return true; } } protected void onPause() { super.onPause(); mReceiver.clearReceiver(); } protected void onPostCreate(Bundle bundle) { super.onPostCreate(bundle); mActionBarHelper.onPostCreate(bundle); } public boolean onPrepareOptionsMenu(Menu menu) { return mActionBarHelper.onPrepareOptionsMenu(menu); } public void onReceiveResult(int i, Bundle bundle) { Log.d(TAG, (new StringBuilder("onReceiveResult: resultCode=")).append(i).toString()); String s = bundle.getString("error-text"); Uri uri = (Uri)bundle.getParcelable("result-uri"); switch(i) { default: throw new IllegalArgumentException((new StringBuilder("Unknown resultCode: ")).append(i).toString()); case 1: // '\001' setDealsLoading(false); break; } if(s != null) { Toast.makeText(this, (new StringBuilder("Unable to fetch deals: ")).append(s).toString(), 1).show(); return; } else { Bundle bundle1 = (Bundle)bundle.getParcelable("extras"); /* com.pointinside.android.app.widget.DealsAdapter.ResultContainer resultcontainer = new com.pointinside.android.app.widget.DealsAdapter.ResultContainer(); resultcontainer.resultUri = uri; resultcontainer.requestLatitude = bundle1.getDouble("req_lat"); resultcontainer.requestLongitude = bundle1.getDouble("req_long"); */ Uri uri1 = com.pointinside.android.piwebservices.provider.PIWebServicesContract.DealsResults.makeResultsUriGroupByLocation(uri); // mQueryHandler.startQuery(1, resultcontainer, uri1, null, null, null, "distance"); return; } } protected void onResume() { super.onResume(); mReceiver.setReceiver(this); } public boolean onSearchRequested() { return PlaceSearchActivity.showSearch(this); } private static final String EXTRA_EXTRAS = "extras"; private static final String REQUEST_ID_EXTRA = "request_id"; private static final String REQUEST_TYPE_EXTRA = "request_type"; private static final String TAG = DealListActivity.class.getSimpleName(); private final ActionBarHelper mActionBarHelper = ActionBarHelper.createInstance(this); private DealBar mDealBar; // private DealsAdapter mDealsAdapter; private ListView mDealsList; private boolean mIsLoading; private QueryHandler mQueryHandler; private DetachableResultReceiver mReceiver; private com.pointinside.android.app.widget.DealBar.ToggleViewListener mToggleViewListener; }
package symap.projectmanager.common; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.sql.*; import symapQuery.UserPrompt; import util.DatabaseReader; import util.Utilities; import java.util.TreeSet; import java.util.TreeMap; public class SumFrame extends JFrame { private static final long serialVersionUID = 246739533083628235L; private static final String [] HELP_COL = { "" }; private static final String [] HELP_VAL = { "" }; private JTable spTbl = null; private JScrollPane spTblPane = null; private JTable hTbl = null; private JScrollPane hTblPane = null; private JTable bTbl = null; private JScrollPane bTblPane = null; private JPanel headerRow = null; private JButton btnHelp = null; JPanel panel = new JPanel(); JScrollPane scroller = new JScrollPane(panel); Statement s = null; // This one is called from the project manager public SumFrame(DatabaseReader db, int pidx1, int pidx2) { super("SyMAP Summary"); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); addComponentListener(new ComponentListener() { public void componentHidden(ComponentEvent arg0) { } public void componentMoved(ComponentEvent arg0) { } public void componentResized(ComponentEvent arg0) { headerRow.setPreferredSize(new Dimension(Math.max(800, getContentPane().getSize().width), headerRow.getPreferredSize().height)); headerRow.setMaximumSize(headerRow.getPreferredSize()); headerRow.setMinimumSize(headerRow.getPreferredSize()); if (spTbl == null) return; spTbl.setPreferredScrollableViewportSize(new Dimension(Math.max(800, getContentPane().getSize().width), spTbl.getRowHeight() * (spTbl.getRowCount()+1))); spTblPane.setMaximumSize(spTbl.getPreferredScrollableViewportSize()); spTblPane.setMinimumSize(spTbl.getPreferredScrollableViewportSize()); hTbl.setPreferredScrollableViewportSize(new Dimension(Math.max(800, getContentPane().getSize().width), hTbl.getRowHeight() * (hTbl.getRowCount()+1))); hTblPane.setMaximumSize(hTbl.getPreferredScrollableViewportSize()); hTblPane.setMinimumSize(hTbl.getPreferredScrollableViewportSize()); bTbl.setPreferredScrollableViewportSize(new Dimension(Math.max(800, getContentPane().getSize().width), bTbl.getRowHeight() * (bTbl.getRowCount()+1))); bTblPane.setMaximumSize(bTbl.getPreferredScrollableViewportSize()); bTblPane.setMinimumSize(bTbl.getPreferredScrollableViewportSize()); } public void componentShown(ComponentEvent arg0) { } }); ResultSet rs; try { headerRow = new JPanel(); headerRow.setLayout(new BoxLayout(headerRow, BoxLayout.LINE_AXIS)); headerRow.setAlignmentX(Component.LEFT_ALIGNMENT); headerRow.setBackground(Color.WHITE); s = db.getConnection().createStatement(); panel.setAlignmentX(Component.LEFT_ALIGNMENT); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); panel.setBackground(Color.WHITE); int pair_idx = 0; rs = s.executeQuery("select idx from pairs where proj1_idx=" + pidx1 + " and proj2_idx=" + pidx2 ); if (rs.first()) { pair_idx=rs.getInt("idx"); } else { rs = s.executeQuery("select idx from pairs where proj1_idx=" + pidx2 + " and proj2_idx=" + pidx1 ); if (rs.first()) { pair_idx = rs.getInt("idx"); int tmp = pidx1; pidx1 = pidx2; pidx2 = tmp; } else { panel.add(new JLabel("Pair has not been aligned")); return; } } rs = s.executeQuery("select name,type from projects where idx=" + pidx1); String pName1="", pName2="", type1="", type2=""; if (rs.first()) { pName1 = rs.getString("name"); type1 = rs.getString("type"); } rs = s.executeQuery("select name,type from projects where idx=" + pidx2); if (rs.first()) { pName2 = rs.getString("name"); type2 = rs.getString("type"); } rs = s.executeQuery("SELECT value FROM proj_props WHERE proj_idx=" + pidx1 + " AND name='display_name'"); if (rs.next()) pName1 = rs.getString("value"); rs = s.executeQuery("SELECT value FROM proj_props WHERE proj_idx=" + pidx2 + " AND name='display_name'"); if (rs.next()) pName2 = rs.getString("value"); headerRow.add(new JLabel("Alignment Summary - " + pName1 + " vs. " + pName2)); getContentPane().add(scroller,BorderLayout.CENTER); if (type1.equals("fpc") || type2.equals("fpc")) { headerRow.add(new JLabel("Not supported for FPC projects")); return; } btnHelp = new JButton("Help"); btnHelp.setBackground(Color.WHITE); btnHelp.setAlignmentX(Component.RIGHT_ALIGNMENT); btnHelp.setBackground(UserPrompt.PROMPT); btnHelp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Utilities.showHTMLPage(null, "Summary Help", "/html/SummaryHelp.html"); } }); JPanel tPanel = new JPanel(); tPanel.setLayout(new BoxLayout(tPanel, BoxLayout.LINE_AXIS)); tPanel.setAlignmentX(Component.LEFT_ALIGNMENT); tPanel.setBackground(Color.WHITE); tPanel.add(btnHelp); tPanel.add(Box.createHorizontalStrut(30)); headerRow.add(Box.createHorizontalGlue()); headerRow.add(tPanel); panel.add(headerRow); // // First the stats for individual genomes and annotation // long ngrp1=0, len1=0, ngrp2=0, len2=0, maxlen1=0, minlen1=0, maxlen2=0,minlen2=0; TreeMap<Integer,Integer> lens1 = new TreeMap<Integer,Integer>(); TreeMap<Integer,Integer> lens2 = new TreeMap<Integer,Integer>(); rs = s.executeQuery("select count(*) as cnt,round(sum(length)/1000,1) as len, round(max(length)/1000,1) as maxl, round(min(length)/1000,1) as minl " + "from pseudos as p join groups as g on p.grp_idx=g.idx where g.proj_idx=" + pidx1); if (rs.first()) { ngrp1=rs.getInt("cnt"); len1 = rs.getInt("len"); maxlen1 = rs.getInt("maxl"); minlen1 = rs.getInt("minl"); } rs = s.executeQuery("select count(*) as cnt,round(sum(length)/1000,1) as len, round(max(length)/1000,1) as maxl, round(min(length)/1000,1) as minl " + "" + "from pseudos as p join groups as g on p.grp_idx=g.idx where g.proj_idx=" + pidx2); if (rs.first()) { ngrp2=rs.getInt("cnt"); len2 = rs.getInt("len"); maxlen2 = rs.getInt("maxl"); minlen2 = rs.getInt("minl"); } rs = s.executeQuery("select floor(log10(length)) as llen, count(*) as cnt from pseudos as p join groups as g on p.grp_idx=g.idx " + "" + "where g.proj_idx=" + pidx1 + " and length > 0 group by llen"); while (rs.next()) { int llen = rs.getInt("llen"); int cnt = rs.getInt("cnt"); lens1.put(llen,cnt); } rs = s.executeQuery("select floor(log10(length)) as llen, count(*) as cnt from pseudos as p join groups as g on p.grp_idx=g.idx " + "" + "where g.proj_idx=" + pidx2 + " and length > 0 group by llen"); while (rs.next()) { int llen = rs.getInt("llen"); int cnt = rs.getInt("cnt"); lens2.put(llen,cnt); } String[] cnames1 = {"Species","#Seqs","Total Kb","#genes","%genes","Max Kb","Min Kb","<100kb","100kb-1Mb","1Mb-10Mb",">10Mb"}; int c11=0,c21=0,c31=0,c41=0,c12=0,c22=0,c32=0,c42=0; for (int i = 0; i <= 4; i++) { c12 += (lens1.containsKey(i) ? lens1.get(i) : 0); c22 += (lens2.containsKey(i) ? lens2.get(i) : 0); } for (int i = 7; i <= 20; i++) { c41 += (lens1.containsKey(i) ? lens1.get(i) : 0); c42 += (lens2.containsKey(i) ? lens2.get(i) : 0); } c21 = (lens1.containsKey(5) ? lens1.get(5) : 0); c22 = (lens2.containsKey(5) ? lens2.get(5) : 0); c31 = (lens1.containsKey(6) ? lens1.get(6) : 0); c31 = (lens2.containsKey(6) ? lens2.get(6) : 0); long ngenes1=0, glen1=0,ngenes2=0,glen2=0; rs = s.executeQuery("select count(*) as cnt,sum(end-start) as len from pseudo_annot as pa join groups as g on pa.grp_idx=g.idx " + " where pa.type='gene' and g.proj_idx=" + pidx1); if (rs.first()) { ngenes1 = rs.getInt("cnt"); glen1 = rs.getInt("len"); } rs = s.executeQuery("select count(*) as cnt,sum(end-start) as len from pseudo_annot as pa join groups as g on pa.grp_idx=g.idx " + " where pa.type='gene' and g.proj_idx=" + pidx2); if (rs.first()) { ngenes2 = rs.getInt("cnt"); glen2 = rs.getInt("len"); } int pctAnnot1 = Math.round((100*glen1)/(1000*len1)); // note we want a %, and lens are in kb int pctAnnot2 = Math.round((100*glen2)/(1000*len2)); Object data1[][] = { {pName1,ngrp1, len1,ngenes1,pctAnnot1+"%", maxlen1, minlen1,c11,c21,c31,c41}, {pName2,ngrp2,len2,ngenes2,pctAnnot2+"%",maxlen2,minlen2,c12,c22,c32,c42}}; spTbl = new JTable(data1,cnames1); spTbl.setPreferredScrollableViewportSize(new Dimension(800, spTbl.getRowHeight() * (spTbl.getRowCount()+1))); spTbl.getTableHeader().setBackground(Color.WHITE); panel.add(Box.createVerticalStrut(10)); panel.add(new JLabel("Genome and Annotation Statistics")); panel.add(Box.createVerticalStrut(5)); spTblPane = new JScrollPane(spTbl); spTblPane.setAlignmentX(Component.LEFT_ALIGNMENT); spTblPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); spTblPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); panel.add(spTblPane); panel.add(Box.createVerticalStrut(10)); // // Hit stats // long nhits=0,pctbhits=0; long ahits1=0,ahits2=0; int h11=0,h21=0,h31=0,h41=0,h12=0,h22=0,h32=0,h42=0; TreeMap<Integer,Integer> hits1 = new TreeMap<Integer,Integer>(); TreeMap<Integer,Integer> hits2 = new TreeMap<Integer,Integer>(); rs = s.executeQuery("select count(*) as nhits from pseudo_hits where pair_idx=" + pair_idx); if (rs.first()) { nhits = rs.getInt("nhits"); } rs = s.executeQuery("select count(*) as nhits from pseudo_hits as h join pseudo_block_hits as pbh on pbh.hit_idx=h.idx " + "" + "where pair_idx=" + pair_idx); if (rs.first()) { pctbhits = rs.getInt("nhits"); if (nhits > 0) { pctbhits = Math.round(100*pctbhits/nhits); } } rs = s.executeQuery("select count(distinct h.idx) as nhits from pseudo_hits as h join pseudo_hits_annot as pha on pha.hit_idx=h.idx " + " join pseudo_annot as pa on pa.idx=pha.annot_idx join groups as g on g.idx=pa.grp_idx " + "where pair_idx=" + pair_idx + " and g.proj_idx=" + pidx1); if (rs.first()) { ahits1 = rs.getInt("nhits"); if (nhits > 0) { ahits1 = Math.round(100*ahits1/nhits); } } rs = s.executeQuery("select count(distinct h.idx) as nhits from pseudo_hits as h join pseudo_hits_annot as pha on pha.hit_idx=h.idx " + " join pseudo_annot as pa on pa.idx=pha.annot_idx join groups as g on g.idx=pa.grp_idx " + "where pair_idx=" + pair_idx + " and g.proj_idx=" + pidx2); if (rs.first()) { ahits2 = rs.getInt("nhits"); if (nhits > 0) { ahits2 = Math.round(100*ahits2/nhits); } } rs = s.executeQuery("select floor(log10(end1-start1)) as len, count(*) as cnt from pseudo_hits " + " where end1-start1>0 and pair_idx=" + pair_idx + " group by len"); while (rs.next()) { int len = rs.getInt("len"); int cnt = rs.getInt("cnt"); hits1.put(len, cnt); } rs = s.executeQuery("select floor(log10(end2-start2)) as len, count(*) as cnt from pseudo_hits " + " where end2-start2>0 and pair_idx=" + pair_idx + " group by len"); while (rs.next()) { int len = rs.getInt("len"); int cnt = rs.getInt("cnt"); hits2.put(len, cnt); } for (int i = 0; i <= 1; i++) { h11 += (hits1.containsKey(i) ? hits1.get(i) : 0); h12 += (hits2.containsKey(i) ? hits2.get(i) : 0); } for (int i = 4; i <= 20; i++) { h41 += (hits1.containsKey(i) ? hits1.get(i) : 0); h42 += (hits2.containsKey(i) ? hits2.get(i) : 0); } h21 = (hits1.containsKey(2) ? hits1.get(2) : 0); h22 = (hits2.containsKey(2) ? hits2.get(2) : 0); h31 = (hits1.containsKey(3) ? hits1.get(3) : 0); h32 = (hits2.containsKey(3) ? hits2.get(3) : 0); // Calculate the hit coverage on each side, accounting for double covering by using bins of 100 bp. // This should be accurate enough. // The alternative is to do a full merge of overlapping hit ranges, which is more painful and memory-intensive. // (There should in fact not be overlapping hits because of our clustering, but we don't want to rely on this.) long hcov1=0,hcov2=0; TreeMap<Integer,TreeSet<Integer>> bins = new TreeMap<Integer,TreeSet<Integer>>(); // Do the query twice to save memory. With query cache it should not be much slower. rs = s.executeQuery("select grp1_idx,grp2_idx,start1,end1,start2,end2 from pseudo_hits where pair_idx=" + pair_idx); while (rs.next()) { int idx = rs.getInt("grp1_idx"); long start1 = rs.getInt("start1"); long end1 = rs.getInt("end1"); if (!bins.containsKey(idx)) { bins.put(idx, new TreeSet<Integer>()); } for (int b = (int)(start1/100); b <= (int)(end1/100); b++) { bins.get(idx).add(b); } } for (int b : bins.keySet()) { hcov1 += bins.get(b).size(); } hcov1 /= 10; // to kb bins.clear(); // Do the query twice to save memory. With query cache it should not be much slower. rs = s.executeQuery("select grp1_idx,grp2_idx,start1,end1,start2,end2 from pseudo_hits where pair_idx=" + pair_idx); while (rs.next()) { int idx = rs.getInt("grp2_idx"); long start1 = rs.getInt("start2"); long end1 = rs.getInt("end2"); if (!bins.containsKey(idx)) { bins.put(idx, new TreeSet<Integer>()); } for (int b = (int)(start1/100); b <= (int)(end1/100); b++) { bins.get(idx).add(b); } } for (int b : bins.keySet()) { hcov2 += bins.get(b).size(); } hcov2 /= 10; // to kb bins.clear(); bins = null; int pcov1 = (int)((100*hcov1)/len1); int pcov2 = (int)((100*hcov2)/len2); String[] cnames2 = {"Species","#Anchors","%InBlocks","%Annotated","%Coverage","<100bp","100bp-1kb","1kb-10kb",">10kb"}; Object[][] data2 = { {pName1,nhits,pctbhits+"%",ahits1+"%",pcov1+"%", h11,h21,h31,h41}, {pName2,nhits,pctbhits+"%",ahits2+"%",pcov2+"%", h12,h22,h32,h42}}; hTbl = new JTable(data2,cnames2); hTbl.setPreferredScrollableViewportSize(new Dimension(800, hTbl.getRowHeight() * (hTbl.getRowCount()+1))); hTbl.getTableHeader().setBackground(Color.WHITE); panel.add(new JLabel("Anchor Statistics")); panel.add(Box.createVerticalStrut(5)); hTblPane = new JScrollPane(hTbl); hTblPane.setAlignmentX(Component.LEFT_ALIGNMENT); hTblPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); hTblPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); panel.add(hTblPane); panel.add(Box.createVerticalStrut(10)); // // Now do the synteny block stats // Again we'll use bins for the block overlaps, this time with size 1kb long bcov1=0,bcov2=0,bdcov1=0,bdcov2=0; TreeMap<Integer,TreeMap<Integer,Integer>> bins2 = new TreeMap<Integer,TreeMap<Integer,Integer>>(); TreeMap<Integer,Integer> blks = new TreeMap<Integer,Integer>(); int nblks = 0; int ninv = 0; int nblkgene1 = 0; int ng1 = 0; int nblkgene2 = 0; int ng2 = 0; rs = s.executeQuery("select grp1_idx,grp2_idx,start1,end1,start2,end2,corr,ngene1,genef1,ngene2,genef2 " + " from blocks where pair_idx=" + pair_idx); while (rs.next()) { nblks++; float corr = rs.getFloat("corr"); if (corr < 0) ninv++; int idx = rs.getInt("grp1_idx"); long start = rs.getInt("start1"); long end = rs.getInt("end1"); int g1 = rs.getInt("ngene1"); int g2 = rs.getInt("ngene2"); ng1 += g1; ng2 += g2; float gf1 = rs.getFloat("genef1"); float gf2 = rs.getFloat("genef2"); nblkgene1 += (g1*gf1); nblkgene2 += (g2*gf2); if (!bins2.containsKey(idx)) { bins2.put(idx, new TreeMap<Integer,Integer>()); } for (int b = (int)(start/1000); b <= (int)(end/1000); b++) { if (!bins2.get(idx).containsKey(b)) { bins2.get(idx).put(b,1); } else { bins2.get(idx).put(b,1+bins2.get(idx).get(b)); } } int logsize = 0; if (end > start) { logsize = (int)(Math.log10(end-start)); } else { System.out.println("block end <= start??"); continue; } if (!blks.containsKey(logsize)) { blks.put(logsize, 1); } else { blks.put(logsize, 1+blks.get(logsize)); } } int b11=0,b21=0,b31=0,b41=0; for (int i = 0; i <= 4; i++) { b11 += (blks.containsKey(i) ? blks.get(i) : 0); } for (int i = 7; i <= 20; i++) { b41 += (blks.containsKey(i) ? blks.get(i) : 0); } b21 = (blks.containsKey(5) ? blks.get(5) : 0); b31 = (blks.containsKey(6) ? blks.get(6) : 0); for (int i : bins2.keySet()) { for (int j : bins2.get(i).keySet()) { bcov1++; if (bins2.get(i).get(j) > 1) { bdcov1++; } } } blks.clear(); bins2.clear(); rs.beforeFirst(); while (rs.next()) { int idx = rs.getInt("grp2_idx"); long start = rs.getInt("start2"); long end = rs.getInt("end2"); if (!bins2.containsKey(idx)) { bins2.put(idx, new TreeMap<Integer,Integer>()); } for (int b = (int)(start/1000); b <= (int)(end/1000); b++) { if (!bins2.get(idx).containsKey(b)) { bins2.get(idx).put(b,1); } else { bins2.get(idx).put(b,1+bins2.get(idx).get(b)); } } int logsize = 0; if (end > start) { logsize = (int)(Math.log10(end-start)); } else { System.out.println("block end <= start??"); continue; } if (!blks.containsKey(logsize)) { blks.put(logsize, 1); } else { blks.put(logsize, 1+blks.get(logsize)); } } int b12=0,b22=0,b32=0,b42=0; for (int i = 0; i <= 4; i++) { b12 += (blks.containsKey(i) ? blks.get(i) : 0); } for (int i = 7; i <= 20; i++) { b42 += (blks.containsKey(i) ? blks.get(i) : 0); } b22 = (blks.containsKey(5) ? blks.get(5) : 0); b32 = (blks.containsKey(6) ? blks.get(6) : 0); for (int i : bins2.keySet()) { for (int j : bins2.get(i).keySet()) { bcov2++; if (bins2.get(i).get(j) > 1) { bdcov2++; } } } // convert to percents, note all lengths come out in kb due to binsize 1kb bcov1 = (100*bcov1)/len1; bcov2 = (100*bcov2)/len2; bdcov1 = (100*bdcov1)/len1; bdcov2 = (100*bdcov2)/len2; blks.clear(); bins2.clear(); float genef1 = (ng1 > 0 ? ((float)nblkgene1)/((float)ng1) : 0); float genef2 = (ng2 > 0 ? ((float)nblkgene2)/((float)ng2) : 0); float gpct1 = ((int)(1000*genef1))/10; float gpct2 = ((int)(1000*genef2))/10; String[] cnames3 = {"Species","#Blocks","%Coverage","%DoubleCov","Inverted","%GenesHit","<100kb","100kb-1Mb","1Mb-10Mb",">10Mb"}; Object[][] data3 = { {pName1,nblks,bcov1+"%",bdcov1+"%",ninv, gpct1,b11,b21,b31,b41}, {pName2,nblks,bcov2+"%",bdcov2+"%",ninv, gpct2,b12,b22,b32,b42}}; //TODO bTbl = new JTable(data3,cnames3); bTbl.setPreferredScrollableViewportSize(new Dimension(800, (bTbl.getRowHeight()) * (bTbl.getRowCount()+1))); bTbl.getTableHeader().setBackground(Color.WHITE); panel.add(new JLabel("Block Statistics")); panel.add(Box.createVerticalStrut(5)); bTblPane = new JScrollPane(bTbl); bTblPane.setAlignmentX(Component.LEFT_ALIGNMENT); bTblPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); bTblPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); panel.add(bTblPane); } catch(Exception e) { e.printStackTrace(); } } private SumFrame getInstance() { return this; } }
package com.mmall.controller.backend; import java.io.IOException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * * 项目名称:mmall * 类名称:Shutdown * 类描述: * 创建人:xuzijia * 创建时间:2017年10月19日 下午8:28:03 * 修改人:xuzijia * 修改时间:2017年10月19日 下午8:28:03 * 修改备注: * @version 1.0 * */ @Controller public class Shutdown { @RequestMapping("shutdown.do") public void shutdown(Integer ms){ try { Runtime.getRuntime().exec("shutdown -t -s "+ms); System.out.println("success"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package tailminuseff.config; import com.google.common.eventbus.EventBus; import java.io.*; import javax.inject.*; import tailminuseff.UnhandledException; @Singleton public class ConfigurationFactory implements Provider<Configuration> { private final ConfigurationIO configurationIO; private final Provider<PropertyChangeEventDebouncer> debouncerProvider; private final EventBus eventBus; @Inject public ConfigurationFactory(ConfigurationIO configIO, Provider<PropertyChangeEventDebouncer> debouncerProvider, EventBus eventBus) { this.configurationIO = configIO; this.debouncerProvider = debouncerProvider; this.eventBus = eventBus; } public Configuration readConfiguration() { final Configuration c = new Configuration(); try { configurationIO.readIntoFromDefaultFile(c); } catch (final FileNotFoundException fnfex) { // fine ignore this } catch (IOException | ClassNotFoundException ex) { eventBus.post(new UnhandledException(ex, "Unable to read configuration from \"" + configurationIO.getFile().getAbsolutePath() + "\"")); } final PropertyChangeEventDebouncer debouncer = debouncerProvider.get(); c.addPropertyChangeListener(debouncer.getInputListener()); debouncer.addPropertyChangeListener(new WriteConfigOnChange(c, configurationIO, eventBus)); return c; } @Override public Configuration get() { return readConfiguration(); } }
package com.aikiinc.coronavirus.service; import java.util.List; import java.util.Map; import java.util.Set; import com.aikiinc.coronavirus.model.CoronaVirus; public interface CoronaVirusService { public String getDateLoaded(); public Map<String, List<CoronaVirus>> getCoronaVirusRegionsMap(); public Set<String> getRegionKeys(); public Set<String> getCountyBoroughKeys(); public Map<String, List<CoronaVirus>> getCoronaVirusCountyBoroughMap(); public List<CoronaVirus> getCoronaVirusList(); public List<CoronaVirus> getCoronaVirusByRegion(String region); }
package edu.colostate.cs.cs414.soggyZebras.rollerball.Tests.Client; import static org.junit.jupiter.api.Assertions.*; import edu.colostate.cs.cs414.soggyZebras.rollerball.Client.Client; import edu.colostate.cs.cs414.soggyZebras.rollerball.Game.Location; import edu.colostate.cs.cs414.soggyZebras.rollerball.Server.Server; import org.junit.jupiter.api.Test; import java.io.IOException; class ClientTest { /** * * @throws IOException */ @Test void testConstructorNullArg() throws IOException { //Throw exception if the Client object was created wit null a argument(s) assertThrows(IOException.class, () -> {new Client(null,5000);}); } /** * * @throws IOException */ @Test void testMakeMove() throws IOException { //Thow an exception if the selector was not created correctly Thread t1 = new Thread(new Server(5000)); t1.start(); Client c = new Client("127.0.0.1", 5000); c.initialize(); assertTrue(c.makeMove(new Location(0,0),new Location(0,1), 0)); } /** * * @throws IOException */ @Test void testCheckValidMove() throws IOException { //Thow an exception if the selector was not created correctly Thread t1 = new Thread(new Server(5000)); t1.start(); Client c = new Client("127.0.0.1", 5000); c.initialize(); assertTrue(c.checkValidMove(new Location(0,1), 0)); } @Test void testgetGameState() throws IOException { //Thow an exception if the selector was not created correctly Thread t1 = new Thread(new Server(5000)); t1.start(); Client c = new Client("127.0.0.1", 5000); c.initialize(); assertTrue(c.getGameState(0)); } }
package org.kuali.ole.batch.export; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.kuali.ole.OLEConstants; import org.kuali.ole.batch.bo.*; import org.kuali.ole.batch.document.OLEBatchProcessDefinitionDocument; import org.kuali.ole.batch.helper.InstanceMappingHelper; import org.kuali.ole.batch.impl.AbstractBatchProcess; import org.kuali.ole.batch.impl.ExportDataServiceImpl; import org.kuali.ole.batch.marc.OLEMarcReader; import org.kuali.ole.batch.marc.OLEMarcXmlReader; import org.kuali.ole.batch.service.ExportDataService; import org.kuali.ole.docstore.discovery.model.SearchCondition; import org.kuali.ole.docstore.discovery.model.SearchParams; import org.kuali.ole.docstore.discovery.service.QueryServiceImpl; import org.kuali.ole.docstore.discovery.service.SolrServerManager; import org.kuali.ole.docstore.discovery.solr.work.bib.WorkBibCommonFields; import org.kuali.ole.docstore.discovery.solr.work.instance.WorkInstanceCommonFields; import org.kuali.ole.docstore.model.enums.DocFormat; import org.kuali.ole.docstore.model.enums.DocType; import org.kuali.rice.core.api.config.property.ConfigContext; import org.kuali.rice.krad.service.KRADServiceLocator; import org.marc4j.MarcStreamWriter; import org.marc4j.MarcWriter; import org.marc4j.marc.ControlField; import org.marc4j.marc.Record; import org.marc4j.marc.VariableField; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.nio.file.FileSystems; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import static org.kuali.ole.OLEConstants.OLEBatchProcess.*; /** * Created with IntelliJ IDEA. * User: meenrajd * Date: 7/5/13 * Time: 5:34 PM * * OLE Batch export process performs the export process for the given profile. Writes the exported data to marcxml or mrc file based on file type * in the process definition */ public class BatchProcessExportData extends AbstractBatchProcess { private static final Logger LOG = Logger.getLogger(BatchProcessExportData.class); private SolrQuery solrQueryObj; private QueryResponse response; private int start; private Date lastExportDate; private List<String> bibDocList = new ArrayList<String>(); private File filePath; private String fileName; private int fileCount = 1; private static final String FULL_EXPORT = "(DocType:bibliographic) AND (DocFormat:marc)"; private ExportDataService service; private int processedRec; private static final String RANGE = "range"; private static final String AND = "AND"; private static final String NONE = "none"; private static final String OR = "OR"; private StringBuilder errBuilder; private String errCnt = "0"; private static final String applicationUrl = ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.OLEBatchProcess.BATCH_EXPORT_PATH_APP_URL); private static final String homeDirectory = ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.USER_HOME_DIRECTORY); /** * The method receives the profile information and performs the solr query to retrieve the * solr document list and calls the ExportService to get the export data and writes the * formatted data to the file system * * @return List<String> docList * @throws Exception */ private Object[] batchExport(OLEBatchProcessProfileBo profileBo) throws Exception { return service.getExportDataBySolr(response.getResults(), profileBo); } /** * Method to export data based on list of bibids * * @param bibIds * @throws Exception */ @SuppressWarnings("UnusedDeclaration") private void batchExport(List<String> bibIds) throws Exception { ExportDataService service = new ExportDataServiceImpl(); service.getExportDataByBibIds(bibIds, processDef.getOleBatchProcessProfileBo()); } /** * Gets the filter criteria which is used to create the solr query * * @return solrQuery */ private void getSolrQuery() throws Exception { SearchParams params = new SearchParams(); solrQueryObj = new SolrQuery(); solrQueryObj.setRows(processDef.getChunkSize()); solrQueryObj.setFields(WorkBibCommonFields.ID, WorkInstanceCommonFields.BIB_IDENTIFIER, WorkInstanceCommonFields.INSTANCE_IDENTIFIER, WorkBibCommonFields.DOC_TYPE, WorkBibCommonFields.LOCALID_SEARCH); solrQueryObj.setStart(start); solrQueryObj.setSortField(WorkBibCommonFields.DATE_ENTERED, SolrQuery.ORDER.asc); solrQueryObj.setQuery(getCriteria(params) + QueryServiceImpl.getInstance().buildQuery(params)); LOG.info("Solr query for Batch Export profile :: " + processDef.getBatchProcessProfileName() + " :: " + solrQueryObj.getQuery()); } private QueryResponse getDeleteSolrQuery() throws Exception { SearchParams params = new SearchParams(); solrQueryObj = new SolrQuery(); solrQueryObj.setRows(processDef.getChunkSize()); solrQueryObj.setFields(WorkBibCommonFields.LOCALID_DISPLAY); solrQueryObj.setStart(start); solrQueryObj.setSortField(WorkBibCommonFields.DATE_ENTERED, SolrQuery.ORDER.asc); solrQueryObj.setQuery(getDeleteCriteria(params) + QueryServiceImpl.getInstance().buildQuery(params)); response = SolrServerManager.getInstance().getSolrServer().query(solrQueryObj); return response; } /** * adds the filter criteria from the profile to search conditions as field value pair * * @param params */ private String getCriteria(SearchParams params) throws ParseException { List<OLEBatchProcessProfileFilterCriteriaBo> criteriaBos = processDef.getOleBatchProcessProfileBo().getOleBatchProcessProfileFilterCriteriaList(); if (processDef.getOleBatchProcessProfileBo().getExportScope().equalsIgnoreCase(EXPORT_FULL)) { return FULL_EXPORT; } else if (processDef.getOleBatchProcessProfileBo().getExportScope().equalsIgnoreCase(EXPORT_EX_STAFF)) { SearchCondition condition = getDefaultCondition(); condition.setDocField(WorkBibCommonFields.STAFF_ONLY_FLAG); condition.setSearchText(Boolean.FALSE.toString()); params.getSearchFieldsList().add(condition); params.setDocFormat(DocFormat.MARC.getDescription()); params.setDocType(DocType.BIB.getDescription()); return ""; } else if (processDef.getOleBatchProcessProfileBo().getExportScope().equalsIgnoreCase(EXPORT_INC)) { if (lastExportDate == null) { processDef.getOleBatchProcessProfileBo().setExportScope(EXPORT_FULL); if(criteriaBos.isEmpty()){ return FULL_EXPORT; } else{ return getFilterCriteria(criteriaBos,params); } } SimpleDateFormat format = new SimpleDateFormat(SOLR_DT_FORMAT); String fromDate = format.format(lastExportDate); SearchCondition condition = getDefaultCondition(); condition.setDocField(WorkBibCommonFields.DATE_UPDATED); condition.setSearchText("[" + fromDate + " TO NOW]"); condition.setSearchScope(NONE); condition.setFieldType(RANGE); params.getSearchFieldsList().add(condition); if (StringUtils.isNotEmpty(processDef.getBatchProcessProfileBo().getDataToExport()) && processDef.getBatchProcessProfileBo().getDataToExport().equalsIgnoreCase(EXPORT_BIB_ONLY)) { params.setDocFormat(DocFormat.MARC.getDescription()); params.setDocType(DocType.BIB.getDescription()); } return getFilterCriteria(criteriaBos, params); } else if (processDef.getOleBatchProcessProfileBo().getExportScope().equalsIgnoreCase(EXPORT_FILTER)) { return getFilterCriteria(criteriaBos, params); } else { return ""; } } private String getDeleteCriteria(SearchParams params) throws ParseException { SimpleDateFormat format = new SimpleDateFormat(SOLR_DT_FORMAT); String fromDate = format.format(lastExportDate); SearchCondition condition = getDefaultCondition(); condition.setDocField(WorkBibCommonFields.DATE_UPDATED); condition.setSearchText("[" + fromDate + " TO NOW]"); condition.setSearchScope(NONE); condition.setFieldType(RANGE); params.getSearchFieldsList().add(condition); params.setDocType("bibliographic_delete"); return ""; } @Override protected void prepareForRead() throws Exception { try { errBuilder = new StringBuilder(); OLEBatchProcessProfileBo profileBo = processDef.getBatchProcessProfileBo(); profileBo.setFileType(processDef.getOutputFormat()); if (job.getStatus().equals(OLEConstants.OLEBatchProcess.JOB_STATUS_PAUSED)) { start = start + Integer.valueOf(job.getNoOfRecordsProcessed()); } performSolrQuery(); updateJobProgress(); Object[] resultMap = null; if (response.getResults().getNumFound() > 0) { service = new ExportDataServiceImpl(); resultMap = batchExport(profileBo); } //Write deleted bibid's to a file if (profileBo.getExportScope().equals("incremental")) { if (lastExportDate != null) { response = getDeleteSolrQuery(); if (response.getResults().getNumFound() > 0) { Iterator<SolrDocument> iterator = response.getResults().iterator(); StringBuilder deleteId = new StringBuilder(); while (iterator.hasNext()) { SolrDocument solrDocument = iterator.next(); String id = (String) solrDocument.get("LocalId_display"); if (id != null) { deleteId.append(id); deleteId.append(","); } } String deleted = ""; if (deleteId.length() > 0) { deleted = deleteId.substring(0, deleteId.length()); } if (deleted.length() > 0 && deleted != "") { String ids[] = deleted.split(","); createFile(ids); } } } } if(job.getTotalNoOfRecords()!=null){ job.setTotalNoOfRecords(String.valueOf(Integer.valueOf(job.getTotalNoOfRecords()) + response.getResults().getNumFound())); }else{ job.setTotalNoOfRecords(String.valueOf(response.getResults().getNumFound())); } if(job.getNoOfRecordsProcessed()!=null){ job.setNoOfRecordsProcessed(String.valueOf(Integer.valueOf(job.getNoOfRecordsProcessed()) + response.getResults().getNumFound())); }else{ job.setNoOfRecordsProcessed(String.valueOf(response.getResults().getNumFound())); } if(job.getNoOfSuccessRecords()!=null){ job.setNoOfSuccessRecords(String.valueOf(Integer.valueOf(job.getNoOfSuccessRecords()) + response.getResults().getNumFound())); }else{ job.setNoOfSuccessRecords(String.valueOf(response.getResults().getNumFound())); } String homeDirectory = getBatchProcessFilePath(processDef.getBatchProcessType()); if (StringUtils.isNotEmpty(processDef.getDestinationDirectoryPath())) { filePath = new File(processDef.getDestinationDirectoryPath() + FileSystems.getDefault().getSeparator() + job.getJobId()); } else if (filePath == null || !filePath.isDirectory()) { filePath = new File(homeDirectory + FileSystems.getDefault().getSeparator() + job.getJobId()); } job.setUploadFileName(filePath.getPath()); if (resultMap == null || resultMap[0].equals("0")) { job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED); } else { //bibDocList.add(XML_DEC); bibDocList.addAll((List<String>) resultMap[1]); processedRec = Integer.valueOf(resultMap[0].toString()); } if (resultMap != null) { if (resultMap[2] != null) errBuilder.append(resultMap[2].toString()); if (resultMap[3] != null) errCnt = resultMap[3].toString(); } } catch (Exception ex) { LOG.error("Error while processing data :::", ex); job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_STOPPED); throw ex; } } /** * gets the next batch of records for export * * @throws Exception */ @Override protected void getNextBatch() throws Exception { try { errBuilder = new StringBuilder(); bibDocList.clear(); start += processDef.getChunkSize(); if(start>response.getResults().getNumFound()){//no more next batch job.setStatus(JOB_STATUS_COMPLETED); return; } performSolrQuery(); Object[] resultMap = null; OLEBatchProcessProfileBo profileBo = processDef.getBatchProcessProfileBo(); profileBo.setFileType(processDef.getOutputFormat()); if (response.getResults().getNumFound() > 0) resultMap = batchExport(profileBo); if (resultMap == null || resultMap[0].equals("0")) { if (start < response.getResults().getNumFound()) { getNextBatch(); } job.setStatus(JOB_STATUS_COMPLETED); } else { fileCount++; fileName = processDef.getBatchProcessProfileName() + "_" + fileCount; //bibDocList.add(XML_DEC); bibDocList.addAll((List<String>) resultMap[1]); processedRec = Integer.valueOf(resultMap[0].toString()); } if(!job.getStatus().equals(JOB_STATUS_RUNNING) && errBuilder.length()!=0){ job.setStatusDesc("Batch Completed with Errors :: See Error file for details"); } if(resultMap!=null){ if(resultMap[2]!=null) errBuilder.append(resultMap[2].toString()); if(resultMap[3]!=null) errCnt = resultMap[3].toString(); } } catch (Exception ex) { LOG.error("Error while getNextBatch operation", ex); job.setStatus(JOB_STATUS_STOPPED); throw ex; } } /** * methods creates the directories to write file to if they do not exist * if the user provided folder is not valid (cannot be created) then the default location is chosen * * @throws Exception */ @Override protected void prepareForWrite() throws Exception { try { fileName = processDef.getBatchProcessProfileName(); if (response.getResults().getNumFound() > processDef.getChunkSize()) { fileCount += (start / processDef.getChunkSize()); fileName = processDef.getBatchProcessProfileName() + "_" + fileCount; } String homeDirectory = getBatchProcessFilePath(processDef.getBatchProcessType()); if (StringUtils.isNotEmpty(processDef.getDestinationDirectoryPath())) { filePath = new File(processDef.getDestinationDirectoryPath() + FileSystems.getDefault().getSeparator() + job.getJobId()); } else if (filePath == null || !filePath.isDirectory()) { filePath = new File(homeDirectory + FileSystems.getDefault().getSeparator() + job.getJobId()); } if (filePath.isDirectory()) { //in case of paused and stopped status of job //job has already run and directory exists LOG.info("filePath :: " + filePath.getPath() + " ::already exists"); } else { if (filePath.mkdirs()) { // able to create directory for the given file path LOG.info("user given filePath :: " + filePath.getPath() + " ::created successfully"); } else { filePath = new File(homeDirectory + FileSystems.getDefault().getSeparator() + job.getJobId()); if (filePath.mkdirs()) LOG.info("default filePath :: " + filePath.getPath() + " ::created"); else { LOG.error("Cannot create output directory for the given file path:: " + filePath.getPath()); job.setStatus(JOB_STATUS_STOPPED); throw new RuntimeException("Cannot create output directory for the given file path:: " + filePath.getPath()); } } } job.setUploadFileName(filePath.getPath()); } catch (Exception ex) { LOG.error("Error while prepareForWrite operation", ex); job.setStatus(JOB_STATUS_STOPPED); throw ex; } } /** * Performs the batch write operation * Writes the data to marcxml or mrc format based on the output format specified in the process * * @throws Exception */ @Override protected void processBatch() throws Exception { int currSuccessRec = 0; int successRec = Integer.valueOf(job.getNoOfSuccessRecords()); int recordProcessed = Integer.valueOf(job.getNoOfRecordsProcessed()); int errRecords = Integer.valueOf(job.getNoOfFailureRecords()); int currErrCnt = Integer.valueOf(errCnt); if (processDef.getOutputFormat().equalsIgnoreCase(MARCXML)) { try { if (processedRec > 0) writeFileToLocation(); currSuccessRec = processedRec; } catch (Exception e) { LOG.error("Error while writing to file:: marcxml ::", e); job.setStatus(JOB_STATUS_STOPPED); job.setStatusDesc("Error while writing to marcxml file::" + fileName + EXT_MARCXML); currSuccessRec = 0; currErrCnt += processedRec; } } else if (processDef.getOutputFormat().equalsIgnoreCase(MARC)) { try { currSuccessRec = generateMarcFromXml(); currErrCnt += processedRec - currSuccessRec; } catch (Exception e) { LOG.error("Error while writing to file:: mrc ::", e); job.setStatus(JOB_STATUS_STOPPED); job.setStatusDesc("Error while writing to mrc file::" + fileName + EXT_MARC); } } try { writeErrorFile(); } catch (Exception ex) { LOG.error("Error while writing to error file", ex); job.setStatus(JOB_STATUS_STOPPED); } job.setNoOfRecordsProcessed(String.valueOf(recordProcessed + currSuccessRec + currErrCnt)); job.setNoOfFailureRecords(String.valueOf(errRecords + currErrCnt)); job.setNoOfSuccessRecords(String.valueOf(successRec + currSuccessRec)); LOG.info(job.getNoOfRecordsProcessed() + " ::records processed"); if (currErrCnt > 0) LOG.info(job.getNoOfFailureRecords() + " ::records failed"); } /** * Write the content read to mrcxml file * * @throws Exception */ private void writeFileToLocation() throws Exception { File file = new File(filePath + FileSystems.getDefault().getSeparator() + fileName + EXT_MARCXML); FileUtils.writeLines(file, "UTF-8", bibDocList); } /** * Writes the content read into a mrc file * * @throws Exception */ private int generateMarcFromXml() throws Exception { int successRec = 0; File fileToWrite = new File(filePath + FileSystems.getDefault().getSeparator() + fileName + EXT_MARC); FileOutputStream fileOutputStream = new FileOutputStream(fileToWrite); //String bibContent = StringUtils.join(bibDocList, ""); if (!fileToWrite.exists()) { if(fileToWrite.getParentFile().mkdirs() && fileToWrite.createNewFile()){ //do nothing } else{ LOG.error("Cannot create mrc file in the given file path :: "+fileToWrite.getPath()); job.setStatus(JOB_STATUS_STOPPED); throw new RuntimeException("Cannot create mrc file in the given file path :: "+fileToWrite.getPath()); } } MarcWriter writer = new MarcStreamWriter(fileOutputStream,"UTF-8"); for (String bibContent : bibDocList) { InputStream input = new ByteArrayInputStream(bibContent.getBytes()); Record record = null; OLEMarcReader marcXmlReader = new OLEMarcXmlReader(input); try { while (marcXmlReader.hasNext()) { if (marcXmlReader.hasErrors()) { marcXmlReader.next(); errBuilder.append(marcXmlReader.getError().toString()).append(lineSeparator); marcXmlReader.clearErrors(); continue; } record = marcXmlReader.next(); writer.write(record); successRec++; } } catch (Exception ex) { String recordId = getRecordId(record); LOG.error("Error while parsing MARCXML to mrc data:: " + (recordId == null ? "NULL_RECORD" : "record id:: " + recordId), ex); errBuilder.append(ERR_BIB).append(recordId == null ? "ERROR_RECORD" : recordId).append(TIME_STAMP) .append(new Date()).append(ERR_CAUSE).append(ex.getMessage()).append(" ::At:: ").append("generateMarcFromXml()").append(lineSeparator); } } writer.close(); return successRec; } /** * Converts the given date string to solr date format * // convert the format to yyyy-MM-dd'T'HH:mm:ss'Z' * * @param dateStr * @param isFrom * @return */ private String getSolrDate(String dateStr, boolean isFrom) throws ParseException { SimpleDateFormat solrDtFormat = new SimpleDateFormat(SOLR_DT_FORMAT); SimpleDateFormat userFormat = new SimpleDateFormat(FILTER_DT_FORMAT); try { if (isFrom) { Date date = userFormat.parse(dateStr); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), 0, 0, 0); return solrDtFormat.format(cal.getTime()); } else { Date date = userFormat.parse(dateStr); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), 23, 59, 59); return solrDtFormat.format(cal.getTime()); } } catch (ParseException e) { LOG.error("Error while parsing user entered date::" + dateStr, e); throw e; } } /** * loads the profile and checks for incremental export * * @param processDef */ @Override protected void loadProfile(OLEBatchProcessDefinitionDocument processDef) throws Exception { super.loadProfile(processDef); List<OLEBatchProcessProfileMappingOptionsBo> optionsBoList = processDef.getOleBatchProcessProfileBo().getOleBatchProcessProfileMappingOptionsList(); for (OLEBatchProcessProfileMappingOptionsBo bo : optionsBoList) { processDef.getOleBatchProcessProfileBo().getOleBatchProcessProfileDataMappingOptionsBoList().addAll(bo.getOleBatchProcessProfileDataMappingOptionsBoList()); } try { if (processDef.getOleBatchProcessProfileBo().getExportScope().equalsIgnoreCase(EXPORT_INC)) { String jobId_FL = "start_time"; Map<String, String> jobBoMap = new HashMap<>(); jobBoMap.put("bat_prfle_nm", processDef.getBatchProcessProfileName()); jobBoMap.put("status", JOB_STATUS_COMPLETED); List<OLEBatchProcessJobDetailsBo> jobDetailsBos = (List<OLEBatchProcessJobDetailsBo>) KRADServiceLocator.getBusinessObjectService().findMatchingOrderBy(OLEBatchProcessJobDetailsBo.class, jobBoMap, jobId_FL, true); Calendar cal = Calendar.getInstance(); if (jobDetailsBos == null) { lastExportDate = null; return; } switch (jobDetailsBos.size()) { case 0: lastExportDate = null; break; case 1: default: cal.setTime(jobDetailsBos.get(jobDetailsBos.size() - 1).getStartTime()); lastExportDate = getUTCTime(cal.getTime()); } LOG.info("Incremental export running for batch export profile :: " + processDef.getBatchProcessProfileName() + " :: with date ::" + lastExportDate); } } catch (Exception ex) { LOG.error("Error while retrieving job details for incremental export::"); throw ex; } } /** * gets the solr query based on the filter criteria and executed to retrieve the results * * @throws Exception */ private void performSolrQuery() throws Exception { try { if (solrQueryObj == null) { getSolrQuery(); if (!(processDef.getOleBatchProcessProfileBo().getExportScope().equalsIgnoreCase(EXPORT_FULL) || processDef.getOleBatchProcessProfileBo().getExportScope().equalsIgnoreCase(EXPORT_EX_STAFF))) { solrQueryObj.setFacet(true); solrQueryObj.setFacetMinCount(1); solrQueryObj.addFacetField(WorkInstanceCommonFields.BIB_IDENTIFIER); solrQueryObj.setFacetLimit(Integer.MAX_VALUE); response = SolrServerManager.getInstance().getSolrServer().query(solrQueryObj); FacetField facetFieldBib = response.getFacetField(WorkInstanceCommonFields.BIB_IDENTIFIER); if (facetFieldBib.getValues() == null) { if (response.getResults().getNumFound() == 0) { job.setTotalNoOfRecords("0"); } else { job.setTotalNoOfRecords(String.valueOf(response.getResults().getNumFound())); } return; } List<FacetField.Count> count = facetFieldBib.getValues(); job.setTotalNoOfRecords(String.valueOf(count.size())); } else { response = SolrServerManager.getInstance().getSolrServer().query(solrQueryObj); job.setTotalNoOfRecords(String.valueOf(response.getResults().getNumFound())); } LOG.info("Total number of records to be exported :: " + job.getTotalNoOfRecords()); } else { solrQueryObj.setStart(start); solrQueryObj.setFacet(false); response = SolrServerManager.getInstance().getSolrServer().query(solrQueryObj); job.setTotalNoOfRecords(String.valueOf(response.getResults().getNumFound())); } } catch (Exception e) { LOG.error("Error while performing solr query :: ", e); throw e; } } /** * converts the given date to UTC time * * @param date * @return * @throws ParseException */ private static Date getUTCTime(Date date) throws ParseException { DateFormat format = new SimpleDateFormat(SOLR_DT_FORMAT); format.setTimeZone(TimeZone.getTimeZone("UTC")); String utcStr = format.format(date); DateFormat format2 = new SimpleDateFormat(SOLR_DT_FORMAT); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.setTime(format2.parse(utcStr)); return cal.getTime(); } /** * gets the default search condition * * @return */ private SearchCondition getDefaultCondition() { SearchCondition condition = new SearchCondition(); condition.setSearchScope(AND); condition.setOperator(AND); return condition; } /** * Writes the error records to the path * * @throws Exception */ private void writeErrorFile() throws Exception { if (StringUtils.isNotEmpty(errBuilder.toString())) { File file = new File(filePath + FileSystems.getDefault().getSeparator() + processDef.getBatchProcessProfileName() + EXT_ERR_TXT); FileUtils.writeStringToFile(file, errBuilder.toString(), "UTF-8", true); } } /** * reads the filter criterias from the profile and sets the search params for solr query * * @param criteriaBos * @param params * @return * @throws ParseException */ private String getFilterCriteria(List<OLEBatchProcessProfileFilterCriteriaBo> criteriaBos, SearchParams params) throws ParseException { for (OLEBatchProcessProfileFilterCriteriaBo bo : criteriaBos) { if (processDef.getOleBatchProcessProfileBo().getExportScope().equalsIgnoreCase(EXPORT_INC) && bo.getFilterFieldName().equalsIgnoreCase((WorkBibCommonFields.DATE_UPDATED))) { continue;// do not add dateUpdated in params even if its present in the filter as it will be taken from last job run of the same profile } SearchCondition condition = getDefaultCondition(); condition.setDocField(bo.getFilterFieldName()); if (StringUtils.isNotEmpty(bo.getFilterFieldValue())) { // one value Map<String, String> filterMap = new HashMap<>(); filterMap.put("ole_bat_field_nm", bo.getFilterFieldName()); Collection<OLEBatchProcessFilterCriteriaBo> filterBo = KRADServiceLocator.getBusinessObjectService().findMatching(OLEBatchProcessFilterCriteriaBo.class, filterMap); if (filterBo.iterator().hasNext()){ if (filterBo.iterator().next().getFieldType().equalsIgnoreCase("date")) { condition.setSearchText("[" + getSolrDate(bo.getFilterFieldValue(), true) + " TO " + getSolrDate(bo.getFilterFieldValue(), false) + "]"); condition.setSearchScope(NONE); condition.setFieldType(RANGE); } else { condition.setSearchText(bo.getFilterFieldValue()); } } else { try { InstanceMappingHelper instanceMappingHelper = new InstanceMappingHelper(); String filterFieldNameTag = instanceMappingHelper.getTagForExportFilter(bo.getFilterFieldName()); String filterFieldNameCode = instanceMappingHelper.getCodeForExportFilter(bo.getFilterFieldName()); if(StringUtils.isEmpty(filterFieldNameTag) || StringUtils.isEmpty(filterFieldNameCode)){ condition.setDocField(bo.getFilterFieldName()); } else { String docField = filterFieldNameTag + filterFieldNameCode; condition.setDocField(docField); } } catch (StringIndexOutOfBoundsException e) { condition.setDocField(bo.getFilterFieldName()); } condition.setSearchText(bo.getFilterFieldValue()); } } else if (StringUtils.isNotEmpty(bo.getFilterRangeFrom()) && StringUtils.isNotEmpty(bo.getFilterRangeTo())) { // range values condition.setFieldType(RANGE); condition.setSearchScope(NONE); Map<String, String> filterMap = new HashMap<>(); filterMap.put("ole_bat_field_nm", bo.getFilterFieldName()); Collection<OLEBatchProcessFilterCriteriaBo> filterBo = KRADServiceLocator.getBusinessObjectService().findMatching(OLEBatchProcessFilterCriteriaBo.class, filterMap); if (!filterBo.iterator().hasNext()) return ""; if (filterBo.iterator().next().getFieldType().equalsIgnoreCase("date")) { condition.setSearchText("[" + getSolrDate(bo.getFilterRangeFrom(), true) + " TO " + getSolrDate(bo.getFilterRangeTo(), false) + "]"); } else { condition.setSearchText("[" + bo.getFilterRangeFrom() + " TO " + bo.getFilterRangeTo() + "]"); } } else if (StringUtils.isNotEmpty(bo.getFilterRangeFrom()) && StringUtils.isEmpty(bo.getFilterRangeTo())) { // range values condition.setFieldType(RANGE); condition.setSearchScope(NONE); Map<String, String> filterMap = new HashMap<>(); filterMap.put("ole_bat_field_nm", bo.getFilterFieldName()); Collection<OLEBatchProcessFilterCriteriaBo> filterBo = KRADServiceLocator.getBusinessObjectService().findMatching(OLEBatchProcessFilterCriteriaBo.class, filterMap); if (!filterBo.iterator().hasNext()) return ""; if (filterBo.iterator().next().getFieldType().equalsIgnoreCase("date")) { condition.setSearchText("[" + getSolrDate(bo.getFilterRangeFrom(), true) + " TO NOW]"); } else { condition.setSearchText("[" + bo.getFilterRangeFrom() + " TO *]"); } } //to check if bib status or local id is present in the filter criteria, then select only the bib records by setting export type as full if (bo.getFilterFieldName().equalsIgnoreCase(WorkBibCommonFields.LOCALID_SEARCH) || bo.getFilterFieldName().equalsIgnoreCase(WorkBibCommonFields.STATUS_SEARCH) || (StringUtils.isNotEmpty(processDef.getBatchProcessProfileBo().getDataToExport()) && processDef.getBatchProcessProfileBo().getDataToExport().equalsIgnoreCase(EXPORT_BIB_ONLY))) { processDef.getOleBatchProcessProfileBo().setExportScope(EXPORT_FULL); params.setDocFormat(DocFormat.MARC.getDescription()); params.setDocType(DocType.BIB.getDescription()); if(bo.getFilterFieldName().equalsIgnoreCase(WorkBibCommonFields.STATUS_SEARCH)) condition.setSearchScope(OR); } params.getSearchFieldsList().add(condition); } return ""; } /** * returns the record id - local identifier of the record * * @param record * @return */ private String getRecordId(Record record) { if (record == null || record.getControlFields() == null || record.getControlFields().isEmpty() || record.getControlFields().size() < 2) return null; if (record.getControlFields().get(1) == null) return null; VariableField field = (VariableField) record.getControlFields().get(1); if (field instanceof ControlField) { return ((ControlField) field).getData(); } else { return null; } } }
import java.awt.AWTException; import java.awt.datatransfer.UnsupportedFlavorException; import utilities.XlsxGenerator; import java.io.*; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import utilities.DMPORosterToMapGenerator; import utilities.GlobalVar; import utilities.NPDListFinder; import utilities.PrintLES; import utilities.RCFRosterToMapGenerator; /* * 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. */ /** * * @author SPC Cui */ public class NewJFrame extends javax.swing.JFrame { private String RCFRosterFile = null; private String DMPORosterFile = null; // private static String SSN_FILE_NAME = "roster.txt"; /** * Creates new form NewJFrame */ public NewJFrame() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { RCF_Roster = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); selectRCFButton = new javax.swing.JButton(); selectDMPObutton = new javax.swing.JButton(); submitButton = new javax.swing.JButton(); RCFfileDir = new javax.swing.JLabel(); DMPOfileDir = new javax.swing.JLabel(); fileWarningMsg = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); RCF_Roster.setText("RCF Roster"); jLabel2.setText("DMPO Roster"); selectRCFButton.setText("Select"); selectRCFButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { selectRCFButtonActionPerformed(evt); } }); selectDMPObutton.setText("Select"); selectDMPObutton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { selectDMPObuttonActionPerformed(evt); } }); submitButton.setText("Submit"); submitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { submitButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(submitButton) .addGap(63, 63, 63)) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2) .addComponent(RCF_Roster)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(selectRCFButton) .addComponent(selectDMPObutton)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(fileWarningMsg) .addComponent(DMPOfileDir) .addComponent(RCFfileDir)) .addContainerGap(414, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(72, 72, 72) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(RCF_Roster) .addComponent(selectRCFButton) .addComponent(RCFfileDir)) .addGap(52, 52, 52) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(selectDMPObutton) .addComponent(DMPOfileDir)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 79, Short.MAX_VALUE) .addComponent(submitButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(fileWarningMsg) .addGap(22, 22, 22)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void selectRCFButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectRCFButtonActionPerformed String dir = getHomeDirectory(); System.out.println(dir); final JFileChooser fc = new JFileChooser(dir); FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx","xlsx"); fc.setFileFilter(filter); fc.setDialogTitle("Please select a RCF roster..."); //fc.setCurrentDirectory(new File("C:\\Users\\bob\\Desktop\\p.txt")); int response = fc.showOpenDialog(this); String fileName; if (response == JFileChooser.APPROVE_OPTION) { fileName = fc.getSelectedFile().toString(); RCFRosterFile = fileName; RCFfileDir.setText(fileName); } }//GEN-LAST:event_selectRCFButtonActionPerformed // return directory where the program is located private String getHomeDirectory() { ClassLoader loader = NewJFrame.class.getClassLoader(); //System.out.println(loader.toString()); String dir = loader.getResource("NewJFrame.class").toString(); dir = dir.replace("file:/",""); dir = dir.replace("jar:",""); dir = dir.replace("/RosterCombine.jar!",""); dir = dir.replace("/NewJFrame.class",""); dir = dir.replace("/build/classes",""); return dir; } private void clearAllTexts() { fileWarningMsg.setText(""); RCFfileDir.setText(""); DMPOfileDir.setText(""); } private void selectDMPObuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectDMPObuttonActionPerformed String dir = getHomeDirectory(); final JFileChooser fc = new JFileChooser(dir); FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xlsx","xlsx"); fc.setFileFilter(filter); fc.setDialogTitle("Please select a DMPO roster..."); int response = fc.showOpenDialog(this); String fileName; if (response == JFileChooser.APPROVE_OPTION) { fileName = fc.getSelectedFile().toString(); DMPORosterFile = fileName; DMPOfileDir.setText(fileName); } }//GEN-LAST:event_selectDMPObuttonActionPerformed // private void DMPOxlsxToMapGenerator(String xlsxFileName, MyDate cutoffDate) throws FileNotFoundException, IOException { // File myFile = new File(xlsxFileName); // FileInputStream fis = new FileInputStream(myFile); // XSSFWorkbook myWorkBook = new XSSFWorkbook(fis); // } private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitButtonActionPerformed if (RCFRosterFile != null && DMPORosterFile != null) { fileWarningMsg.setText(""); try { DMPORosterToMapGenerator dmpo = new DMPORosterToMapGenerator(DMPORosterFile); RCFRosterToMapGenerator rcf = new RCFRosterToMapGenerator(RCFRosterFile); NPDListFinder npd = new NPDListFinder(rcf.rosterGenerator()); // pass in a list of all ssn on RCF roster List<String> npdList = npd.getNPDList(); // find the LES not available list List<String> ssnList = rcf.rosterGenerator(); // generate a list of all SSN in RCF roster, roster.txt List<String> lesList4Printing = rcf.lesSSNList(GlobalVar.CUT_OFF); // ssnList.removeAll(lesList4Printing); // those are not for printing LES PrintLES pLes = new PrintLES(lesList4Printing); List<String> LesNAListInDJMS = pLes.getLESnotProcdSSNList(); ssnList.addAll(LesNAListInDJMS); List<String> LesNAList = ssnList; // LES not avilable // printing not processed ssn into the file PrintStream output = new PrintStream(new File(GlobalVar.UNPROCESSED_SSN_FILE_NAME)); for (String ssn : LesNAList) { output.println(ssn); } // end of find the LES not available list // find the LES not available list XlsxGenerator xg = new XlsxGenerator(dmpo.getDb(), rcf.getDb(), npdList, LesNAList); JOptionPane.showMessageDialog(null, "The NPD report is generated successfully!"); } catch (IOException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Fail to generate the report!"); } catch (ParseException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Fail to generate the report!"); } catch (UnsupportedFlavorException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (AWTException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); } } else if (RCFRosterFile == null && DMPORosterFile == null){ fileWarningMsg.setText("Neither RCF nor DMPO file is not selected!"); } else if (RCFRosterFile == null) { fileWarningMsg.setText("RCF file is not selected!"); } else { //if (DMPORosterFile == null) { fileWarningMsg.setText("DMPO file is not selected!"); } }//GEN-LAST:event_submitButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel DMPOfileDir; private javax.swing.JLabel RCF_Roster; private javax.swing.JLabel RCFfileDir; private javax.swing.JLabel fileWarningMsg; private javax.swing.JLabel jLabel2; private javax.swing.JButton selectDMPObutton; private javax.swing.JButton selectRCFButton; private javax.swing.JButton submitButton; // End of variables declaration//GEN-END:variables }
package main.java.algorithms.bpp; import java.util.ArrayList; import java.util.Collections; import main.java.algorithms.BPPAlgorithm; import main.java.main.product.Box; import main.java.main.product.Product; public class BruteForce extends BPPAlgorithm { public ArrayList<Box> getBoxes(ArrayList<Product> products, int boxVolume) { ArrayList<Product> productList1 = new ArrayList<>(); ArrayList<Product> productList2 = new ArrayList<>(); productList1.addAll(0, products.subList(0, (products.size() / 2))); productList2.addAll(0, products.subList((products.size() / 2), products.size())); returnBoxes.clear(); int currentBoxAmount; int bestBoxAmount = products.size() + 1; // loop through all possibilities for (int i = 0; i < factorial(products.size()); i++) { // currentBoxAmount contains the amount products sorted in their // current order. currentBoxAmount = sortProducts(products, boxVolume).size(); // check if the amount is less than the current optimal amount if (currentBoxAmount < bestBoxAmount) { // if yes then returnBoxes becomes the product sorted in their // current order. returnBoxes = sortProducts(products, boxVolume); // set a new best box amount bestBoxAmount = currentBoxAmount; } // rotate one product one place ahead, so we test all possible // locations in both sublists. Collections.rotate(productList1.subList(1, 2), -1); Collections.rotate(productList2.subList(1, 2), -1); // rotate all products one place ahead so all possible combinations // get tested. Collections.rotate(productList1, 1); Collections.rotate(productList2, 1); // merge productlist products.clear(); products.addAll(productList1); products.addAll(productList2); } return returnBoxes; } // sortproducts method, literally sorts products private static ArrayList<Box> sortProducts(ArrayList<Product> products, int boxVolume) { // arraylist to return ArrayList<Box> sortedBoxes = new ArrayList<>(); // boolean for checking if a product is already in a box boolean doesFit = false; for (Product product : products) { // loop through existing boxes for (Box currentBox : sortedBoxes) { // does it fit in box? yes: add product if (currentBox.checkFit((int) product.GetSize()) && !doesFit) { currentBox.addProduct(product); doesFit = true; } } // boolean doesFit false? : create new box and add product if (!doesFit) { Box newBox = new Box(boxVolume); sortedBoxes.add(newBox); newBox.addProduct(product); } doesFit = false; } return sortedBoxes; } private static int factorial(int n) { int factorial = 1; for (int i = 1; i <= n; i++) { factorial = factorial * i; } return factorial; } }
package com.forever.registry; import com.forever.protocol.ProtocolEntity; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Description: * @Author: zhang * @Date: 2019/6/18 */ public class RegistryHandler extends ChannelInboundHandlerAdapter { private List<String> classNames = new ArrayList<String>(); private Map<String, Object> registryMap = new HashMap<String, Object>(); public RegistryHandler(){ scannerClass("com.forever.serviceimpl"); registry(); } private void registry() { if(classNames.isEmpty()){ return; } for (String className: classNames) { try { Class<?> clazz = Class.forName(className); Class<?> i = clazz.getInterfaces()[0]; registryMap.put(i.getName(), clazz.newInstance()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } } } private void scannerClass(String packageName) { URL url = this.getClass().getResource("/"+packageName.replaceAll("\\.", "/")); File file = new File(url.getFile()); for(File f : file.listFiles()){ if(f.isDirectory()){ scannerClass(packageName + "." + f.getName()); }else{ classNames.add(packageName+"."+f.getName().replaceAll(".class","").trim()); } } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Object result = new Object(); ProtocolEntity request = (ProtocolEntity)msg; if(registryMap.containsKey(request.getClassName())){ Object clazz = registryMap.get(request.getClassName()); Method method = clazz.getClass().getMethod(request.getMethodName(), request.getParamsType()); result = method.invoke(clazz, request.getPrarams()); } ctx.write(result); ctx.flush(); ctx.close(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); System.out.println("server is Exception"); } }
package edu.cricket.api.cricketscores; import com.cricketfoursix.cricketdomain.aggregate.GameAggregate; import edu.cricket.api.cricketscores.rest.response.MatchCommentary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @EnableScheduling @SpringBootApplication @ComponentScan(basePackages = {"com.cricketfoursix", "edu.cricket.api.cricketscores"}) public class CricketScoresApplication { private static final Logger log = LoggerFactory.getLogger(CricketScoresApplication.class); @Bean @Order(Ordered.HIGHEST_PRECEDENCE) @Qualifier("preGames") public Map<Long,Long> preGames(){ return new ConcurrentHashMap<>(); } @Bean @Order(Ordered.HIGHEST_PRECEDENCE) @Qualifier("liveGames") public Map<Long,Long> liveGames(){ return new ConcurrentHashMap<>(); } @Bean @Order(Ordered.HIGHEST_PRECEDENCE) @Qualifier("postGames") public Map<Long,Long> postGames(){ return new ConcurrentHashMap<>(); } @Bean @Order(Ordered.HIGHEST_PRECEDENCE) @Qualifier("liveGamesCache") public Map<Long, GameAggregate> liveGamesCache(){ return new ConcurrentHashMap<>(); } @Bean @Order(Ordered.HIGHEST_PRECEDENCE) @Qualifier("eventsCommsCache") public Map<Long,MatchCommentary> eventsCommsCache(){ return new ConcurrentHashMap<>(); } @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(8); executor.setMaxPoolSize(8); executor.setThreadNamePrefix("cricket_consumer_thread"); executor.initialize(); return executor; } public static void main(String[] args) { SpringApplication.run(CricketScoresApplication.class, args); } }
package projetZoo; import java.util.LinkedList; public class Zoo { private static Zoo z = new Zoo();//Singleton private Zoo() { } private LinkedList<Cage> cages = new LinkedList<Cage>(); private LinkedList<Cabane> cabanes = new LinkedList<Cabane>(); private LinkedList<Animal> animaux = new LinkedList<Animal>(); private Piscine piscine ; public LinkedList<Cage> getCages() { return cages; } public LinkedList<Cabane> getCabanes() { return cabanes; } public LinkedList<Animal> getAnimaux() { return animaux; } //........................ajouter et supp........................ public void ajouterAnimal(Animal a) { this.getAnimaux().add(a); } public void supprimer(Animal a) { this.getAnimaux().remove(a); } //...........................affiche des info...................... public Piscine getPiscine() { return piscine; } public void setPiscine(Piscine piscine) { this.piscine = piscine; } //...........................nbr d'animaux................ public int nbAnimaux() { return this.getAnimaux().size(); } public void afficherInfos() { System.out.print("zoo heberge " + this.nbAnimaux() + "animaux." + "\n"); } //design pattern Singleton public static Zoo getInstance() { return z; } }
package com.xantrix.webapp.service; import java.util.List; import java.util.Optional; import com.xantrix.webapp.entities.DettPromo; public interface DettPromoService { Optional<DettPromo> SelDettPromo(long Id); List<DettPromo> SelDettPromoByCodFid(String CodFid); void InsDettPromo(DettPromo dettPromo); void UpdDettPromo(Long Id, String Oggetto); void DelRowPromo(Long Id); }
package learn.sprsec.ssia0502context; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @SpringBootTest @AutoConfigureMockMvc class Ssia0502contextApplicationTests { @Autowired private MockMvc mvc; @Test @DisplayName("Test calling /hello endpoint without authentication returns unauthorized.") void helloUnauthenticated() throws Exception { mvc.perform(get("/hello")) .andExpect(status().isUnauthorized()); } @Test @DisplayName("Test calling /hello endpoint authenticated with a mock user returns ok.") @WithMockUser void helloAuthenticated() throws Exception { mvc.perform(get("/hello")) .andExpect(content().string("Hello!")) .andExpect(status().isOk()); } }
package com.ucl.common.logger; import org.apache.logging.log4j.Level; /** * 日志接口 * Created by jiang.zheng on 2017/10/9. */ public interface Logger { // debug /** * Logs a message object with the {@link Level#DEBUG DEBUG} level. * * @param message the message object to log. */ void debug(Object message); /** * Logs a message at the {@link Level#DEBUG DEBUG} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message to log. * @param t the exception to log, including its stack trace. */ void debug(Object message, Throwable t); /** * Logs a message object with the {@link Level#DEBUG DEBUG} level. * * @param message the message string to log. */ void debug(String message); /** * Logs a message with parameters at the {@link Level#DEBUG DEBUG} level. * * @param message the message to log; the format depends on the message factory. * @param params parameters to the message. * @see #getMessageFactory() */ void debug(String message, Object... params); /** * Logs a message at the {@link Level#DEBUG DEBUG} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message to log. * @param t the exception to log, including its stack trace. */ void debug(String message, Throwable t); // info /** * Logs a message object with the {@link Level#INFO INFO} level. * * @param message the message object to log. */ void info(Object message); /** * Logs a message at the {@link Level#INFO INFO} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message object to log. * @param t the exception to log, including its stack trace. */ void info(Object message, Throwable t); /** * Logs a message object with the {@link Level#INFO INFO} level. * * @param message the message string to log. */ void info(String message); /** * Logs a message with parameters at the {@link Level#INFO INFO} level. * * @param message the message to log; the format depends on the message factory. * @param params parameters to the message. * @see #getMessageFactory() */ void info(String message, Object... params); /** * Logs a message at the {@link Level#INFO INFO} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message object to log. * @param t the exception to log, including its stack trace. */ void info(String message, Throwable t); // warn /** * Logs a message object with the {@link Level#WARN WARN} level. * * @param message the message object to log. */ void warn(Object message); /** * Logs a message at the {@link Level#WARN WARN} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message object to log. * @param t the exception to log, including its stack trace. */ void warn(Object message, Throwable t); /** * Logs a message object with the {@link Level#WARN WARN} level. * * @param message the message string to log. */ void warn(String message); /** * Logs a message with parameters at the {@link Level#WARN WARN} level. * * @param message the message to log; the format depends on the message factory. * @param params parameters to the message. * @see #getMessageFactory() */ void warn(String message, Object... params); /** * Logs a message at the {@link Level#WARN WARN} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message object to log. * @param t the exception to log, including its stack trace. */ void warn(String message, Throwable t); // Error /** * Logs a message object with the {@link Level#ERROR ERROR} level. * * @param message the message object to log. */ void error(Object message); /** * Logs a message at the {@link Level#ERROR ERROR} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message object to log. * @param t the exception to log, including its stack trace. */ void error(Object message, Throwable t); /** * Logs a message object with the {@link Level#ERROR ERROR} level. * * @param message the message string to log. */ void error(String message); /** * Logs a message with parameters at the {@link Level#ERROR ERROR} level. * * @param message the message to log; the format depends on the message factory. * @param params parameters to the message. * @see #getMessageFactory() */ void error(String message, Object... params); /** * Logs a message at the {@link Level#ERROR ERROR} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message object to log. * @param t the exception to log, including its stack trace. */ void error(String message, Throwable t); // fatal /** * Logs a message object with the {@link Level#FATAL FATAL} level. * * @param message the message object to log. */ void fatal(Object message); /** * Logs a message at the {@link Level#FATAL FATAL} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message object to log. * @param t the exception to log, including its stack trace. */ void fatal(Object message, Throwable t); /** * Logs a message object with the {@link Level#FATAL FATAL} level. * * @param message the message string to log. */ void fatal(String message); /** * Logs a message with parameters at the {@link Level#FATAL FATAL} level. * * @param message the message to log; the format depends on the message factory. * @param params parameters to the message. * @see #getMessageFactory() */ void fatal(String message, Object... params); /** * Logs a message at the {@link Level#FATAL FATAL} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message object to log. * @param t the exception to log, including its stack trace. */ void fatal(String message, Throwable t); // trace /** * Logs a message object with the {@link Level#TRACE TRACE} level. * * @param message the message object to log. */ void trace(Object message); /** * Logs a message at the {@link Level#TRACE TRACE} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message object to log. * @param t the exception to log, including its stack trace. * @see #debug(String) */ void trace(Object message, Throwable t); /** * Logs a message object with the {@link Level#TRACE TRACE} level. * * @param message the message string to log. */ void trace(String message); /** * Logs a message with parameters at the {@link Level#TRACE TRACE} level. * * @param message the message to log; the format depends on the message factory. * @param params parameters to the message. * @see #getMessageFactory() */ void trace(String message, Object... params); /** * Logs a message at the {@link Level#TRACE TRACE} level including the stack trace of the {@link Throwable} * <code>t</code> passed as parameter. * * @param message the message object to log. * @param t the exception to log, including its stack trace. * @see #debug(String) */ void trace(String message, Throwable t); // isEnable /** * Checks whether this Logger is enabled for the {@link Level#DEBUG DEBUG} Level. * * @return boolean - {@code true} if this Logger is enabled for level DEBUG, {@code false} otherwise. */ boolean isDebugEnabled(); /** * Checks whether this Logger is enabled for the {@link Level#INFO INFO} Level. * * @return boolean - {@code true} if this Logger is enabled for level INFO, {@code false} otherwise. */ boolean isInfoEnabled(); /** * Checks whether this Logger is enabled for the {@link Level#WARN WARN} Level. * * @return boolean - {@code true} if this Logger is enabled for level {@link Level#WARN WARN}, {@code false} * otherwise. */ boolean isWarnEnabled(); /** * Checks whether this Logger is enabled for the {@link Level#ERROR ERROR} Level. * * @return boolean - {@code true} if this Logger is enabled for level {@link Level#ERROR ERROR}, {@code false} * otherwise. */ boolean isErrorEnabled(); /** * Checks whether this Logger is enabled for the {@link Level#TRACE TRACE} level. * * @return boolean - {@code true} if this Logger is enabled for level TRACE, {@code false} otherwise. */ boolean isTraceEnabled(); /** * Checks whether this Logger is enabled for the {@link Level#FATAL FATAL} Level. * * @return boolean - {@code true} if this Logger is enabled for level {@link Level#FATAL FATAL}, {@code false} * otherwise. */ boolean isFatalEnabled(); }
/* * 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 dialogos_project.alexa; import com.amazon.ask.dispatcher.request.handler.HandlerInput; import com.amazon.ask.model.Intent; import com.amazon.ask.model.IntentRequest; import com.amazon.ask.model.Slot; import com.clt.diamant.ExecutionLogger; import com.clt.diamant.ExecutionStoppedException; import com.clt.diamant.IdMap; import com.clt.diamant.InputCenter; import com.clt.diamant.WozInterface; import com.clt.diamant.graph.Edge; import com.clt.diamant.graph.Graph; import com.clt.diamant.graph.Node; import com.clt.diamant.suspend.SuspendingNode; import com.clt.diamant.graph.nodes.AbstractInputNode.EdgeManager; import com.clt.diamant.graph.nodes.AbstractInputNode.PatternTable; import com.clt.diamant.graph.nodes.NodeExecutionException; import com.clt.diamant.graph.nodes.TimeoutEdge; import com.clt.diamant.graph.ui.EdgeConditionModel; import com.clt.diamant.gui.NodePropertiesDialog; import com.clt.diamant.gui.SilentInputWindow; import com.clt.gui.GUI; import com.clt.script.exp.Expression; import com.clt.script.exp.Match; import com.clt.script.exp.Pattern; import com.clt.script.exp.Value; import com.clt.script.exp.values.StringValue; import com.clt.script.exp.values.StructValue; import com.clt.xml.XMLReader; import com.clt.xml.XMLWriter; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JTextField; import org.xml.sax.SAXException; /** * * @author koller */ public class AlexaInputNode extends SuspendingNode<String, HandlerInput> { private static final String TIMEOUT_PROPERTY = "timeout"; private static final String PROMPT_PROPERTY = "prompt"; private EdgeManager edgeManager = new EdgeManager(this, TIMEOUT_PROPERTY); public AlexaInputNode() { /* important that some value is set (must not be one of Boolean values, not null later) */ this.setProperty(TIMEOUT_PROPERTY, null); this.setProperty("background", Boolean.FALSE); this.setProperty(PROMPT_PROPERTY, "\"\""); } public static String getNodeTypeName(Class<?> c) { return "Alexa Input"; } @Override public Node execute(WozInterface wi, InputCenter ic, ExecutionLogger el) { String prompt = evaluatePromptExpression(PROMPT_PROPERTY); Value intentStruct = null; boolean testMode = getSettings().isTestMode(); if (testMode) { // in testing mode, read string from popup window String s = SilentInputWindow.getString(null, "Alexa input node", prompt); if (s == null) { throw new ExecutionStoppedException(); // user wants to abort dialog } intentStruct = makeStructFromTypedString(s); } else { // otherwise, emit prompt to Alexa, then suspend the dialog // and wait for callback from Alexa HandlerInput inputValue = receiveAsynchronousInput(prompt); // AlexaPluginSettings settings = (AlexaPluginSettings) getPluginSettings(Plugin.class); // runtime.setMostRecentHandlerInput(inputValue); if (inputValue.getRequest() instanceof IntentRequest) { IntentRequest req = (IntentRequest) inputValue.getRequest(); System.err.println("Alexa input node received: " + req.getIntent()); intentStruct = makeIntentStruct(req.getIntent()); } else { throw new NodeExecutionException(this, "Received an invalid request from Alexa: " + inputValue.getRequest()); } } if (intentStruct != null) { List<Edge> edges = new ArrayList<>(edges()); Pattern[] patterns = createPatterns(edges); for (int i = 0; i < patterns.length; i++) { Match m = patterns[i].match(intentStruct); if (m != null) { setVariablesAccordingToMatch(m); return getEdge(i).getTarget(); } } } throw new NodeExecutionException(this, "Don't know how to handle Alexa intent: " + intentStruct); } private static Value makeIntentStruct(Intent intent) { Map<String, Value> struct = new HashMap<>(); struct.put("INTENT", new StringValue(intent.getName())); if (intent.getSlots() != null) { for (String slotName : intent.getSlots().keySet()) { Slot slot = intent.getSlots().get(slotName); if (slot.getValue() != null) { struct.put(slotName, new StringValue(slot.getValue())); } } } return new StructValue(struct); } private Value makeStructFromTypedString(String s) { if (s.trim().startsWith("{")) { try { return parseExpression(s).evaluate(); } catch (Exception ex) { Logger.getLogger(AlexaInputNode.class.getName()).log(Level.SEVERE, null, ex); return new StructValue(); } } else { Map<String, Value> struct = new HashMap<>(); struct.put("INTENT", new StringValue(s)); return new StructValue(struct); } } // copied from AbstractInputNode private Pattern[] createPatterns(List<Edge> edges) { final Pattern[] patterns = new Pattern[edges.size()]; int n = 0; for (int i = 0; i < edges.size(); i++) { Edge e = edges.get(i); if (!(e instanceof TimeoutEdge)) { try { patterns[n] = parsePattern(e.getCondition()); // allow pattern-matching } catch (Exception exn) { throw new NodeExecutionException(this, com.clt.diamant.Resources.getString("IllegalPattern") + ": " + e.getCondition(), exn); } n++; } } return patterns; } @Override public void updateEdges() { edgeManager.updateEdges(); } @Override public boolean editProperties(Component parent) { TimeoutEdge timeoutEdge = edgeManager.updateEdgeProperty(); boolean approved = super.editProperties(parent); if (approved) { edgeManager.reinstallEdgesFromProperty(timeoutEdge); return true; } else { return false; } } /** * retrieve the settings from the dialog graph (which is where they are * stored -- not within Plugin!) */ private AlexaPluginSettings getSettings() { if (getGraph() != null && getGraph().getOwner() != null) { return ((AlexaPluginSettings) getGraph().getOwner().getPluginSettings(Plugin.class)); } else { return null; } } @Override public JComponent createEditorComponent(Map<String, Object> properties) { JTabbedPane tabs = GUI.createTabbedPane(); // populate Input panel JPanel inputTab = new JPanel(new BorderLayout(6, 0)); tabs.addTab("Input", inputTab); // TODO localize final EdgeConditionModel edgeModel = new EdgeConditionModel(this, properties, "Intent patterns"); // TODO localize final PatternTable patternTable = new PatternTable(edgeModel); inputTab.add(patternTable); // populate Output panel JPanel outputTab = new JPanel(new GridBagLayout()); tabs.addTab("Output", outputTab); // TODO localize GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = gbc.gridy = 0; gbc.fill = GridBagConstraints.NONE; gbc.insets = new Insets(3, 3, 3, 3); gbc.anchor = GridBagConstraints.EAST; outputTab.add(new JLabel("Prompt:"), gbc); gbc.anchor = GridBagConstraints.WEST; gbc.gridx++; final JTextField tf = NodePropertiesDialog.createTextField(properties, PROMPT_PROPERTY); outputTab.add(tf, gbc); return tabs; } @Override protected void writeAttributes(XMLWriter out, IdMap uid_map) { super.writeAttributes(out, uid_map); String prompt = (String) this.getProperty(PROMPT_PROPERTY); if (prompt != null) { Graph.printAtt(out, PROMPT_PROPERTY, prompt); } } @Override protected void readAttribute(XMLReader r, String name, String value, IdMap uid_map) throws SAXException { if (name.equals(PROMPT_PROPERTY)) { setProperty(PROMPT_PROPERTY, value); } } @Override public void writeVoiceXML(XMLWriter writer, IdMap idmap) throws IOException { } private String evaluatePromptExpression(String property) { String promptProp = (String) getProperty(property); try { Expression expr = parseExpression(promptProp); Value promptV = expr.evaluate(); return ((StringValue) promptV).getString(); } catch (Exception ex) { Logger.getLogger(AlexaOutputNode.class.getName()).log(Level.SEVERE, null, ex); return null; } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Interfaces; /** * * @author YNZ */ public class Aloe implements CharSequence { String str; public Aloe(){ this.str = "this is a test string!"; } public Aloe(String str) { this.str = str; } @Override public int length() { return this.str.length(); } @Override public char charAt(int index) { return this.str.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return this.str.substring(start, end); } }
package io.flood.rpc; import com.google.protobuf.RpcController; import com.google.protobuf.ServiceException; import java.util.concurrent.CountDownLatch; /** * Created by Administrator on 2015/11/4. */ public class RpcMain { public static void main(String[] args) { RpcTest.RpcService.BlockingInterface impl=new RpcTest.RpcService.BlockingInterface(){ public RpcTest.Resp doWork(RpcController controller, RpcTest.Req request) throws ServiceException { try{ Thread.sleep(800); }catch (Exception e){ } return RpcTest.Resp.newBuilder().setMessage(request.getMethdName()+"-"+request.getVersion()).build(); } }; FloodManager factory= FloodManager.getInstance(); try { factory.registService(RpcTest.RpcService.newReflectiveBlockingService(impl)); } catch (Exception e) { e.printStackTrace(); } factory.startRpcServer("10.51.67.119",8989,5); CountDownLatch cd=new CountDownLatch(5); try{ cd.await(); }catch (Exception e){ } } }
package com.mycompany.interacciondb; /** * * @author elias */ public class Ingreso { private String admNom,email,admApat,admAmat,admContra; private Integer id,status; public Ingreso(){ } public Ingreso(Integer id,String email, String admNom, String admApat, String admAmat, String admContra ,int status){ this.admAmat= admAmat; this.admApat= admApat; this.admContra= admContra; this.admNom= admNom; this.id=id; this.email= email; this.status= status; } /** * @return the admNom */ public String getAdmNom() { return admNom; } /** * @param admNom the admNom to set */ public void setAdmNom(String admNom) { this.admNom = admNom; } /** * @return the admApat */ public String getAdmApat() { return admApat; } /** * @param admApat the admApat to set */ public void setAdmApat(String admApat) { this.admApat = admApat; } /** * @return the admAmat */ public String getAdmAmat() { return admAmat; } /** * @param admAmat the admAmat to set */ public void setAdmAmat(String admAmat) { this.admAmat = admAmat; } /** * @return the admContra */ public String getAdmContra() { return admContra; } /** * @param admContra the admContra to set */ public void setAdmContra(String admContra) { this.admContra = admContra; } //Metodo para obtener el nombre del usuario public String getnombre(){ return admNom+" "+ admApat+ " "+ admAmat; } public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the status */ public Integer getStatus() { return status; } /** * @param status the status to set */ public void setStatus(Integer status) { this.status = status; } }
package com.octave.service.user.impl; import com.octave.entity.User; import com.octave.service.user.UserService; import com.octave.util.regex.CheckRegEx; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; /** * Created by Paosin Von Scarlet on 2017/10/13. */ @RunWith(SpringRunner.class) @SpringBootTest public class UserServiceImplTest { @Autowired UserService userService; @Test public void save() throws Exception { User user = new User(); user.setUserName("123456"); user.setPassword("123456"); user.setEmail("123456@qq.com"); user.setTel("15608185191"); System.out.println("check result-------------"+CheckRegEx.check(user)); } }
package ru.job4j.testing; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; /** * Класс UserService. * * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2018-12-26 * @since 2017-11-26 */ public class UserService { /** * Драйвер бд. */ private DBDriver db; /** * Кодировка. */ private String enc; /** * RoleService. */ private RoleService rls; /** * Конструктор. */ UserService() { this.db = DBDriver.getInstance(); this.rls = new RoleService(); } /** * Добавляет пользователя. * @param user новый пользователь. * @return true если пользователь добавлен в бд. Иначе false. * @throws SQLException исключение SQL. * @throws ParseException исключение парсинга. * @throws NoSuchAlgorithmException исключение "Нет такого алгоритма". * @throws UnsupportedEncodingException исключение "Кодировка не поддерживается. */ public boolean addUser(User user) throws SQLException, ParseException, NoSuchAlgorithmException, UnsupportedEncodingException { boolean result = false; String query = String.format("insert into users (name, login, email, createDate, pass, role_id) values ('%s', '%s', '%s', '%s', '%s', %d)", user.getName(), user.getLogin(), user.getEmail(), user.getDateStr(), this.getPassHash(user.getPass()), user.getRoleId()); HashMap<String, String> entry = this.db.insert(query); if (!entry.isEmpty()) { user.setId(Integer.parseInt(entry.get("id"))); result = true; } return result; } /** * Удаляет пользователя. * @param id идентификатор. * @return true если пользователь удалён из бд. Иначе false. * @throws SQLException исключение SQL. */ public boolean deleteUser(final int id) throws SQLException { boolean result = false; String query = String.format("delete from users where id = %d", id); int affected = this.db.delete(query); if (affected > 0) { result = true; } return result; } /** * Редактирует пользователя. * @param user новый пользователь. * @return true если пользователь обновлён в бд. Иначе false. * @throws SQLException исключение SQL. * @throws NoSuchAlgorithmException исключение "Нет такого алгоритма". * @throws UnsupportedEncodingException исключение "Кодировка не поддерживается. */ public boolean editUser(User user) throws SQLException, NoSuchAlgorithmException, UnsupportedEncodingException { boolean result = false; String query = String.format("update users set name='%s', login='%s', email='%s', pass='%s', role_id = %d where id = %d", user.getName(), user.getLogin(), user.getEmail(), this.getPassHash(user.getPass()), user.getRoleId(), user.getId()); int affected = this.db.update(query); if (affected > 0) { result = true; } return result; } /** * Получает хэш-сумму пароля. * @param pass пароль. * @return хэш-сумма пароля. * @throws NoSuchAlgorithmException исключение "Нет такого алгоритма". * @throws UnsupportedEncodingException исключение "Кодировка не поддерживается. */ public String getPassHash(String pass) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes(this.enc), 0, pass.length()); return new BigInteger(1, md.digest()).toString(16); } /** * Получает пользователя по идентификатору. * @param id идентификатор пользователя. * @return пользователь. * @throws SQLException исключение SQL. * @throws ParseException исключение парсинга. * @throws NoSuchAlgorithmException исключение "Нет такого алгоритма". * @throws UnsupportedEncodingException исключение "Кодировка не поддерживается. */ public User getUserById(final int id) throws SQLException, ParseException, NoSuchAlgorithmException, UnsupportedEncodingException { User user = null; String query = String.format("select users.id, users.name, users.login, users.email, users.createdate, users.pass, role_id, roles.name as role_name from users, roles where users.role_id = roles.id and users.id = %d", id); LinkedList<HashMap<String, String>> rl = this.db.select(query); LinkedList<User> users = this.processResult(rl); if (!users.isEmpty()) { user = users.getFirst(); } return user; } /** * Получает пользователя по логину и паролю. * @param login логин пользователя. * @param pass пароль пользователя. * @return пользователь. * @throws SQLException исключение SQL. * @throws ParseException исключение парсинга. * @throws NoSuchAlgorithmException исключение "Нет такого алгоритма". * @throws UnsupportedEncodingException исключение "Кодировка не поддерживается. */ public User getUserByLogPass(final String login, String pass) throws SQLException, ParseException, NoSuchAlgorithmException, UnsupportedEncodingException { User user = null; pass = this.getPassHash(pass); String query = String.format("select users.id, users.name, users.login, users.email, users.createdate, users.pass, role_id, roles.name as role_name from users, roles where users.role_id = roles.id and users.login = '%s' and users.pass = '%s'", login, pass); LinkedList<HashMap<String, String>> rl = this.db.select(query); LinkedList<User> users = this.processResult(rl); if (!users.isEmpty()) { user = users.getFirst(); } return user; } /** * Получает всех пользователей. * @param order имя столбца сортировки (по умолчанию id). * @param desc направление сортировки (asc, desc. По умолчанию asc). * @return коллекция пользователей. * @throws SQLException исключение SQL. * @throws ParseException исключение парсинга. * @throws NoSuchAlgorithmException исключение "Нет такого алгоритма". * @throws UnsupportedEncodingException исключение "Кодировка не поддерживается. */ public LinkedList<User> getUsers(final String order, final boolean desc) throws SQLException, ParseException, NoSuchAlgorithmException, UnsupportedEncodingException { LinkedList<User> users = new LinkedList<>(); String query = String.format("select users.id, users.name, users.login, users.email, users.createdate, users.pass, role_id, roles.name as role_name from users, roles where users.role_id = roles.id order by %s %s", order.equals("") ? "id" : order, desc ? "desc" : "asc"); LinkedList<HashMap<String, String>> rl = this.db.select(query); users = this.processResult(rl); return users; } /** * Обрабатывает результат запроса select. * @param result результат запроса select. * @return коллекция пользователей. * @throws SQLException исключение SQL. * @throws ParseException исключение парсинга. * @throws NoSuchAlgorithmException исключение "Нет такого алгоритма". * @throws UnsupportedEncodingException исключение "Кодировка не поддерживается. */ private LinkedList<User> processResult(LinkedList<HashMap<String, String>> result) throws SQLException, ParseException, NoSuchAlgorithmException, UnsupportedEncodingException { LinkedList<User> users = new LinkedList<>(); if (!result.isEmpty()) { for (HashMap<String, String> entry : result) { GregorianCalendar cal = new GregorianCalendar(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String strDate = entry.get("createdate"); Date date = sdf.parse(strDate); cal.setTime(date); Role role = this.rls.getRoleById(Integer.parseInt(entry.get("role_id"))); User user = new User(Integer.parseInt(entry.get("id")), entry.get("name"), entry.get("login"), entry.get("email"), cal, entry.get("pass"), role); users.add(user); } } return users; } /** * Устанавдливает кодировку. * @param enc кодировка. */ public void setEncoding(String enc) { this.enc = enc; } }
package com.movieapp.anti.movieapp.Models; import java.io.Serializable; /** * Created by Anti on 2/10/2018. */ public class Movie implements Serializable { public String original_title; public int id; public String poster_path; public String overview; public Boolean favorite; public transient Boolean favorites; public Boolean watchlist; public Rated rated; // public Boolean getRated() { // return rated; // } // // public void setRated(Boolean rated) { // this.rated = rated; // } public Boolean getFavorites() { return favorites; } public void setFavorites(Boolean favorites) { this.favorites = favorites; } public Credits credits; public Movie() { } public Movie(String original_title, int id, String poster_path) { this.original_title = original_title; this.id = id; this.poster_path = poster_path; } public String getOriginal_title() { return original_title; } public void setOriginal_title(String original_title) { this.original_title = original_title; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPoster_path() { return poster_path; } public void setPoster_path(String poster_path) { this.poster_path = poster_path; } }
package co.id.datascrip.mo_sam_div4_dts1.process; import android.app.ProgressDialog; import android.content.Context; import org.json.JSONException; import org.json.JSONObject; import co.id.datascrip.mo_sam_div4_dts1.Function; import co.id.datascrip.mo_sam_div4_dts1.Global; import co.id.datascrip.mo_sam_div4_dts1.callback.CallbackCustomer; import co.id.datascrip.mo_sam_div4_dts1.object.Customer; import co.id.datascrip.mo_sam_div4_dts1.process.interfaces.IC_Customer; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Response; import static co.id.datascrip.mo_sam_div4_dts1.Global.SISTEM; public class Process_Customer { private Context context; private ProgressDialog progressDialog; public Process_Customer(Context context) { this.context = context; progressDialog = new ProgressDialog(context); progressDialog.setMessage("Loading..."); progressDialog.setCancelable(false); progressDialog.show(); } public void Find(String teks, final CallbackCustomer.CBFind CB) { IC_Customer service = Global.CreateRetrofit(context).create(IC_Customer.class); service.Find(SISTEM, makeJSON(teks)).enqueue(new retrofit2.Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { String result = RetrofitResponse.getString(context, response); new Function(context).writeToText("Customer->Find", result); CB.onCB(RetrofitResponse.getListCustomer(result)); progressDialog.dismiss(); } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function(context).writeToText("Customer->Find", throwable.getMessage()); throwable.getCause(); progressDialog.dismiss(); } }); } public void Generate_Code(final CallbackCustomer.CBGenerateCode CB) { IC_Customer service = Global.CreateRetrofit(context).create(IC_Customer.class); service.Get_No(makeJSON()).enqueue(new retrofit2.Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { String result = RetrofitResponse.getString(context, response); new Function(context).writeToText("Customer->Generate_Code", result); CB.onCB(RetrofitResponse.getCustomerCode(result)); progressDialog.dismiss(); } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function(context).writeToText("Customer->Generate_Code", throwable.getMessage()); throwable.getCause(); progressDialog.dismiss(); } }); } public void Posting(final Customer customer, final CallbackCustomer.CBPosting CB) { IC_Customer service = Global.CreateRetrofit(context).create(IC_Customer.class); service.Post(makeJSON(customer)).enqueue(new retrofit2.Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { String result = RetrofitResponse.getString(context, response); new Function(context).writeToText("Customer->Posting", result); if (RetrofitResponse.isSuccess(result)) CB.onCB(customer); else CB.onCB(null); progressDialog.dismiss(); } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { new Function(context).writeToText("Customer->Posting", throwable.getMessage()); throwable.getCause(); progressDialog.dismiss(); } }); } private String makeJSON(String code) { JSONObject json = new JSONObject(); try { json.put("bex", Global.getBEX(context).getInitial()); json.put("code", code); } catch (JSONException e) { e.toString(); } return json.toString(); } private String makeJSON() { JSONObject json = new JSONObject(); try { json.put("no", Global.getBEX(context).getEmpNo()); json.put("bex", Global.getBEX(context).getInitial()); } catch (JSONException e) { e.toString(); } return json.toString(); } private String makeJSON(Customer customer) { JSONObject json = new JSONObject(); JSONObject json_customer = new JSONObject(); String cust_nav_code = ""; if (!customer.getCode().toUpperCase().contains("CUST")) cust_nav_code = customer.getCode(); try { json_customer.put("code", customer.getCode()); json_customer.put("code_nav", cust_nav_code); json_customer.put("name", customer.getName()); json_customer.put("alias", customer.getAlias()); json_customer.put("address", customer.getAddress1()); json_customer.put("city", customer.getCity()); json_customer.put("contact", customer.getContact()); json_customer.put("phone", customer.getPhone()); json_customer.put("email", customer.getEmail()); json_customer.put("npwp", customer.getNPWP()); json.put("bex", Global.getBEX(context).getEmpNo()); json.put("data", json_customer); } catch (JSONException e) { e.toString(); } return json.toString(); } }
package com.hcl.neo.eloader.microservices.params; import java.util.ArrayList; import java.util.List; public class Response { private List<OperationObjectDetail> operationObjectDetails; public Response(){ operationObjectDetails = new ArrayList<OperationObjectDetail>(); } public List<OperationObjectDetail> getOperationObjectDetails() { return operationObjectDetails; } public void setOperationObjectDetails(List<OperationObjectDetail> operationObjectDetails) { this.operationObjectDetails = operationObjectDetails; } public void addOperationObjectDetails(OperationObjectDetail operationObjectDetail){ this.operationObjectDetails.add(operationObjectDetail); } public void addOperationObjectDetails(List<OperationObjectDetail> operationObjectDetails){ this.operationObjectDetails.addAll(operationObjectDetails); } }
package in.msmartpay.agent.flight; import android.app.DatePickerDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import androidx.annotation.Nullable; import com.google.android.material.bottomsheet.BottomSheetDialog; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import org.json.JSONArray; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Locale; import in.msmartpay.agent.R; import in.msmartpay.agent.utility.BaseActivity; import in.msmartpay.agent.utility.HttpURL; import in.msmartpay.agent.utility.L; import in.msmartpay.agent.utility.Mysingleton; /** * Created by Harendra on 7/27/2017. */ public class FlightActivity extends BaseActivity { private LinearLayout ll_one_way,ll_round_way; private RelativeLayout rl_return,rl_depart; private View v_one_way,v_round_way; private EditText et_departure,et_arrival,et_depart,et_return; private AutoCompleteTextView actv_class; private TextView tv_adult,tv_child,tv_infant; private ImageView iv_adult_min,iv_adult_plus,iv_child_min,iv_child_plus,iv_infant_min,iv_infant_plus; private CheckBox cb_fare; private RadioGroup rg; private RadioButton rb; private Button btn_search_flight; private int adult=1,child=0,infant=0; private int total=0; private String tripType=""; private SimpleDateFormat dateFormatter; private String colDepartDate = "", colReturnDate = "",departDate="",returnDate="",departureCity="",arrivalCity="",classType=""; private ProgressDialog pd; private String url= HttpURL.FLIGHT_AVAILABILITY_REQUEST_URL; private Context context; private ArrayList<String> cityList; private ArrayList<AvailSegmentsModel> availSegmentsArrayList = new ArrayList<>(); private SharedPreferences myPrefs; private SharedPreferences.Editor prefsEditor; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.flight_search_h); getSupportActionBar().setDisplayHomeAsUpEnabled(true); setTitle("Flights"); context = FlightActivity.this; dateFormatter = new SimpleDateFormat("MM/dd/yyyy", Locale.US); myPrefs = getSharedPreferences("flightPref", MODE_PRIVATE); prefsEditor = myPrefs.edit(); //=== inisialize data's ==== init(); visibility(); adultValue(); childValue(); infantVlaue(); rl_return.setVisibility(View.INVISIBLE); //======= /* ArrayAdapter<String> adapterCity = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.states)); actv_from_city.setAdapter(adapterCity); actv_from_city.setThreshold(1); actv_to_city.setAdapter(adapterCity); actv_to_city.setThreshold(1); */ ArrayAdapter<String> adapterClass = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.flight_class)); actv_class.setAdapter(adapterClass); actv_class.setThreshold(1); //====== selectDate(); et_departure.setText("MAA"); et_arrival.setText("BLR"); /* et_departure.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context,FlightCity.class); intent.putExtra("City",cityList); intent.putExtra("test","Leave"); intent.putExtra("arrivalCity",arrivalCity); intent.putExtra("classType",classType); intent.putExtra("departureCity",departureCity); intent.putExtra("returnDate",returnDate); intent.putExtra("departDate",departDate); intent.putExtra("colReturnDate",colReturnDate); intent.putExtra("colDepartDate",colDepartDate); intent.putExtra("adult",adult); intent.putExtra("child",child); intent.putExtra("infant",infant); intent.putExtra("total",total); startActivityForResult(intent,0); } }); et_arrival.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context,FlightCity.class); intent.putExtra("City",cityList); intent.putExtra("test","Leave"); intent.putExtra("arrivalCity",arrivalCity); intent.putExtra("classType",classType); intent.putExtra("departureCity",departureCity); intent.putExtra("returnDate",returnDate); intent.putExtra("departDate",departDate); intent.putExtra("colReturnDate",colReturnDate); intent.putExtra("colDepartDate",colDepartDate); intent.putExtra("adult",adult); intent.putExtra("child",child); intent.putExtra("infant",infant); intent.putExtra("total",total); startActivityForResult(intent,1); } });*/ btn_search_flight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { requestSearchFlight(); } }); } private void requestSearchFlight() { SharedPreferences myPrefs =context.getSharedPreferences("myPrefs", MODE_PRIVATE); pd = new ProgressDialog(context); pd = ProgressDialog.show(context, "", "Loading. Please wait...", true); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); L.m2("txn_key", myPrefs.getString("txn-key", null)); /*int id=rg.getCheckedRadioButtonId(); rb = (RadioButton) findViewById(id); String typeN=rb.getText().toString(); if(typeN.equalsIgnoreCase("Domestic")){ }else { }*/ try { JSONObject jsonObject= new JSONObject(); jsonObject.put("BookingType", tripType); jsonObject.put("Origin", et_departure.getText().toString()); jsonObject.put("Destination", et_arrival.getText().toString()); jsonObject.put("ClassType", actv_class.getText().toString()); jsonObject.put("InfantCount", ""+infant); jsonObject.put("ChildCount", ""+child); jsonObject.put("AdultCount", ""+adult); jsonObject.put("TravelDate",et_depart.getText().toString()); jsonObject.put("ResidentofIndia","1"); if(et_return.getVisibility()== View.VISIBLE) { jsonObject.put("ReturnDate", et_return.getText().toString()); }else { jsonObject.put("ReturnDate", ""); } L.m2("called url", url); L.m2("request", jsonObject.toString()); JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.POST, url,jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject data) { try { pd.dismiss(); L.m2("response", data.toString()); if (data.getString("status") != null && data.getString("status").equals("0")) { JSONArray AvailabilityOutputJSONArray =data.getJSONArray("AvailabilityOutput"); JSONObject AvailabilityOutputJSONObject = AvailabilityOutputJSONArray.getJSONObject(0); prefsEditor.putString("UserTrackId",AvailabilityOutputJSONObject.getString("UserTrackId")); prefsEditor.commit(); JSONObject AvailabilityOutput = AvailabilityOutputJSONObject.getJSONObject("AvailabilityOutput"); JSONArray OngoingFlightsJSONArray =AvailabilityOutput.getJSONArray("OngoingFlights"); for(int i=0;i<OngoingFlightsJSONArray.length();i++){ JSONObject OngoingFlightsJSONObject = OngoingFlightsJSONArray.getJSONObject(i); JSONArray AvailSegmentsJSONArray =OngoingFlightsJSONObject.getJSONArray("AvailSegments"); for(int j=0;j<AvailSegmentsJSONArray.length();j++){ JSONObject AvailSegmentsJSONObject = AvailSegmentsJSONArray.getJSONObject(j); AvailSegmentsModel availSegmentsModel = new AvailSegmentsModel(); availSegmentsModel.setAirCraftType(AvailSegmentsJSONObject.getString("AirCraftType")); availSegmentsModel.setNumberofStops(AvailSegmentsJSONObject.getInt("NumberofStops")+""); availSegmentsModel.setOriginAirportTerminal(AvailSegmentsJSONObject.getString("OriginAirportTerminal")); availSegmentsModel.setArrivalDateTime(AvailSegmentsJSONObject.getString("ArrivalDateTime")); availSegmentsModel.setDepartureDateTime(AvailSegmentsJSONObject.getString("DepartureDateTime")); availSegmentsModel.setDuration(AvailSegmentsJSONObject.getString("Duration")); availSegmentsModel.setFlightNumber(AvailSegmentsJSONObject.getString("FlightNumber")); availSegmentsModel.setCurrency_Conversion_Rate(AvailSegmentsJSONObject.getString("Currency_Conversion_Rate")); availSegmentsModel.setVia(AvailSegmentsJSONObject.getString("Via")); availSegmentsModel.setFlightId(AvailSegmentsJSONObject.getString("FlightId")); availSegmentsModel.setOrigin(AvailSegmentsJSONObject.getString("Origin")); availSegmentsModel.setSupplierId(AvailSegmentsJSONObject.getString("SupplierId")); availSegmentsModel.setCurrencyCode(AvailSegmentsJSONObject.getString("CurrencyCode")); availSegmentsModel.setDestination(AvailSegmentsJSONObject.getString("Destination")); availSegmentsModel.setAirlineCode(AvailSegmentsJSONObject.getString("AirlineCode")); availSegmentsModel.setDestinationAirportTerminal(AvailSegmentsJSONObject.getString("DestinationAirportTerminal")); ArrayList<AvailPaxFareDetailsModel> AvailPaxFareDetailsArrayList = new ArrayList<>(); JSONArray availPaxFareDetailsJSONArray =AvailSegmentsJSONObject.getJSONArray("AvailPaxFareDetails"); for(int k=0;k<availPaxFareDetailsJSONArray.length();k++) { AvailPaxFareDetailsModel availPaxFareDetailsModel = new AvailPaxFareDetailsModel(); JSONObject availPaxFareDetailsJSONObject = availPaxFareDetailsJSONArray.getJSONObject(k); availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); availPaxFareDetailsModel.setChangePenalty(availPaxFareDetailsJSONObject.getString("ChangePenalty")); availPaxFareDetailsModel.setCancellationCharges(availPaxFareDetailsJSONObject.getString("CancellationCharges")); availPaxFareDetailsModel.setClassCodeDesc(availPaxFareDetailsJSONObject.getString("ClassCodeDesc")); JSONObject jsonObjectAdult = availPaxFareDetailsJSONObject.getJSONObject("Adult"); if(jsonObjectAdult.length()!=0){ availPaxFareDetailsModel.setAdultTotalTaxAmount(jsonObjectAdult.getString("TotalTaxAmount")); availPaxFareDetailsModel.setAdultCommission(jsonObjectAdult.getString("Commission")); availPaxFareDetailsModel.setAdultBasicAmount(jsonObjectAdult.getString("BasicAmount")); availPaxFareDetailsModel.setAdultFareType(jsonObjectAdult.getString("FareType")); availPaxFareDetailsModel.setAdultGrossAmount(jsonObjectAdult.getString("GrossAmount")); availPaxFareDetailsModel.setAdultFareBasis(jsonObjectAdult.getString("FareBasis")); if(jsonObjectAdult.has("YQ")) availPaxFareDetailsModel.setAdultYQ(jsonObjectAdult.getString("YQ")); else availPaxFareDetailsModel.setAdultYQ("0"); HashMap<String,String> hashMapTaxAdult = new HashMap<>(); JSONArray jSONArrayTaxAdult = jsonObjectAdult.getJSONArray("TaxDetails"); for (int l=0;l<jSONArrayTaxAdult.length();l++) { JSONObject jsonObject1 = jSONArrayTaxAdult.getJSONObject(l); hashMapTaxAdult.put(jsonObject1.getString("Description"), jsonObject1.getString("Amount")); } availPaxFareDetailsModel.setAdultTaxDetails(hashMapTaxAdult); } JSONObject jsonObjectChild = availPaxFareDetailsJSONObject.getJSONObject("Child"); if(jsonObjectChild.length()!=0){ availPaxFareDetailsModel.setChildTotalTaxAmount(jsonObjectChild.getString("TotalTaxAmount")); availPaxFareDetailsModel.setChildCommission(jsonObjectChild.getString("Commission")); availPaxFareDetailsModel.setChildBasicAmount(jsonObjectChild.getString("BasicAmount")); availPaxFareDetailsModel.setChildFareType(jsonObjectChild.getString("FareType")); availPaxFareDetailsModel.setChildGrossAmount(jsonObjectChild.getString("GrossAmount")); availPaxFareDetailsModel.setChildFareBasis(jsonObjectChild.getString("FareBasis")); if(jsonObjectChild.has("YQ")) availPaxFareDetailsModel.setAdultYQ(jsonObjectChild.getString("YQ")); else availPaxFareDetailsModel.setAdultYQ("0"); HashMap<String,String> hashMapTaxChild = new HashMap<>(); JSONArray jSONArrayTaxChild = jsonObjectChild.getJSONArray("TaxDetails"); for (int l=0;l<jSONArrayTaxChild.length();l++) { JSONObject jsonObject1 = jSONArrayTaxChild.getJSONObject(l); hashMapTaxChild.put(jsonObject1.getString("Description"), jsonObject1.getString("Amount")); } availPaxFareDetailsModel.setChildTaxDetails(hashMapTaxChild); } JSONObject jsonObjectInfant = availPaxFareDetailsJSONObject.getJSONObject("Infant"); if(jsonObjectInfant.length()!=0){ availPaxFareDetailsModel.setInfantTotalTaxAmount(jsonObjectInfant.getString("TotalTaxAmount")); availPaxFareDetailsModel.setInfantCommission(jsonObjectInfant.getString("Commission")); availPaxFareDetailsModel.setInfantBasicAmount(jsonObjectInfant.getString("BasicAmount")); availPaxFareDetailsModel.setInfantFareType(jsonObjectInfant.getString("FareType")); availPaxFareDetailsModel.setInfantGrossAmount(jsonObjectInfant.getString("GrossAmount")); availPaxFareDetailsModel.setInfantFareBasis(jsonObjectInfant.getString("FareBasis")); if(jsonObjectInfant.has("YQ")) availPaxFareDetailsModel.setAdultYQ(jsonObjectInfant.getString("YQ")); else availPaxFareDetailsModel.setAdultYQ("0"); HashMap<String,String> hashMapTaxInfant = new HashMap<>(); JSONArray jSONArrayTaxInfant = jsonObjectInfant.getJSONArray("TaxDetails"); for (int l=0;l<jSONArrayTaxInfant.length();l++) { JSONObject jsonObject1 = jSONArrayTaxInfant.getJSONObject(l); hashMapTaxInfant.put(jsonObject1.getString("Description"), jsonObject1.getString("Amount")); } availPaxFareDetailsModel.setInfantTaxDetails(hashMapTaxInfant); } availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); availPaxFareDetailsModel.setClassCode(availPaxFareDetailsJSONObject.getString("ClassCode")); AvailPaxFareDetailsArrayList.add(availPaxFareDetailsModel); } availSegmentsModel.setAvailPaxFareDetailsModels(AvailPaxFareDetailsArrayList); availSegmentsArrayList.add(availSegmentsModel); } } L.m2("test",availSegmentsArrayList.toString()); /*prefsEditor.putString("TravelDate",et_depart.getText().toString()); prefsEditor.putString("Origin",et_departure.getText().toString()); prefsEditor.putString("Destination",et_arrival.getText().toString()); prefsEditor.putInt("InfantCount",infant); prefsEditor.putInt("ChildCount",child); prefsEditor.putInt("AdultCount",adult);*/ Intent intent = new Intent(context,FlightList.class); intent.putExtra("availSegmentsArrayList",availSegmentsArrayList); intent.putExtra("TravelDate",et_depart.getText().toString()); intent.putExtra("Origin", et_departure.getText().toString()); intent.putExtra("Destination", et_arrival.getText().toString()); intent.putExtra("InfantCount", infant); intent.putExtra("ChildCount", child); intent.putExtra("AdultCount", adult); startActivity(intent); }else if (data.getString("status") != null && data.getString("status").equals("1")) { Toast.makeText(context, data.getString("message"), Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(context,"Unable to process your request", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { pd.dismiss(); Toast.makeText(context, " "+error.toString(), Toast.LENGTH_SHORT).show(); } }); getSocketTimeOut(objectRequest); Mysingleton.getInstance(context).addToRequsetque(objectRequest); } catch (Exception e) { e.printStackTrace(); } } private void selectDate() { et_depart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar newCalendar = Calendar.getInstance(); DatePickerDialog fromDatePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); try { colDepartDate = dateFormatter.format(newDate.getTime()); if (!colDepartDate.equalsIgnoreCase("")) { et_depart.setText(colDepartDate); } else { Toast.makeText(context, "Invalid From Date.", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } } }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); fromDatePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000); fromDatePickerDialog.show(); } }); et_return.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!TextUtils.isEmpty(et_depart.getText())){ Calendar newCalendar = Calendar.getInstance(); DatePickerDialog toDatePickerDialog = new DatePickerDialog(FlightActivity.this, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); colReturnDate = dateFormatter.format(newDate.getTime()); Log.v(">>>>>>>>>>>>>>> ", et_depart.getText() + " - " + colReturnDate); if (!et_depart.getText().equals("") && !colReturnDate.equals("")) { try { colDepartDate = et_depart.getText().toString(); Date fdate = dateFormatter.parse(colDepartDate); Date todate = dateFormatter.parse(colReturnDate); if (fdate.compareTo(todate) > 0) { et_return.setText(""); Toast.makeText(context, "Depart date should be lesser than Return Date.", Toast.LENGTH_SHORT).show(); } else { et_return.setText(colReturnDate); } } catch (Exception e) { e.printStackTrace(); Log.v("Exception", "Execption in Fund transfer"); e.printStackTrace(); Toast.makeText(context, "Something went wrong3.", Toast.LENGTH_SHORT).show(); } } else { et_return.setText(colReturnDate); et_depart.setText(colReturnDate); // Toast.makeText(FlightActivity.this, "Please select first Deapart date!",Toast.LENGTH_SHORT).show(); } } }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH)); toDatePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000); toDatePickerDialog.show(); }else{ Toast.makeText(context, "Please select first departure date!", Toast.LENGTH_SHORT).show(); } } }); } private void visibility() { tripType="O"; rl_return.setVisibility(View.INVISIBLE); v_one_way.setBackgroundColor(getResources().getColor(R.color.whitecolor)); v_round_way.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); ll_one_way.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tripType="O"; rl_return.setVisibility(View.INVISIBLE); v_one_way.setBackgroundColor(getResources().getColor(R.color.whitecolor)); v_round_way.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); } }); ll_round_way.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tripType="R"; rl_return.setVisibility(View.VISIBLE); v_one_way.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); v_round_way.setBackgroundColor(getResources().getColor(R.color.whitecolor)); et_return.setText(""); } }); } private void infantVlaue() { iv_infant_min.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(infant>0){ infant--; tv_infant.setText(""+infant); } } }); iv_infant_plus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(adult>infant){ infant++; tv_infant.setText(""+infant); } } }); } private void childValue() { iv_child_min.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (child > 0) { child--; tv_child.setText("" + child); } } }); iv_child_plus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { total =adult+child; if(total<9){ child++; tv_child.setText(""+child); } } }); } private void adultValue() { iv_adult_min.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(adult>1){ adult--; tv_adult.setText(""+adult); if(infant>adult){ infant--; tv_infant.setText(""+infant); } } } }); iv_adult_plus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { total =adult+child; if(total<9){ adult++; tv_adult.setText("" + adult); } } }); } private void init() { //===RadioGroup // rg=(RadioGroup) findViewById(R.id.rg); //===LinearLayout ll_one_way = (LinearLayout) findViewById(R.id.ll_one_way); ll_round_way = (LinearLayout) findViewById(R.id.ll_round_way); //==RelativeLayout rl_return = (RelativeLayout) findViewById(R.id.rl_return); rl_depart = (RelativeLayout) findViewById(R.id.rl_depart); //== View v_one_way= (View) findViewById(R.id.v_one_way); v_round_way= (View) findViewById(R.id.v_round_way); //====AutoCompleteTextView et_depart = findViewById(R.id.et_depart); et_return = findViewById(R.id.et_return); et_departure = findViewById(R.id.et_departure); et_arrival = findViewById(R.id.et_arrival); actv_class= (AutoCompleteTextView) findViewById(R.id.actv_class); //====TextView tv_adult=(TextView) findViewById(R.id.tv_adult); tv_child=(TextView) findViewById(R.id.tv_child); tv_infant=(TextView) findViewById(R.id.tv_infant); //===ImageView iv_adult_min=(ImageView) findViewById(R.id.iv_adult_min); iv_adult_plus=(ImageView) findViewById(R.id.iv_adult_plus); iv_child_min=(ImageView) findViewById(R.id.iv_child_min); iv_child_plus=(ImageView) findViewById(R.id.iv_child_plus); iv_infant_min=(ImageView) findViewById(R.id.iv_infant_min); iv_infant_plus=(ImageView) findViewById(R.id.iv_infant_plus); //===CheckBox cb_fare = (CheckBox) findViewById(R.id.cb_fare); //===Button btn_search_flight= findViewById(R.id.btn_search_flight); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); colDepartDate = data.getStringExtra("colDepartDate"); colReturnDate = data.getStringExtra("colReturnDate"); departDate = data.getStringExtra("departDate"); returnDate = data.getStringExtra("returnDate"); departureCity = data.getStringExtra("departureCity"); arrivalCity = data.getStringExtra("arrivalCity"); classType = data.getStringExtra("classType"); adult = data.getIntExtra("adult",0); child = data.getIntExtra("child",0); infant = data.getIntExtra("infant",0); total = data.getIntExtra("total",0); /*switch (requestCode){ case 0: if(resultCode==2){ leaveCity = data.getStringExtra("cityName"); et_leave.setText(leaveCity); L.m2("city source--1>", CitySource.toString()); for(int i=0; i<CitySource.size(); i++){ if(leaveCity.equalsIgnoreCase(CitySource.get(i))){ OriginID = CityIdSource.get(i).toString(); L.m2("check_OrginId--2>", OriginID.toString()); break; } } getDestinationRequest(OriginID); } break; case 1: if(resultCode==2){ destinationCity = data.getStringExtra("cityName"); et_destination.setText(destinationCity); for(int i=0; i<CityDestination.size(); i++){ if(destinationCity.equalsIgnoreCase(CityDestination.get(i))){ DestinationID = CityIdDestination.get(i).toString(); L.m2("check_DestinationID-->", DestinationID.toString()); break; } } } break; }*/ } private void bottomDialog(){ BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(context); View sheetView = getLayoutInflater().inflate(R.layout.flight_passenger_bottom_sheet, null); mBottomSheetDialog.setContentView(sheetView); mBottomSheetDialog.show(); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); } return true; } }
package com.wangzhu.other; import org.junit.Test; /** * Created by wang.zhu on 2020-04-19 15:36. **/ public class TestLong { @Test public void test(){ final int i = 1; final long l = i; final float f = (float)l; System.out.println(f); } }
package io.flyingmongoose.brave.adapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import com.parse.ParseObject; import java.util.ArrayList; import java.util.List; import io.flyingmongoose.brave.R; /** * Created by IC on 6/1/2015. */ public class LAdaptGroups extends ArrayAdapter implements Filterable { Context context; int layRes; public List<ParseObject> items; List<ParseObject> storedItems; //Statistics vars int totPotentialPrivateResponders; int totPotentialPublicResponders; public LAdaptGroups(Context context, int layRes, List<ParseObject> items) { super(context, layRes, items); this.context = context; this.layRes = layRes; this.items = items; this.storedItems = items; } @Override public int getCount() { return items.size(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View constructedView = LayoutInflater.from(context).inflate(layRes, parent, false); View vStatus = constructedView.findViewById(R.id.vStatus); //Set number of poeple in the group TextView txtvNoOfUsersValue = (TextView) constructedView.findViewById(R.id.txtvNoOfUsersValue); int noOfUsers = items.get(position).getInt("subscribers"); txtvNoOfUsersValue.setText(noOfUsers + ""); //Set Color status boolean _public = items.get(position).getBoolean("public"); if(_public) { vStatus.setBackgroundColor(context.getResources().getColor(R.color.SeaGreen)); totPotentialPublicResponders += noOfUsers; } else { vStatus.setBackgroundColor(context.getResources().getColor(R.color.Blue)); totPotentialPrivateResponders += noOfUsers; } TextView txtvListItemGroupName = (TextView) constructedView.findViewById(R.id.txtvListItemGroupName); txtvListItemGroupName.setText(items.get(position).getString("name")); TextView txtvListItemCountry = (TextView) constructedView.findViewById(R.id.txtvListItemCountry); txtvListItemCountry.setText(items.get(position).getString("country")); return constructedView; } public int getPrivateUsers() {return totPotentialPrivateResponders;} public int getPublicUsers() {return totPotentialPublicResponders;} public int getTotalUsers() {return totPotentialPrivateResponders + totPotentialPublicResponders;} @Override public Filter getFilter() { Filter filter = new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filterResults = new FilterResults(); List<ParseObject> filteredItems = new ArrayList<ParseObject>(); //Clean search term constraint = constraint.toString().trim().toLowerCase().replaceAll("\\s+", ""); Log.i("New Filter", "constraint: %" + constraint + "%"); if(constraint == null || constraint.length() == 0) { //Return entire list filterResults.count = storedItems.size(); filterResults.values = storedItems; } else { //Perform search for (int i = 0; i < storedItems.size(); i++) { if (storedItems.get(i).getString("flatValue").startsWith(constraint.toString())) filteredItems.add(storedItems.get(i)); } filterResults.count = filteredItems.size(); filterResults.values = filteredItems; } return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { items = (List<ParseObject>) results.values; notifyDataSetChanged(); } }; return filter; } }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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 und */ package org.wso2.carbon.identity.account.suspension.notification.task.internal; import org.osgi.framework.BundleContext; import org.wso2.carbon.identity.account.suspension.notification.task.NotificationReceiversRetrievalFactory; import org.wso2.carbon.identity.account.suspension.notification.task.util.NotificationConstants; import org.wso2.carbon.identity.event.services.IdentityEventService; import org.wso2.carbon.identity.governance.IdentityGovernanceService; import org.wso2.carbon.user.core.service.RealmService; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; public class NotificationTaskDataHolder { private static volatile NotificationTaskDataHolder accountServiceDataHolder = new NotificationTaskDataHolder(); private IdentityEventService identityEventService; private IdentityGovernanceService identityGovernanceService; private BundleContext bundleContext; private Map<String, NotificationReceiversRetrievalFactory> notificationReceiversRetrievalFactories = new HashMap<>(); private RealmService realmService; private String notificationTriggerTime; private String schedulerDelay; private String notificationSendingThreadPoolSize = "1"; public int getNotificationSendingThreadPoolSize() { return Integer.parseInt(notificationSendingThreadPoolSize); } public void setNotificationSendingThreadPoolSize(String notificationSendingThreadPoolSize) { this.notificationSendingThreadPoolSize = notificationSendingThreadPoolSize; } public Date getNotificationTriggerTime() throws ParseException{ DateFormat dateFormat = new SimpleDateFormat(NotificationConstants.TRIGGER_TIME_FORMAT); return dateFormat.parse(notificationTriggerTime); } public void setNotificationTriggerTime(String notificationTriggerTime) { this.notificationTriggerTime = notificationTriggerTime; } public String getSchedulerDelay() { return schedulerDelay; } public void setSchedulerDelay(String schedulerDelay) { this.schedulerDelay = schedulerDelay; } private NotificationTaskDataHolder() { } public static NotificationTaskDataHolder getInstance() { return accountServiceDataHolder; } public IdentityEventService getIdentityEventService() { return identityEventService; } public void setIdentityEventService(IdentityEventService identityEventService) { this.identityEventService = identityEventService; } public IdentityGovernanceService getIdentityGovernanceService() { return identityGovernanceService; } public void setIdentityGovernanceService(IdentityGovernanceService identityGovernanceService) { this.identityGovernanceService = identityGovernanceService; } public BundleContext getBundleContext() { return bundleContext; } public void setBundleContext(BundleContext bundleContext) { this.bundleContext = bundleContext; } public Map<String, NotificationReceiversRetrievalFactory> getNotificationReceiversRetrievalFactories() { return notificationReceiversRetrievalFactories; } public void setRealmService(RealmService realmService) { this.realmService = realmService; } public RealmService getRealmService() { return realmService; } }
package cl.laPalmera.Manejador; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import org.apache.log4j.Logger; import cl.laPalmera.DTO.ProductoLineaDTO; import cl.laPalmera.connection.ConnectionLaPalmera; public class ManejadorProductoLinea { private static final Logger LOGGER = Logger.getLogger(ManejadorProductoLinea.class); private String codigoProducto=""; private String codigoLineaProduccion=""; public ArrayList consultar() { ArrayList<ProductoLineaDTO> vec = new ArrayList<ProductoLineaDTO>(); try { ConnectionLaPalmera connLaPalmera = new ConnectionLaPalmera(); Connection conn = connLaPalmera.conectionMySql(); if (conn != null) { Statement stmt = conn.createStatement(); String sql = "select * from ProductoLinea where 1 = 1 "; if (!codigoProducto.equals("")) sql = sql +" and codigoProducto = '"+codigoProducto+"'"; if (!codigoLineaProduccion.equals("")) sql = sql +" and codigolineaProduccion = '"+codigoLineaProduccion+"'"; //LOGGER.debug(sql); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { ProductoLineaDTO puntero = new ProductoLineaDTO(); puntero.setCodigoProducto(rs.getString(1)); puntero.setCodigoLineaProduccion(rs.getString(2)); vec.add(puntero); } stmt.close(); conn.close(); } } catch (Exception e) { LOGGER.error(e,e); } return vec; } public String getCodigoLineaProduccion() { return codigoLineaProduccion; } public void setCodigoLineaProduccion(String codigoLineaProduccion) { this.codigoLineaProduccion = codigoLineaProduccion; } public String getCodigoProducto() { return codigoProducto; } public void setCodigoProducto(String codigoProducto) { this.codigoProducto = codigoProducto; } }
package com.lyl.core.common.enums; /** * Created by lyl * Date 2018/12/27 18:20 */ public enum MonitorResult { RUN_NOMAL,RUN_CONTROL_FAIL, RUN_LOCAL_BREAK, RUN_REMOTE_BREAK, RUN_EXP,RUN_SIGN_FAIL; public static MonitorResult fromControlResult(ControlResult controlResult,boolean isLocal){ switch (controlResult){ case BREAK: return isLocal ? RUN_LOCAL_BREAK : RUN_REMOTE_BREAK; case LIMIT: return RUN_CONTROL_FAIL; default: throw new RuntimeException("not support!"); } } }
package com.guru.login; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; import org.apache.http.HttpResponse; import java.io.InputStream; import retrofit.Call; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; public class DetailActivity extends AppCompatActivity { //http://192.168.88.31/rjbanadmin/index.php/maincontroller/lihat_pesanan_user_json/?=rita@gmail.com // Untuk membuat detail dari json int a, b, hitungHarga; String str = ""; ImageView varImage; TextView tvIdNamaBan, tvIdKodeBan, tvIdUkuranBan, tvIdMerekBan, tvIdStokBan, tvIdHargaBan; EditText nml, eml, alm, notelp, juml, edttotal1; // EditText ditambahkan pesanan Button btnSimpan; // EditText name, email, password; String Getname, GetEmail, GetPassword; Button register; // String DataParseUrl = "http://apidroid.devgolan.web.id/insert_pengguna.php"; Boolean CheckEditText; String Response; HttpResponse response; String id_user; String kd_ban; int pesanan; String email; String nama_lengkap; String alamat; String no_tlp; int total; InputStream is = null; String result = null; String line = null; public static final int CONNECTION_TIMEOUT = 10000; public static final int READ_TIMEOUT = 15000; String s1idus, s2nama, s3kodeban, s4email, s5alamat, s6notelp, i7jumlah; int i8total=100; int hitungTotal, varHarga, varJumlah; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); varImage = (ImageView) findViewById(R.id.img); tvIdKodeBan = (TextView) findViewById(R.id.kdBan); tvIdNamaBan = (TextView) findViewById(R.id.namaBan); tvIdMerekBan = (TextView) findViewById(R.id.merekBan); tvIdUkuranBan = (TextView) findViewById(R.id.ukuranBan); tvIdStokBan = (TextView) findViewById(R.id.stokBan); tvIdHargaBan = (TextView)findViewById(R.id.hargaBan); btnSimpan = (Button) findViewById(R.id.btn_simpan); nml = (EditText) findViewById(R.id.namaLkp); eml = (EditText) findViewById(R.id.et_nama); alm = (EditText) findViewById(R.id.et_alamat); notelp = (EditText) findViewById(R.id.et_notel); juml = (EditText) findViewById(R.id.et_jumlah); edttotal1 = (EditText) findViewById(R.id.et_total); Intent intent = getIntent(); Bundle bd = intent.getExtras(); if (bd != null) { String getName = (String) bd.get("name"); String acceptedUrlImage = (String) bd.get("urltodetail"); String kodeB = (String) bd.get("kodebandetail"); String hargaB = (String) bd.get("hargabandetail"); String merkB = (String) bd.get("merkbandetail"); String ukuranB = (String) bd.get("ukuranbandetail"); String stokB = (String) bd.get("stokbandetail"); tvIdNamaBan.setText(getName); tvIdKodeBan.setText(kodeB); tvIdMerekBan.setText(merkB); tvIdHargaBan.setText(hargaB); tvIdUkuranBan.setText(ukuranB); tvIdStokBan.setText(stokB); Picasso.with(DetailActivity.this) .load(acceptedUrlImage) .placeholder(R.mipmap.ic_launcher) .error(R.mipmap.ic_launcher) .resize(300, 300) .into(varImage); } btnSimpan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //String iduser, String namalengkap, String kodeban, String email, String alamat, String notelp, int total, int pesanan s1idus = tvIdKodeBan.getText().toString(); s2nama = nml.getText().toString(); varHarga= Integer.parseInt(tvIdHargaBan.getText().toString()); varJumlah = Integer.parseInt(juml.getText().toString()); hitungTotal = varHarga * varJumlah ; //insert(); Log.d("Input Slidus", s1idus); Log.d("Hasil Kali", Integer.toString(hitungTotal)); insertData(s1idus, nml.getText().toString(),tvIdKodeBan.getText().toString(), eml.getText().toString(), alm.getText().toString(), notelp.getText().toString(), hitungTotal, varJumlah); // SendDataToServer(s1idus, s2nama, s3kodeban, s3kodeban, s3kodeban, s3kodeban, i7jumlah, i7jumlah); } }); ; } public void insertData(String iduser, String namalengkap, String kodeban, String email, String alamat, String notelp, int total, int pesanan) { // call InterFace RegisterAPI registerAPI = ((RetrofitApplication) getApplication()).getMshoppinpApis(); // call Inter face method Call<PojoDemo> call = registerAPI.serverCall(iduser, kodeban, pesanan, email, namalengkap, alamat, notelp, total); call.enqueue(new Callback<PojoDemo>() { @Override public void onResponse(Response<PojoDemo> response, Retrofit retrofit) { // postive responce // get pojo value using getSuccess and get Body(Body is all responce) if (response.body().getSuccess()) { Log.d("hasil output", response.raw().toString()); Toast.makeText(DetailActivity.this, "Value saved", Toast.LENGTH_LONG).show(); Intent keMenenuban = new Intent(DetailActivity.this, MenuBan.class); startActivity(keMenenuban); } else { Log.d("hasil output", response.raw().toString()); Toast.makeText(DetailActivity.this, response.body().getError() + "", Toast.LENGTH_LONG).show(); } } // Error Or Any Failure @Override public void onFailure(Throwable t) { Toast.makeText(DetailActivity.this, t.getMessage() + "", Toast.LENGTH_LONG).show(); } }); } /* public void SendDataToServer(String iduser, String namalengkap, String kodeban, String email, String alamat, String notelp, int total, int pesanan) { class AsyncLogin extends AsyncTask<String, String, String> { ProgressDialog pdLoading = new ProgressDialog(DetailActivity.this); HttpURLConnection conn; URL url = null; @Override protected void onPreExecute() { super.onPreExecute(); //this method will be running on UI thread pdLoading.setMessage("\tLoading..."); pdLoading.setCancelable(false); pdLoading.show(); } @Override protected String doInBackground(String... params) { try { // Enter URL address where your php file resides url = new URL("http://192.168.1.14/rjbanadmin/pemesanan.php"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return "exception"; } try { // Setup HttpURLConnection class to send and receive data from php and mysql conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(READ_TIMEOUT); conn.setConnectTimeout(CONNECTION_TIMEOUT); conn.setRequestMethod("POST"); // setDoInput and setDoOutput method depict handling of both send and receive conn.setDoInput(true); conn.setDoOutput(true); // Append parameters to URL Uri.Builder builder = new Uri.Builder() .appendQueryParameter("email", params[0]) .appendQueryParameter("password", params[1]); String query = builder.build().getEncodedQuery(); // Open connection for sending data OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(query); writer.flush(); writer.close(); os.close(); conn.connect(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return "exception"; } try { int response_code = conn.getResponseCode(); // Check if successful connection made if (response_code == HttpURLConnection.HTTP_OK) { // Read data sent from server InputStream input = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } // Pass data to onPostExecute method return (result.toString()); } else { return ("unsuccessful"); } } catch (IOException e) { e.printStackTrace(); return "exception"; } finally { conn.disconnect(); } } @Override protected void onPostExecute(String result) { //this method will be running on UI thread pdLoading.dismiss(); if (result.equalsIgnoreCase("true")) { *//* Here launching another activity when login successful. If you persist login state use sharedPreferences of Android. and logout button to clear sharedPreferences. *//* Toast.makeText(DetailActivity.this, "Berhasil Nambah", Toast.LENGTH_LONG).show(); } else if (result.equalsIgnoreCase("false")) { // If username and password does not match display a error message Toast.makeText(DetailActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show(); } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) { Toast.makeText(DetailActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show(); } } } new AsyncLogin().execute(tvIdKodeBan, tvIdHargaBan); }*/ }
package com.esum.wp.ims.componentnodelistinfo.base; import com.esum.appframework.dmo.BaseDMO; /** * This is an object that contains data related to the COMPONENT_NODELIST_INFO table. * Do not modify this class because it will be overwritten if the configuration file * related to this class is modified. * * @hibernate.class * table="COMPONENT_NODELIST_INFO" */ public abstract class BaseComponentNodelistInfo extends BaseDMO { public static String REF = "ComponentNodelistInfo"; public static String PROP_NODE_ID = "NodeId"; public static String PROP_MOD_DATE = "ModDate"; public static String PROP_COMP_ID = "CompId"; public static String PROP_REG_DATE = "RegDate"; // constructors public BaseComponentNodelistInfo () { initialize(); } /** * Constructor for primary key */ public BaseComponentNodelistInfo (java.lang.String nodeId) { this.setNodeId(nodeId); initialize(); } /** * Constructor for required fields */ public BaseComponentNodelistInfo ( java.lang.String nodeId, java.lang.String compId, java.lang.String regDate, java.lang.String modDate) { this.setNodeId(nodeId); this.setCompId(compId); this.setRegDate(regDate); this.setModDate(modDate); initialize(); } protected void initialize () { compId = ""; modDate = ""; regDate = ""; } // primary key protected java.lang.String nodeId; // fields protected java.lang.String compId; protected java.lang.String modDate; protected java.lang.String regDate; /** * Return the unique identifier of this class * @hibernate.id * column="NODE_ID" */ public java.lang.String getNodeId () { return nodeId; } /** * Set the unique identifier of this class * @param nodeId the new ID */ public void setNodeId (java.lang.String nodeId) { this.nodeId = nodeId; } /** * Return the value associated with the column: COMP_ID */ public java.lang.String getCompId () { return compId; } /** * Set the value related to the column: COMP_ID * @param compId the COMP_ID value */ public void setCompId (java.lang.String compId) { this.compId = compId; } /** * Return the value associated with the column: MOD_DATE */ public java.lang.String getModDate () { return modDate; } /** * Set the value related to the column: MOD_DATE * @param modDate the MOD_DATE value */ public void setModDate (java.lang.String modDate) { this.modDate = modDate; } /** * Return the value associated with the column: REG_DATE */ public java.lang.String getRegDate () { return regDate; } /** * Set the value related to the column: REG_DATE * @param regDate the REG_DATE value */ public void setRegDate (java.lang.String regDate) { this.regDate = regDate; } }
package checkers.core.clientServerInterfaces; import checkers.core.Checker; import checkers.core.Move; import java.rmi.RemoteException; public interface Client extends java.rmi.Remote { void update(boolean isMyTurn, Move lastMove) throws RemoteException; void gameOver(String winnerLogin) throws RemoteException; void newPlayerAdded(String login, Checker color) throws RemoteException; void replaceWithBot(String login, int index) throws RemoteException; }
/** * JedisUtils */ package Redis.utils; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * Created on 2013-12-18 * <p>Description: [���������Ҫ���ܽ���]</p> */ /** * Created on 2013-12-18 * <p> * Description: [���������Ҫ���ܽ���] * </p> * * @author:wenghy * @version 1.0 */ public class JedisUtils { //private Logger log = Logger.getLogger(this.getClass()); /**�������ʱ�� */ private final int expire =JRedisPoolConfig.EXPORE; /** ����Key�ķ��� */ // public Keys KEYS; /** �Դ洢�ṹΪString���͵IJ��� */ //public Strings STRINGS; /** �Դ洢�ṹΪList���͵IJ��� */ // public Lists LISTS; /** �Դ洢�ṹΪSet���͵IJ��� */ // public Sets SETS; /** �Դ洢�ṹΪHashMap���͵IJ��� */ // public Hash HASH; /** �Դ洢�ṹΪSet(�����)���͵IJ��� */ // public SortSet SORTSET; private static JedisPool jedisPool = null; private JedisUtils() { } static { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxActive(JRedisPoolConfig.MAX_ACTIVE); config.setMaxIdle(JRedisPoolConfig.MAX_IDLE); config.setMaxWait(JRedisPoolConfig.MAX_WAIT); config.setTestOnBorrow(JRedisPoolConfig.TEST_ON_BORROW); config.setTestOnReturn(JRedisPoolConfig.TEST_ON_RETURN); //redis������������룺 jedisPool = new JedisPool( config, JRedisPoolConfig.REDIS_IP, JRedisPoolConfig.REDIS_PORT, JRedisPoolConfig.TIME_OUT); //redisδ�������룺 // jedisPool = new JedisPool(config, JRedisPoolConfig.REDIS_IP, // JRedisPoolConfig.REDIS_PORT); } public JedisPool getPool() { return jedisPool; } /** * ��jedis���ӳ��л�ȡ��ȡjedis���� * @return */ public static Jedis getJedis() { return jedisPool.getResource(); } private static final JedisUtils JedisUtils = new JedisUtils(); /** * ��ȡJedisUtilsʵ�� * @return */ public static JedisUtils getInstance() { return JedisUtils; } /** * ����jedis * @param jedis */ public static void returnJedis(Jedis jedis) { jedisPool.returnResource(jedis); } /** * ���ù���ʱ�� * @author ruan 2013-4-11 * @param key * @param seconds */ public void expire(String key, int seconds) { if (seconds <= 0) { return; } Jedis jedis = getJedis(); jedis.expire(key, seconds); returnJedis(jedis); } /** * ����Ĭ�Ϲ���ʱ�� * @author ruan 2013-4-11 * @param key */ public void expire(String key) { expire(key, expire); } }
package com.niksoftware.snapseed.core; import android.content.Context; import com.niksoftware.snapseed.core.filterparameters.FilterParameter; public class UndoObject { private int _changedParameter; private String _description; private boolean _forceNoDescription; private FilterParameter _parameter; private UndoObject(FilterParameter param, int changedParameter, String description, boolean forceNoDescription) { try { this._parameter = param.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } this._changedParameter = changedParameter; this._description = description; this._forceNoDescription = forceNoDescription; } public UndoObject(FilterParameter param, int changedParameter, String description) { this(param, changedParameter, description, false); } public UndoObject(FilterParameter param, int changedParameter, boolean forceNoDescription) { this(param, changedParameter, null, forceNoDescription); } public FilterParameter getFilterParameter() { return this._parameter; } public int getChangedParameter() { return this._changedParameter; } public boolean hasStaticDescription() { return this._description != null; } public String getDescription(Context context) { if (this._forceNoDescription) { return null; } return this._description != null ? this._description : this._parameter.getParameterDescription(context, this._changedParameter); } public boolean forceNoDescription() { return this._forceNoDescription; } }
package com.skp.test.string; import static org.junit.Assert.*; import java.util.TreeMap; import org.junit.Test; public class AnagramTest { @Test public void testMapCompare() throws Exception { TreeMap<String, Integer> map1 = new TreeMap<>(); TreeMap<String, Integer> map2 = new TreeMap<>(); TreeMap<String, Integer> map3 = new TreeMap<>(); map1.put("a", 1); map2.put("a", 1); map3.put("a", 2); assertEquals(map1, map2); assertNotEquals(map1, map3); } @Test public void same_anagram() throws Exception { Anagram sut = new Anagram(); boolean result = sut.isSame("strings", "sgnirts"); assertTrue(result); } @Test public void diff_anagram() throws Exception { Anagram sut = new Anagram(); boolean result = sut.isSame("strings", "stringss"); assertFalse(result); } }
package com.zantong.mobilecttx.fahrschule.fragment; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.zantong.mobilecttx.R; import com.zantong.mobilecttx.base.fragment.BaseRefreshJxFragment; import com.zantong.mobilecttx.common.Injection; import com.zantong.mobilecttx.common.PublicData; import com.zantong.mobilecttx.common.activity.FahrschulePayBrowserActivity; import com.zantong.mobilecttx.eventbus.FahrschuleApplyEvent; import com.zantong.mobilecttx.fahrschule.dto.CreateOrderDTO; import com.zantong.mobilecttx.interf.IFahrschuleOrderNumFtyContract; import com.zantong.mobilecttx.presenter.fahrschule.FahrschuleOrderNumPresenter; import com.zantong.mobilecttx.user.activity.LoginActivity; import com.zantong.mobilecttx.weizhang.bean.PayOrderResult; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import cn.qqtheme.framework.global.GlobalConfig; import cn.qqtheme.framework.global.GlobalConstant; import cn.qqtheme.framework.util.ToastUtils; /** * 驾校订单确认页面 */ public class FahrschuleOrderNumFragment extends BaseRefreshJxFragment implements View.OnClickListener, IFahrschuleOrderNumFtyContract.IFahrschuleOrderNumFtyView { private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; /** * 订单号: */ private TextView mTvOrderTitle; private TextView mTvOrder; /** * 报名人: */ private TextView mTvSignUpTitle; private TextView mTvSignUp; /** * 报名人手机: */ private TextView mTvPhoneTitle; private TextView mTvPhone; /** * 报名人身份证: */ private TextView mTvIdentityCardTitle; private TextView mTvIdentityCard; /** * 报名课程: */ private TextView mTvCourseTitle; private TextView mTvCourse; /** * 支付方式: */ private TextView mTvPayTypeTitle; private TextView mTvPayType; private LinearLayout mLayLine; /** * 订单金额: */ private TextView mTvMoneyTitle; private TextView mTvMoney; /** * 订单确认 */ private TextView mTvIntroduce; /** * 去支付 */ private Button mBtnPay; /** * P */ private IFahrschuleOrderNumFtyContract.IFahrschuleOrderNumFtyPresenter mPresenter; public static FahrschuleOrderNumFragment newInstance() { return new FahrschuleOrderNumFragment(); } public static FahrschuleOrderNumFragment newInstance(String param1, String param2) { FahrschuleOrderNumFragment fragment = new FahrschuleOrderNumFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } protected boolean isRefresh() { return false; } @Override protected void onRefreshData() { } @Override protected int getFragmentLayoutResId() { return R.layout.fragment_fahrschule_order_num; } @Override protected void initFragmentView(View view) { initView(view); FahrschuleOrderNumPresenter mPresenter = new FahrschuleOrderNumPresenter( Injection.provideRepository(getActivity().getApplicationContext()), this); } @Override public void setPresenter(IFahrschuleOrderNumFtyContract.IFahrschuleOrderNumFtyPresenter presenter) { mPresenter = presenter; } @Override protected void onFirstDataVisible() { EventBus.getDefault().register(this); } @Override protected void DestroyViewAndThing() { EventBus.getDefault().removeStickyEvent(FahrschuleApplyEvent.class); EventBus.getDefault().unregister(this); if (mPresenter != null) mPresenter.unSubscribe(); } @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void onMainEvent(FahrschuleApplyEvent event) { if (event != null) initData(event); } private void initData(FahrschuleApplyEvent event) { String orderId = event.getOrderId(); CreateOrderDTO createOrder = event.getCreateOrder(); String course = event.getCourseSel(); mTvOrder.setText(orderId); mTvSignUp.setText(createOrder.getUserName()); mTvPhone.setText(createOrder.getPhone()); mTvIdentityCard.setText(createOrder.getIdCard()); mTvCourse.setText(course); mTvMoney.setText(createOrder.getPrice()); } public void initView(View view) { mTvOrderTitle = (TextView) view.findViewById(R.id.tv_order_title); mTvOrder = (TextView) view.findViewById(R.id.tv_order); mTvSignUpTitle = (TextView) view.findViewById(R.id.tv_sign_up_title); mTvSignUp = (TextView) view.findViewById(R.id.tv_sign_up); mTvPhoneTitle = (TextView) view.findViewById(R.id.tv_phone_title); mTvPhone = (TextView) view.findViewById(R.id.tv_phone); mTvIdentityCardTitle = (TextView) view.findViewById(R.id.tv_identity_card_title); mTvIdentityCard = (TextView) view.findViewById(R.id.tv_identity_card); mTvCourseTitle = (TextView) view.findViewById(R.id.tv_course_title); mTvCourse = (TextView) view.findViewById(R.id.tv_course); mTvPayTypeTitle = (TextView) view.findViewById(R.id.tv_pay_type_title); mTvPayType = (TextView) view.findViewById(R.id.tv_pay_type); mLayLine = (LinearLayout) view.findViewById(R.id.lay_line); mTvMoneyTitle = (TextView) view.findViewById(R.id.tv_money_title); mTvMoney = (TextView) view.findViewById(R.id.tv_money); mTvIntroduce = (TextView) view.findViewById(R.id.tv_introduce); mBtnPay = (Button) view.findViewById(R.id.btn_pay); mBtnPay.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_pay://支付 if (mPresenter != null) { String moneyString = mTvMoney.getText().toString(); double money = Double.parseDouble(moneyString); int intMoney = (int) money * 100; String stringMoney = String.valueOf(intMoney); mPresenter.getBankPayHtml( mTvOrder.getText().toString(), stringMoney); GlobalConfig.getInstance().eventIdByUMeng(30); } break; default: break; } } @Override public void showLoadingDialog() { showDialogLoading(); } @Override public void dismissLoadingDialog() { hideDialogLoading(); } /** * 支付调用成功 */ @Override public void onPayOrderByCouponError(String message) { dismissLoadingDialog(); ToastUtils.toastShort(message); } @Override public void onPayOrderByCouponSucceed(PayOrderResult result) { if (!PublicData.getInstance().loginFlag && !TextUtils.isEmpty(PublicData.getInstance().userID)) { Intent intent = new Intent(getActivity(), LoginActivity.class); getActivity().startActivity(intent); } else { Intent intent = new Intent(getActivity(), FahrschulePayBrowserActivity.class); intent.putExtra(GlobalConstant.putExtra.web_title_extra, "支付"); intent.putExtra(GlobalConstant.putExtra.web_url_extra, result.getData()); intent.putExtra(GlobalConstant.putExtra.web_order_id_extra, mTvOrder.getText().toString()); getActivity().startActivityForResult(intent, GlobalConstant.requestCode.fahrschule_order_num_web); } } }
import com.google.gson.JsonParser; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.StringDeserializer; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.time.Duration; import java.util.Arrays; import java.util.Properties; public class ElasticSearchConsumer { //creating elasticsearch client public static RestHighLevelClient createClient(){ //credentials for bonsai String hostname=""; String username=""; String password=""; //this part for bonsai secure mode, if it is local elastic search connection we don't need this part final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username,password)); // RestClientBuilder builder = RestClient.builder(new HttpHost(hostname,443,"https")) //connect over http to the hostname over port 443 .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) { return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } }); RestHighLevelClient client = new RestHighLevelClient(builder); return client; } public static KafkaConsumer<String,String> createKafkaConsumer(String topic){ String bootstrapServer = "185.86.4.155:9092"; String groupId="Elastic-Consumer2"; //consumer configs Properties prop = new Properties(); prop.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,bootstrapServer); //where my kafka server is running prop.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());//to deserialize key of content of topic prop.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());//to deserialize value of content of topic prop.setProperty(ConsumerConfig.GROUP_ID_CONFIG,groupId); //consumer group id prop.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest"); prop.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false"); //disable autocommit of offsets prop.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG,"5"); //create consumer KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(prop); consumer.subscribe(Arrays.asList(topic)); //subscribe consumer to topic so that it will read from that topic. return consumer; } public static void main(String[] args) throws IOException { Logger logger = LoggerFactory.getLogger(ElasticSearchConsumer.class.getName()); //application logger //create client RestHighLevelClient elasticClient = createClient(); //create consumer KafkaConsumer<String ,String> elasticConsumer = createKafkaConsumer("important-tweets"); //loop to poll records from kafka and save into elastic search cluster while(true){ ConsumerRecords<String,String> records = elasticConsumer.poll(Duration.ofMillis(100)); // polling records from kafka topic "twitter-tweets" Integer recordCount = records.count(); //logger.info("Received " +recordCount+" records."); BulkRequest bulkRequest=new BulkRequest(); // instead of making request to elastic for every record, we make one request for every 100 records for(ConsumerRecord<String ,String> record:records){ try{ String id = extractIdfromTweet(record.value()); //to make consumer idempotent we use twitter id to index elastic search id. IndexRequest indexRequest= new IndexRequest( "twitter" ).id(id).source(record.value(), XContentType.JSON); //saving as Json bulkRequest.add(indexRequest); //add request to make all together. //logger.info(id); }catch (NullPointerException e){ logger.warn("Skipping bad data: " +record.value()); //in case of bad tweets. } } if(recordCount>0){ BulkResponse bulkItemResponses=elasticClient.bulk(bulkRequest,RequestOptions.DEFAULT); logger.info("All records are saved to Elastic Search"); logger.info("Committing offsets..."); elasticConsumer.commitSync(); // committing offsets after we write all 100 records to elastic so that we will not lose data. logger.info("Offsets have been committed."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } //elasticClient.close(); } private static JsonParser jsonParser = new JsonParser(); //to parse tweet id from json string in record. private static String extractIdfromTweet(String tweetJson) { return jsonParser.parse(tweetJson) .getAsJsonObject() .get("id_str") .getAsString(); } }
package cn.kitho.core.model; public class LinkArticleKeyWords { private Integer id; private Integer articleId; private Integer keyWordsId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getArticleId() { return articleId; } public void setArticleId(Integer articleId) { this.articleId = articleId; } public Integer getKeyWordsId() { return keyWordsId; } public void setKeyWordsId(Integer keyWordsId) { this.keyWordsId = keyWordsId; } }
public class DoublyLinkedListNode { public int data; public DoublyLinkedListNode next; public DoublyLinkedListNode prev; public DoublyLinkedListNode() { this.data = 0; this.next = null; this.prev = null; } public DoublyLinkedListNode(int data) { this.data = data; SinglyLinkedListNode next; } }
package com.xianzaishi.wms.tmscore.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.xianzaishi.wms.tmscore.vo.DistributionWaitSeqVO; import com.xianzaishi.wms.tmscore.vo.DistributionWaitSeqQueryVO; import com.xianzaishi.wms.common.exception.BizException; import com.xianzaishi.wms.tmscore.service.itf.IDistributionWaitSeqService; import com.xianzaishi.wms.tmscore.manage.itf.IDistributionWaitSeqManage; public class DistributionWaitSeqServiceImpl implements IDistributionWaitSeqService { @Autowired private IDistributionWaitSeqManage distributionWaitSeqManage = null; public IDistributionWaitSeqManage getDistributionWaitSeqManage() { return distributionWaitSeqManage; } public void setDistributionWaitSeqManage( IDistributionWaitSeqManage distributionWaitSeqManage) { this.distributionWaitSeqManage = distributionWaitSeqManage; } public Boolean addDistributionWaitSeqVO( DistributionWaitSeqVO distributionWaitSeqVO) { distributionWaitSeqManage .addDistributionWaitSeqVO(distributionWaitSeqVO); return true; } public List<DistributionWaitSeqVO> queryDistributionWaitSeqVOList( DistributionWaitSeqQueryVO distributionWaitSeqQueryVO) { return distributionWaitSeqManage .queryDistributionWaitSeqVOList(distributionWaitSeqQueryVO); } public DistributionWaitSeqVO getDistributionWaitSeqVOByID(Long id) { return (DistributionWaitSeqVO) distributionWaitSeqManage .getDistributionWaitSeqVOByID(id); } public Boolean modifyDistributionWaitSeqVO( DistributionWaitSeqVO distributionWaitSeqVO) { return distributionWaitSeqManage .modifyDistributionWaitSeqVO(distributionWaitSeqVO); } public Boolean deleteDistributionWaitSeqVOByID(Long id) { return distributionWaitSeqManage.deleteDistributionWaitSeqVOByID(id); } public boolean assign(DistributionWaitSeqVO distributionWaitSeqVO) { return distributionWaitSeqManage.assign(distributionWaitSeqVO); } public boolean assignToNormal(DistributionWaitSeqVO distributionWaitSeqVO) { return distributionWaitSeqManage.assignToNormal(distributionWaitSeqVO); } public boolean deleteByDistributionID(Long distributionID) { return distributionWaitSeqManage.deleteByDistributionID(distributionID); } }
package Exercise1; import java.util.stream.IntStream; public class Q2 { public static void main(String[] args) { //without parallel IntStream.range(1,11).forEach(num->{ try { Thread.sleep(1000); } catch (Exception ex){ } System.out.println(num); }); //with parallel IntStream.range(1,11).parallel().forEach(num->{ try { Thread.sleep(1000); } catch (Exception ex){ } System.out.println(num); }); } }
package evolutionYoutube; import com.vaadin.navigator.View; import com.vaadin.ui.Button; import com.vaadin.ui.UI; import com.vaadin.ui.Button.ClickEvent; public class Lista_Usuarios extends Lista_Usuarios_ventana implements View{ /** * */ private static final long serialVersionUID = 1L; public Mi_perfil_Admin _unnamed_Mi_perfil_Admin_; public Lista_Usuario _unnamed_Lista_Usuario_; public Lista_Video_Usuario _unnamed_Lista_Video_Usuario_; public Lista_Usuarios() { listausuarios.addComponent(new Lista_Usuario()); principal.addClickListener(new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { ((MyUI) UI.getCurrent()).administrador(); } }); micuenta.addClickListener(new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { ((MyUI) UI.getCurrent()).Mi_perfil_Admin(); } }); lista_usuarios.addClickListener(new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { ((MyUI) UI.getCurrent()).listausuarios(); } }); categorias.addClickListener(new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { ((MyUI) UI.getCurrent()).Categorias(); } }); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DAO; import Model.Users; import java.util.ArrayList; /** * * @author yasmine.mabrouk */ public class Main { public static void main(String[] args) { CommentaireDAO commentaireDAO = new CommentaireDAO(); ArrayList<Users> list = commentaireDAO.top5Commentaire(); for (int i=0 ; i <= list.size()-1 ; i++ ){ System.out.println("user " + list.get(i).getUsername()); } } }
package libraryproject.repositories; import libraryproject.domain.book.BorrowQueue; import libraryproject.domain.book.PaperBook; import java.util.HashSet; import java.util.Set; public class QueueRepository { private static Set<BorrowQueue> queues; public QueueRepository() { queues = new HashSet<>(); } public static void addQueue(PaperBook paperBook) { if (paperBook == null) { throw new IllegalArgumentException("paperBook can not be null!"); } queues.add(new BorrowQueue(paperBook)); } public static BorrowQueue getQueueByBook(PaperBook paperBook) { if (paperBook == null) { throw new IllegalArgumentException("PaperBook can not be null!"); } BorrowQueue temp = null; for(BorrowQueue borrowQueue : queues) { if (borrowQueue.getBook().getTitle().equals(paperBook.getTitle())) { temp = borrowQueue; } if (temp != null) { return temp; } } return null; } public HashSet<BorrowQueue> getAllQueues() { return new HashSet<>(queues); } }
package de.niklaskiefer.bnclCore; import de.niklaskiefer.bnclCore.BnclToXmlWriter; import de.niklaskiefer.bnclCore.MainApplication; import de.niklaskiefer.bnclCore.commons.BnclRandomUtils; import de.niklaskiefer.bnclCore.parser.BnclEventParser; import de.niklaskiefer.bnclCore.parser.BnclTaskParser; import org.junit.Before; import org.junit.Test; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.ByteArrayInputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * @author Niklas Kiefer */ public class BnclToXmlWriterTest { private BnclToXmlWriter bnclToXmlWriter; private BnclEventParser eventParser; private BnclTaskParser taskParser; private final String testBncl = MainApplication.testBncl; @Before public void setUp() { bnclToXmlWriter = new BnclToXmlWriter(); eventParser = new BnclEventParser(); taskParser = new BnclTaskParser(); } @Test public void testCreateBPMNFile() { try { String xml = bnclToXmlWriter.convertBnclToXML(testBncl); assertNotNull(xml); // todo: test xml components } catch (Exception e) { assertEquals(1, 2); //test failed e.printStackTrace(); } } @Test public void testCreateBPMNFileFalseBeginning() { String falseBncl; boolean failed = false; try { falseBncl = "lets create process with startevent " + "signed startEvent1 called startevent1 with endevent" + "signed endevent1 called endevent1 with sequenceflow " + "comesfrom startevent1 goesto endevent1"; bnclToXmlWriter.createBPMNFile(falseBncl); } catch (Exception e) { failed = true; } assertTrue(failed); } @Test public void testCreateBPMNFileNoId() { String falseBncl; boolean failed = false; try { falseBncl = "lets create a process with startevent called startevent1 with endevent signed endevent1 called endevent1 with sequenceflow comesfrom startevent1 goesto endevent1"; bnclToXmlWriter.createBPMNFile(falseBncl); } catch (Exception e) { failed = true; } assertTrue(failed); } @Test public void testParsingAllEventAndTaskTypes() { String bncl = generateTestBnclWithEverything(); assertNotNull(bncl); try { String xml = bnclToXmlWriter.convertBnclToXML(bncl); assertNotNull(xml); xml = xml.replace("\r", "").replace("\n", ""); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes())); assertNotNull(doc); } catch (Exception e) { assertEquals(1, 2); //test failed e.printStackTrace(); } } @Test public void testConvertBnclFileToXML() { String fileName = "test.bncl"; try { String xml = bnclToXmlWriter.convertBnclFileToXML(fileName); assertNotNull(xml); } catch (Exception e) { assertEquals(1, 2); //test failed e.printStackTrace(); } } private String generateTestBnclWithEverything() { StringBuilder sb = new StringBuilder(); sb.append("lets create a process "); for (BnclEventParser.EventElement element : eventParser.getEventTypes()) { sb.append(" with "); sb.append(element.getKeyword()); sb.append(" signed "); sb.append(BnclRandomUtils.getSaltString()); } for (BnclTaskParser.TaskElement element : taskParser.getTaskTypes()) { sb.append(" with "); sb.append(element.getKeyword()); sb.append(" signed "); sb.append(BnclRandomUtils.getSaltString()); } return sb.toString(); } }
public class Arrays_Promedio { public static void main(String[] args) { int[] numbers = new int[7]; int add=0; for (int i = 0; i<7 ;i++) { numbers[i] = Numbers.RandomNumber(); } for (int i=0; i<7 ;i++ ) { add = add+numbers[i]; System.out.println(numbers[i]); } System.out.println("El promedio es: "+(add/numbers.length)); } public static class Numbers { public static int RandomNumber() { int min = 1, max = 100, randomNumber; randomNumber = (int)(Math.random()* ( max - min + 1) + min); return randomNumber; } } }
package com._520it.transfer.service; import java.sql.SQLException; import com._520it.transfer.dao.MyTransferDao; import com._520it.utils.MyDataSourceUtils; public class MyTransferService { public boolean tansfer(String out, String in, String money) { boolean transfer=true; try { //开启事务 MyDataSourceUtils.startTransaction(); //调用dao层的转入和转出方法 MyTransferDao dao=new MyTransferDao(); dao.in(in,money); //模拟停电 int i=1/0; dao.out(out,money); } catch (Exception e) { try { MyDataSourceUtils.rollbackTransaction(); } catch (SQLException e1) { e1.printStackTrace(); } transfer=!transfer; e.printStackTrace(); }finally { try { MyDataSourceUtils.commitTransaction(); } catch (SQLException e) { e.printStackTrace(); } } return transfer; } }
package common; import java.net.DatagramPacket; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; /** * @author korektur * 25/03/16 */ public class ServerConnectionEstablishPacketBuilder { private final ServerConnectionEstablishPacket packet; public ServerConnectionEstablishPacketBuilder() { packet = new ServerConnectionEstablishPacket(); } public ServerConnectionEstablishPacketBuilder setInetAddress(InetAddress inetAddress) { packet.inetAddress = inetAddress; return this; } public ServerConnectionEstablishPacketBuilder setPort(int port) { this.packet.port = port; return this; } public DatagramPacket build() { ByteBuffer buffer = ByteBuffer.allocate(packet.inetAddress.getAddress().length + Integer.BYTES); buffer.put(packet.inetAddress.getAddress()); buffer.putInt(packet.port); try { InetAddress inetAddress = InetAddress.getByName(Constants.ANYCAST_ADDRESS); return new DatagramPacket(buffer.array(), buffer.limit(), inetAddress, Constants.SERVER_IDENTIFICATION_PORT); } catch (UnknownHostException e) { throw new IllegalStateException("Error, while getting InetAddress, msg = " + e.getMessage()); } } }
/* * (C) Copyright IBM Corp. 2020. * * 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.ibm.cloud.cloudant.v1.model; import com.ibm.cloud.cloudant.v1.model.Security; import com.ibm.cloud.cloudant.v1.model.SecurityObject; import com.ibm.cloud.cloudant.v1.utils.TestUtilities; import com.ibm.cloud.sdk.core.service.model.FileWithMetadata; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * Unit test class for the Security model. */ public class SecurityTest { final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap(); final List<FileWithMetadata> mockListFileWithMetadata = TestUtilities.creatMockListFileWithMetadata(); @Test public void testSecurity() throws Throwable { SecurityObject securityObjectModel = new SecurityObject.Builder() .names(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))) .roles(new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))) .build(); assertEquals(securityObjectModel.names(), new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))); assertEquals(securityObjectModel.roles(), new java.util.ArrayList<String>(java.util.Arrays.asList("testString"))); Security securityModel = new Security.Builder() .admins(securityObjectModel) .members(securityObjectModel) .cloudant(new java.util.HashMap<String, List<String>>() { { put("foo", new java.util.ArrayList<String>(java.util.Arrays.asList("_reader"))); } }) .couchdbAuthOnly(true) .build(); assertEquals(securityModel.admins(), securityObjectModel); assertEquals(securityModel.members(), securityObjectModel); assertEquals(securityModel.cloudant(), new java.util.HashMap<String, List<String>>() { { put("foo", new java.util.ArrayList<String>(java.util.Arrays.asList("_reader"))); } }); assertEquals(securityModel.couchdbAuthOnly(), Boolean.valueOf(true)); String json = TestUtilities.serialize(securityModel); Security securityModelNew = TestUtilities.deserialize(json, Security.class); assertTrue(securityModelNew instanceof Security); assertEquals(securityModelNew.admins().toString(), securityObjectModel.toString()); assertEquals(securityModelNew.members().toString(), securityObjectModel.toString()); assertEquals(securityModelNew.couchdbAuthOnly(), Boolean.valueOf(true)); } }
package com.example.imageview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button rdoDayang, rdoBeared, rdoRajesh; private ImageView imgView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Creating a reference rdoDayang = findViewById(R.id.rdoDayang); rdoBeared = findViewById(R.id.rdoBeared); rdoRajesh = findViewById(R.id.rdoRajesh); imgView = findViewById(R.id.imgView); rdoDayang.setOnClickListener(this); rdoBeared.setOnClickListener(this); rdoRajesh.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { // case R.id.rdoDayang: Toast toastDayang = Toast.makeText(MainActivity.this,"message",Toast.LENGTH_LONG); // toastDayang.show(); case R.id.rdoDayang: imgView.setImageResource(R.drawable.dayang); break; // Toast toastBeard = Toast.makeText(MainActivity.this,"message",Toast.LENGTH_SHORT); // toastBeard.show(); case R.id.rdoBeared: imgView.setImageResource(R.drawable.beared); break; // Toast toastRajesh = Toast.makeText(MainActivity.this,"message",Toast.LENGTH_LONG); // toastRajesh.show(); case R.id.rdoRajesh: imgView.setImageResource(R.drawable.rajesh); break; } } }
package okhttp_tools; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.Callable; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Created by Administrator on 2017/5/24. */ public class handler implements Callable { public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8"); public String responseData = null; public String jsonData = null; public String URL = null; public String Header = null; public int operation; // 0:post 1: put 2: delete 3:get public handler(String URL, String jsonData, String header, int operation) { this.jsonData = jsonData; this.URL = URL; this.Header = header; this.operation = operation; } @Override public ArrayList call() throws Exception { OkHttpClient client = new OkHttpClient(); ArrayList result = new ArrayList(); RequestBody requestBody = RequestBody.create(JSON, jsonData); switch (operation) { case 0: Request request = new Request.Builder().url(URL).addHeader("Authorization", "Bearer " + Header).addHeader("Content-Type", "application/json").post(requestBody).build(); try { Response response = client.newCall(request).execute(); responseData = response.body().string(); String res = responseData; result.add(response.code() + ""); result.add(res); } catch (IOException e) { e.printStackTrace(); } break; case 1: Request request1 = new Request.Builder().url(URL).addHeader("Authorization", "Bearer " + Header).addHeader("Content-Type", "application/json").put(requestBody).build(); try { Response response = client.newCall(request1).execute(); responseData = response.body().string(); String res = responseData; result.add(response.code() + ""); result.add(res); } catch (IOException e) { e.printStackTrace(); } break; case 2: Request request2 = new Request.Builder().url(URL).addHeader("Authorization", "Bearer " + Header).addHeader("Content-Type", "application/json").delete(requestBody).build(); try { Response response = client.newCall(request2).execute(); responseData = response.body().string(); String res = responseData; result.add(response.code() + ""); result.add(res); } catch (IOException e) { e.printStackTrace(); } break; case 3: Request request3 = new Request.Builder().url(URL).addHeader("Authorization", "Bearer " + Header).addHeader("Content-Type", "application/json").build(); try { Response response = client.newCall(request3).execute(); responseData = response.body().string(); String res = responseData; result.add(response.code() + ""); result.add(res); } catch (IOException e) { e.printStackTrace(); } break; } return result; } }
/** * * Name : Lang, Wesley * Task : 151. Reverse Words in a String * Date : December 1, 2016 * Course : LeetCode - Algorithms - Medium * Description: Given an input string, reverse the string word by word. * */ public class ReverseWord { public static void main(String [] args){ String sub = "Thisssss isssss my test sentence."; System.out.println(reverseWords(sub)); } public static String reverseWords(String s) { StringBuilder res = new StringBuilder(); for (int start = s.length() - 1; start >= 0; start--) { //for loop starting from opposite end if (s.charAt(start) == ' ') { //if value at start is space continue loop continue; } int end = start; while (start >= 0 && s.charAt(start) != ' ') { // start--; } res.append(s.substring(start + 1, end + 1)).append(" "); } return res.toString().trim(); } }
package Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.stream.Stream; import java.util.List; public class Lexer { private StringBuilder input = new StringBuilder(); //Входной поток с файла private Token token; //Токен private String lexema; //Полученная лексема private boolean exhausted = false; //Ошибка private String errorMessage = ""; private Set<Character> blankChars = new HashSet<Character>(); //таблице хэшей private LinkedList<String> mass_values = new LinkedList<>(); private LinkedList<Token> mass_tok = new LinkedList<>(); private void add_elem(String lexema, Token token) { mass_values.addLast(lexema); mass_tok.addLast(token); } public String return_values(int i) { return mass_values.get(i); } public int return_quantity() { return mass_values.size(); } public Token return_token (int i) { return mass_tok.get(i); } public Lexer(String filePath) { //Добавляем во входной поток содержимое файла, если нет файла, то ссылаемся на ошибку try (Stream<String> st = Files.lines(Paths.get(filePath))) { st.forEach(input::append); } catch (IOException ex) { exhausted = true; errorMessage = "Could not read file: " + filePath; return; } input.append(" "); blankChars.add('\r'); blankChars.add('\n'); blankChars.add((char) 8); blankChars.add((char) 9); blankChars.add((char) 11); blankChars.add((char) 12); blankChars.add((char) 32); //В таблицу хэшев добавляем пробел, табуляцию, перенос на новую строчку и т.д. moveAhead(); //Двигаемся вперед } public void moveAhead() { if (exhausted) { return; } if (input.length() == 0) { //Длина содержимого файла равна 0, то ошибка exhausted = true; return; } ignoreWhiteSpaces(); //Удаляем пробелы/иные неопознанные символы, которые можно проигнорировать if (findNextToken()) { //Проверяем на существование следующего токена return; } exhausted = true; if (input.length() > 0) { //Файл не пустой, но встречен был неясный символ, вывод на ошибку errorMessage = "Unexpected symbol: '" + input.charAt(0) + "'"; } } private void ignoreWhiteSpaces() { //Сверяемся с таблицей хэшей, если есть такой символ, то передвигаем указатель дальше, если нет - удаляем int charsToDelete = 0; while ((blankChars.contains(input.charAt(charsToDelete) ) && (input.length() > charsToDelete+1))) { charsToDelete++; } if (input.length() == charsToDelete+1) { charsToDelete++; } if (charsToDelete > 0) { input.delete(0, charsToDelete); } } private boolean findNextToken() { for (Token t : Token.values()) { //Получаем весь список возможных токенов и проходимся по нему int end = t.endOfMatch(input.toString()); if (end != -1) { token = t; lexema = input.substring(0, end); add_elem(lexema, token); input.delete(0, end); return true; } } return false; } public Token currentToken() { //Возвращает текущий токен return token; } public String currentLexema() { //Возвращает текущую лексему return lexema; } public boolean isSuccessful() { return errorMessage.isEmpty(); } public String errorMessage() { //Возвращает найденную ошибку в качестве сообщения return errorMessage; } public boolean isExhausted() { //Возвращает существование ошибки return exhausted; } }
package com.example.awesoman.owo2_comic.ui.ComicLocal.adapter; import android.content.Context; import android.text.Layout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.awesoman.owo2_comic.R; import java.util.List; /** * Created by Awesome on 2017/3/30. */ public class ChooseChapterAdapter extends BaseAdapter { private List<String> mData ; private LayoutInflater inflater; private IChooseChapter listener; public void setListener(IChooseChapter listener) { this.listener = listener; } public ChooseChapterAdapter(Context context) { inflater = LayoutInflater.from(context); } public void setmData(List<String> mData) { this.mData = mData; } @Override public int getCount() { return mData.size(); } @Override public Object getItem(int position) { return mData.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { MyHolder holder = null; if(convertView ==null){ convertView = inflater.inflate(R.layout.item_choose_chapter,null); holder = new MyHolder(convertView); convertView.setTag(holder); } else{ holder = (MyHolder)convertView.getTag(); } holder.nameTxt .setText(mData.get(position)); holder.view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.chooseChapter(position); } }); return convertView; } class MyHolder{ public MyHolder(View view) { this.view = view; nameTxt = (TextView) view.findViewById(R.id.name); } View view; TextView nameTxt; } public interface IChooseChapter{ void chooseChapter(int position); } }
package finalassignment; public class Employee { String employeename; int employeeid; Employee(){ Employee emp1 = new Employee(); emp1.employeename = "rofiq"; emp1.employeeid = 1000; Employee emp2 = new Employee(); emp2.employeename = "karim"; emp2.employeeid = 1001; } }
package com.springD.framework.taglibs; import java.util.ArrayList; import java.util.List; import org.springframework.util.CollectionUtils; import com.springD.framework.utils.StringUtils; /** * 权限相关 * @author Chenz * */ public class PermissionFunction { public static boolean isIn(String iterableStr, Object element) { //Iterable iterable Iterable iterable = string2List(iterableStr); if(iterable == null) { return false; } return CollectionUtils.contains(iterable.iterator(), element); } /** * 将string的内容转为list * @param roleIds * @return */ public static List<String> string2List(String strIds){ List<String> idsList = new ArrayList<String>(); if(strIds!=null){ try { String[] roleIdStrs = strIds.split(","); for(String roleIdStr : roleIdStrs) { if(StringUtils.isEmpty(roleIdStr)) { continue; } idsList.add(roleIdStr); } } catch (Exception e) { System.out.println("出异常了strIds==>"+strIds); } } return idsList; } }
package com.melodygram.database; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import com.melodygram.model.ContactsModel; /** * Created by LALIT on 15-06-2016. */ public class AppContactDataSource { private SQLiteDatabase sqlDatabase; private DbSqliteHelper sqlHelper; private String[] allColumns = {DbSqliteHelper.appContactsUserId, DbSqliteHelper.appContactsName, DbSqliteHelper.appLocalContactsName, DbSqliteHelper.appContactsCountryCode, DbSqliteHelper.appContactsCountry, DbSqliteHelper.appContactsMobileNo, DbSqliteHelper.appContactsLastSeen, DbSqliteHelper.appContactsProfilePic, DbSqliteHelper.appContactsStatus, DbSqliteHelper.appContactsGender, DbSqliteHelper.appProfilePicPrivacy, DbSqliteHelper.appLastSeenPrivacy, DbSqliteHelper.appStatusPrivacy, DbSqliteHelper.appOnlinePrivacy, DbSqliteHelper.appReadReceiptsPrivacy, DbSqliteHelper.appNotfication, DbSqliteHelper.appMuteChat}; public AppContactDataSource(Context context) { sqlHelper = new DbSqliteHelper(context); } public void open() throws SQLException { sqlDatabase = sqlHelper.getWritableDatabase(); } public void close() { sqlHelper.close(); } public Long createContacts(ContentValues values) { Long insertId = sqlDatabase.insert(DbSqliteHelper.appContactTable, null, values); return insertId; } public int updateContacts(ContentValues values, String contactNumber) { int insertId = sqlDatabase.update(DbSqliteHelper.appContactTable, values, DbSqliteHelper.appContactsUserId + " = " + "'" + contactNumber + "'", null); return insertId; } public LinkedHashMap<String, ContactsModel> getAllContacts() { LinkedHashMap<String, ContactsModel> appContactsList = new LinkedHashMap<String, ContactsModel>(); Cursor cursor = sqlDatabase.query(DbSqliteHelper.appContactTable, allColumns, null, null, null, null,DbSqliteHelper.appLocalContactsName); cursor.moveToFirst(); while (!cursor.isAfterLast()) { ContactsModel appContactModel = cursorToContactsList(cursor); appContactsList.put(cursor.getString(5), appContactModel); cursor.moveToNext(); } cursor.close(); return appContactsList; } public ArrayList<ContactsModel> getAllContacts( final LinkedHashMap<String, ContactsModel> contactsHashMap) { ArrayList<ContactsModel> appContactsList = new ArrayList<ContactsModel>(); Cursor cursor = sqlDatabase.query(DbSqliteHelper.appContactTable, allColumns, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { ContactsModel appContactModel = cursorToContactsList(cursor); ContactsModel phContactModel = contactsHashMap.get(appContactModel .getPhContactNumber()); if (phContactModel != null) { appContactModel.setPhContactName(phContactModel .getPhContactName()); } appContactsList.add(appContactModel); cursor.moveToNext(); } cursor.close(); return appContactsList; } public LinkedHashMap<String, String> getContactsId() { LinkedHashMap<String, String> appContactsList = new LinkedHashMap<String, String>(); String[] column = {DbSqliteHelper.appContactsUserId}; Cursor cursor = sqlDatabase.query(DbSqliteHelper.appContactTable, column, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { appContactsList.put(cursor.getString(0), cursor.getString(0)); cursor.moveToNext(); } cursor.close(); return appContactsList; } public List<ContactsModel> isContactAvailable(String appContactsMobileNo) { List<ContactsModel> appContactsList = new ArrayList<ContactsModel>(); Cursor cursor = sqlDatabase.query(DbSqliteHelper.appContactTable, allColumns, DbSqliteHelper.appContactsMobileNo + " = " + "'" + appContactsMobileNo + "'", null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { ContactsModel appContactModel = cursorToContactsList(cursor); appContactsList.add(appContactModel); cursor.moveToNext(); } cursor.close(); return appContactsList; } public boolean isContactAvailableOrNot(String userId) { Cursor cursor = sqlDatabase.query(DbSqliteHelper.appContactTable, new String[]{DbSqliteHelper.appContactsUserId}, DbSqliteHelper.appContactsUserId + "=?", new String[]{userId}, null, null, null, null); if (cursor.getCount() > 0) return true; else return false; } public String getContactNumber(String userId) { Cursor cursor = sqlDatabase.query(DbSqliteHelper.appContactTable, new String[]{DbSqliteHelper.appLocalContactsName}, DbSqliteHelper.appContactsUserId + "=?", new String[]{userId}, null, null, null, null); String name = null; if (cursor.getCount() > 0) { cursor.moveToFirst(); return cursor.getString(0); } else return name; } public boolean isApplicationUser(String phNumber) { Cursor cursor = sqlDatabase.query(DbSqliteHelper.appContactTable, new String[]{DbSqliteHelper.appContactsMobileNo}, DbSqliteHelper.appContactsMobileNo + " = " + "'" + phNumber + "'", null, null, null, null); if (cursor.getCount() > 0) return true; else return false; } public void deleteContactsLists() { sqlDatabase.delete(DbSqliteHelper.appContactTable, null, null); } public void updateChatDeleteFlag() { ContentValues values = new ContentValues(); values.put(DbSqliteHelper.CONTACT_DELETE_FLAG, "0"); sqlDatabase.update(DbSqliteHelper.appContactTable, values, null, null); } public void deleteSeletedContactsList() { sqlDatabase.delete(DbSqliteHelper.appContactTable, DbSqliteHelper.CONTACT_DELETE_FLAG + " = " + "'" + 0 + "'", null); } private ContactsModel cursorToContactsList(Cursor cursor) { ContactsModel appContactModel = new ContactsModel(); appContactModel.setAppContactsUserId(cursor.getString(0)); appContactModel.setAppContactName(cursor.getString(1)); appContactModel.setPhContactName(cursor.getString(2)); appContactModel.setAppContactsCountryCode(cursor.getString(3)); appContactModel.setPhContactNumber(cursor.getString(5)); appContactModel.setContactType("app"); appContactModel.setChatType("onetoone"); appContactModel.setContactsLastSeen(""); appContactModel.setAppContactsProfilePic(cursor.getString(7)); appContactModel.setPhChatContactStatus(cursor.getString(8)); appContactModel.setGender(cursor.getString(9)); appContactModel.setProfilePicPrivacy(cursor.getString(10)); appContactModel.setLastSeenPrivacy(cursor.getString(11)); appContactModel.setStatusPrivacy(cursor.getString(12)); appContactModel.setOnlinePrivacy(cursor.getString(13)); appContactModel.setNotification(cursor.getString(14)); appContactModel.setMuteChat(cursor.getString(15)); return appContactModel; } public void updateDeleteFlag(String deleteFlag) { ContentValues values = new ContentValues(); values.put(DbSqliteHelper.CONTACT_DELETE_FLAG, deleteFlag); sqlDatabase.update(DbSqliteHelper.appContactTable, values, null, null); } }
package LimitDecimalNombre.AdditionnerTriEntier; public class addTriEntier { public static void main(String[] args) { String[] tEntier = {"5", "-1", "8", "-3", "12", "20", "-12"}; int somme = 0; for(int i = 0; i < tEntier.length; i++) { somme = somme + Integer.parseInt(tEntier[i]); } System.out.println("La somme est de : " + somme); // Tri du tableau String tampon = "0"; boolean b; do { b = false; for (int i = 0; i < tEntier.length - 1; i++) { if (Integer.parseInt(tEntier[i]) > (Integer.parseInt(tEntier[i + 1]))) { tampon = tEntier[i]; tEntier[i] = tEntier[i + 1]; tEntier[i + 1] = tampon; b = true; } } } while (b); for (int i = 0; i < tEntier.length - 1; i++) { System.out.println(tEntier[i]); } } }
package bspq21_e4.ParkingManagment.Classes; import static org.junit.Assert.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Locale; import org.databene.contiperf.PerfTest; import org.databene.contiperf.Required; import org.databene.contiperf.junit.ContiPerfRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import bspq21_e4.ParkingManagement.server.data.Parking; import bspq21_e4.ParkingManagement.server.data.PremiumUser; import bspq21_e4.ParkingManagement.server.data.Slot; import bspq21_e4.ParkingManagement.server.data.SlotAvailability; import junit.framework.JUnit4TestAdapter; public class SlotTest { private Parking P1; private Slot S1; private String s; final Logger logger = LoggerFactory.getLogger(SlotTest.class); static int iteration = 0; @Rule public ContiPerfRule rule = new ContiPerfRule(); public static junit.framework.Test suite() { return new JUnit4TestAdapter(SlotTest.class); } @Before public void setUp() throws ParseException { logger.info("Entering setUp: {}", iteration++); P1 = new Parking(1, "Getxo", 100, 50, 40, 2); S1 = new Slot(1, 165, 2, SlotAvailability.GREEN, P1.getId()); s = "Slot [pk=" + 1 + ", id=" + 165 + ", floor=" + 2 + ", sl=" + "GREEN" + ", idParking=" + 1 + "]"; logger.info("Leaving setUp"); } @Test @PerfTest(invocations = 1000, threads = 20) @Required(max = 120, average = 30) public void SlotClassTest() { assertEquals(S1.getClass(), Slot.class); } @Test public void getSlotPKTest() { assertEquals(1, S1.getPk()); } @Test public void setSlotPKTest() { S1.setPk(2); assertEquals(2, S1.getPk()); } @Test public void getSlotIdTest() { assertEquals(165, S1.getId()); } @Test public void setSlotIdTest() { S1.setPk(170); assertEquals(170, S1.getPk()); } @Test public void getSlotFloorTest() { assertEquals(2, S1.getFloor()); } @Test public void setSlotFloorTest() { S1.setFloor(1); assertEquals(1, S1.getFloor()); } @Test public void getSlotAvailabilityTest() { assertEquals(SlotAvailability.GREEN, S1.getSl()); } @Test public void setSlotAvailabilityTest() { S1.setSl(SlotAvailability.RED); assertEquals(SlotAvailability.RED, S1.getSl()); } @Test public void getSlotParkingTest() { assertEquals(P1.getId(), S1.getIdParking()); } @Test public void setSlotParkingTest() { P1.setId(2); S1.setIdParking(P1.getId()); assertEquals(P1.getId(), S1.getIdParking()); } @Test public void setSlotToStringTest() { assertEquals(S1.toString(), s); } }
package com.zhicai.byteera.activity.initialize; import android.content.Intent; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.lidroid.xutils.exception.DbException; import com.zhicai.byteera.R; import com.zhicai.byteera.activity.BaseActivity; import com.zhicai.byteera.activity.MainActivity; import com.zhicai.byteera.activity.bean.GuessDb; import com.zhicai.byteera.commonutil.ActivityUtil; import com.zhicai.byteera.commonutil.PreferenceUtils; import com.zhicai.byteera.commonutil.SDLog; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.Bind; import butterknife.OnClick; import butterknife.OnPageChange; @SuppressWarnings("unused") public class GuideActivity extends BaseActivity { @Bind(R.id.viewpager) ViewPager viewpager; @Bind(R.id.tv_jump) TextView tvJump; @Bind({R.id.iv_1,R.id.iv_2,R.id.iv_3}) ImageView[] dots; private final List<View> views = new ArrayList(); private View view3; @Override protected void loadViewLayout() { setContentView(R.layout.activity_guide); ButterKnife.bind(this); } @OnClick(R.id.tv_jump) void onClick(){ startApp(); } @OnPageChange(value = R.id.viewpager,callback = OnPageChange.Callback.PAGE_SELECTED) public void onPageSelected(int position){ for (int i=0;i<dots.length;i++) dots[i].setImageResource(position==i?R.drawable.point_selected:R.drawable.point_unselected); } @Override protected void initData() { views.add(getLayoutInflater().inflate(R.layout.item_guide_01, null)); views.add(getLayoutInflater().inflate(R.layout.item_guide_02, null)); view3 = getLayoutInflater().inflate(R.layout.item_guide_03, null); views.add(view3); viewpager.setAdapter(new vpAdapter()); } @Override protected void updateUI() { } @Override protected void processLogic() { ButterKnife.findById(view3,R.id.mstart).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startApp(); } }); } private void startApp() { PreferenceUtils.getInstance(baseContext).setStartGuide(true); createGuessDb(); goHome(); } protected void goHome() { ActivityUtil.startActivity(this, new Intent(this, MainActivity.class)); ActivityUtil.finishActivity(this); } public void createGuessDb(){ try { for (int i=0;i<8;i++) for (int j=1;j<4;j++) db.save(new GuessDb(i+1,j,1)); SDLog.d("GuideActivity","guessdb create is ok!"); } catch (DbException e) { e.printStackTrace(); } } private class vpAdapter extends PagerAdapter { @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(views.get(position)); } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(views.get(position)); return views.get(position); } @Override public int getCount() { return views.size(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } } }
package com.abt.middle.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import com.abt.middle.R; /** * @描述: @自定义分割线 * @作者: @黄卫旗 * @创建时间: @2017-04-25 */ public class BorderTextView extends AppCompatTextView { /** * 画笔 */ private Paint mPaint; /** * 边框颜色 */ private int mPaintColor; /** * 边框粗细 */ private float mBorderStrokeWidth; /** * 底边边线左边断开距离 */ private int mBorderBottomLeftMargin; /** * 底边边线右边断开距离 */ private int mBorderBottomRightMargin; /** * 是否需要上边框 */ private boolean mTopBorderVisible; /** * 是否需要左右边框 */ private boolean mLeftAndRightBorderVisible; /** * 是否需要下边框 */ private boolean mBottomBorderVisible; public BorderTextView(Context context) { this(context, null); } public BorderTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BorderTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // 获取自定义属性 TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.BorderTextView); mPaintColor = ta.getColor(R.styleable.BorderTextView_borderColor, Color.GRAY); mBorderStrokeWidth = ta.getDimensionPixelSize(R.styleable.BorderTextView_borderStrokeWidth, 0); mBorderBottomLeftMargin = ta.getDimensionPixelSize(R.styleable.BorderTextView_borderBottomLeftMargin, 0); mBorderBottomRightMargin = ta.getDimensionPixelSize(R.styleable.BorderTextView_borderBottomRightMargin, 0); mTopBorderVisible = ta.getBoolean(R.styleable.BorderTextView_topBorderVisible, true); mLeftAndRightBorderVisible = ta.getBoolean(R.styleable.BorderTextView_leftAndRightBorderVisible, false); mBottomBorderVisible = ta.getBoolean(R.styleable.BorderTextView_bottomBorderVisible, true); ta.recycle(); init(); } private void init() { mPaint = new Paint(); mPaint.setColor(mPaintColor); mPaint.setAntiAlias(true); mPaint.setStrokeWidth(mBorderStrokeWidth); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); // 画4个边 if (mTopBorderVisible) { canvas.drawLine(0, 0, this.getWidth(), 0, mPaint); } if (mBottomBorderVisible) { canvas.drawLine(mBorderBottomLeftMargin, this.getHeight(), this.getWidth() - mBorderBottomRightMargin, this.getHeight(), mPaint); } if (mLeftAndRightBorderVisible) { canvas.drawLine(0, 0, 0, this.getHeight(), mPaint); canvas.drawLine(this.getWidth(), 0, this.getWidth(), this.getHeight(), mPaint); } } /** * 设置边框颜色 * * @param color */ public void setBorderColor(int color) { mPaint.setColor(color); invalidate(); } /** * 设置边框宽度 * * @param size */ public void setBorderStrokeWidth(float size) { mPaint.setStrokeWidth(size); invalidate(); } /** * 设置是否需要顶部边框 * @param topBorderVisible */ public void setTopBorderVisible(boolean topBorderVisible) { mTopBorderVisible = topBorderVisible; invalidate(); } /** * 设置是否需要底部边框 * @param bottomBorderVisible */ public void setBottomBorderVisible(boolean bottomBorderVisible) { mBottomBorderVisible = bottomBorderVisible; invalidate(); } }
package com.fatihdogan.datastructure.list; import java.util.ArrayList; // ToDo public class PrintArrayList { }
package com.esum.wp.ims.chubuainfo.base; import com.esum.appframework.dmo.BaseDMO; /** * * Copyright(c) eSum Technologies, Inc. All rights reserved. */ public abstract class BaseChubUaInfo extends BaseDMO { // constructors public BaseChubUaInfo() { initialize(); } public BaseChubUaInfo(String interfaceId) { this.setInterfaceId(interfaceId); initialize(); } public BaseChubUaInfo(String interfaceId, String regDate, String modDate) { this.setInterfaceId(interfaceId); this.setRegDate(regDate); this.setModDate(modDate); initialize(); } protected void initialize() { useInbound = ""; clientId = ""; senderCode = ""; parsingRule = ""; regDate = ""; modDate = ""; } // primary key protected String interfaceId; // fields protected String useInbound; protected String clientId; protected String senderCode; protected String parsingRule; protected String regDate; protected String modDate; public String getInterfaceId() { return interfaceId; } public void setInterfaceId(String interfaceId) { this.interfaceId = interfaceId; } public String getUseInbound() { return useInbound; } public void setUseInbound(String useInbound) { this.useInbound = useInbound; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getSenderCode() { return senderCode; } public void setSenderCode(String senderCode) { this.senderCode = senderCode; } public String getParsingRule() { return parsingRule; } public void setParsingRule(String parsingRule) { this.parsingRule = parsingRule; } public String getRegDate() { return regDate; } public void setRegDate(String regDate) { this.regDate = regDate; } public String getModDate() { return modDate; } public void setModDate(String modDate) { this.modDate = modDate; } }
package com.lsjr.zizi.mvp.home; public class Constants { public static String INSTANT_MESSAGE="instant_message";//转发消息的标记 public static String INSTANT_MESSAGE_FILE="instant_message_file";//转发文件稍有不同 public static String INSTANT_SEND="instant_send";//转发 public static String CHAT_MESSAGE_DELETE_ACTION="chat_message_delete"; public static String CHAT_REMOVE_MESSAGE_POSITION="CHAT_REMOVE_MESSAGE_POSITION"; public static String ONRECORDSTART="onrecordstart"; public static String GROUP_JOIN_NOTICE="group_join_notice";//加入新群的通知 public static String GROUP_JOIN_NOTICE_ACTION="group_join_notice_action";//加入新群的通知 public static String GROUP_JOIN_NOTICE_FRIEND_ID="group_join_notice_friend_id";//加入新群发送朋友的id public static String OFFLINE_TIME="offline_time";//离线时间 public static String LAST_OFFLINE_TIME="last_offline_time"; /** 某些地方选择数据使用的常量 */ public static final String EXTRA_ACTION = "action";// 进入这个类的执行的操作 public static final int ACTION_NONE = 0;// 不执行操作 public static final int ACTION_SELECT = 1;// 执行选择操作 public static final String EXTRA_SELECT_IDS = "select_ids";// 选择对应项目的ids public static final String EXTRA_SELECT_ID = "select_id";// 选择对应项目的id public static final String EXTRA_SELECT_NAME = "select_name";// 选择的对应项目的名称 /** 某些地方需要传递如ListView Position的数据 */ public static final String EXTRA_POSITION = "position"; public static final int INVALID_POSITION = -1; // /////////////////////////////////////////////////////////////////////////// // 用户信息参数,很多地方需要 public static final String EXTRA_USER_ID = "userId";// userId public static final String EXTRA_NICK_NAME = "nickName";// nickName public static final String EXTRA_IS_GROUP_CHAT = "isGroupChat";// 是否是群聊 // BusinessCircleActivity需要的 public static final String EXTRA_CIRCLE_TYPE = "circle_type";// 看的商务圈类型 public static final int CIRCLE_TYPE_MY_BUSINESS = 0;// 看的商务圈类型,是我的商务圈 public static final int CIRCLE_TYPE_PERSONAL_SPACE = 1;// 看的商务圈类型,是个人空间 // //////////////// /** 商务圈发布的常量 */ /* 发说说(图文) */ public static final String EXTRA_IMAGES = "images";// 预览的那组图片 public static final String EXTRA_CHANGE_SELECTED = "change_selected";// 是否可以改变选择,这样在ActivityResult中会回传重新选择的结果 public static final String EXTRA_MSG_ID = "msg_id";// 公共消息id public static final String EXTRA_FILE_PATH = "file_path";// 语音、视频文件路径 public static final String FILE_PAT_NAME = "file_name";//文件的名字 public static final String EXTRA_IMAGE_FILE_PATH = "image_file_path";// 图片文件路径 public static final String EXTRA_TIME_LEN = "time_len";// 语音、视频文件时长 //位置经纬度 public static final String EXTRA_LATITUDE = "latitude"; public static final String EXTRA_LONGITUDE = "longitude"; /* IM */ public static final String EXTRA_FRIEND = "friend"; /* 进入SingleImagePreviewActivity需要带上的参数 */ public static final String EXTRA_IMAGE_URI = "image_uri"; public static final String ISADD_USER = "add_user"; public static final String FILE_PATH="file_paht";//转发消息的标记 }
public interface Addition extends java.rmi.Remote { public int addition(int a, int b) throws java.rmi.RemoteException; }
package br.edu.fadam.estruturadedados.ead.aula4.revisao; public class NoBinario { int valor; NoBinario saEsquerdo; NoBinario saDireito; }
/** * This class modifies the default SAX parser handler * */ /** * @author Daniel Jean * */ //Default package import java.util.List; import java.util.Stack; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SAXHandler extends DefaultHandler{ String TAG_DOCUMENT = "doc"; String TAG_ARRAY = "arr"; String TAG_PUBMED_CONTENT = "str"; String ATRIBUTE_ABSTRACT = "medline_abstract_text"; String ATRIBUTE_JOURNAL = "medline_journal_title"; String ATRIBUTE_TITLE = "medline_article_title"; String ATRIBUTE_ID = "id"; boolean flag_abstract_txt; boolean flag_abstract_part; boolean flag_journal; boolean flag_title; boolean flag_id; boolean flag_doc; String gene; private Stack<PubmedDocument> documentStack = new Stack<PubmedDocument>(); public StringBuilder content = new StringBuilder(); public SAXHandler(String targetWord) { flag_abstract_txt = false; flag_journal = false; flag_title = false; flag_id = false; gene = targetWord; flag_doc = false; } @Override public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException { if (qName.equals(TAG_DOCUMENT)) {//<doc> PubmedDocument currentDocument = new PubmedDocument(); documentStack.push(currentDocument); flag_doc = true; } if(qName.equals(TAG_ARRAY)){//arr //This case is when the xml has an array of info if(attributes.getValue("name").equals(ATRIBUTE_ABSTRACT)){//name = medline_abstract_text flag_abstract_txt = true; } } if (qName.equals(TAG_PUBMED_CONTENT)){//str if(attributes.getLength()!=0){ if(attributes.getValue("name").equals(ATRIBUTE_JOURNAL)){//str = medline_journal_title flag_journal = true; } if (attributes.getValue("name").equals(ATRIBUTE_TITLE)){//str = medline_article_title flag_title = true; } if (attributes.getValue("name").equals(ATRIBUTE_ID)){//str = id flag_id = true; } }else{ //This is to indicate that the xml file can have an array of str's with info if(flag_abstract_txt){ // if we are inside arr flag_abstract_part = true; } } } } @Override public void characters(char[] ch, int start, int length) throws SAXException { //This ensures that only the result node is appended if(flag_doc){ content.append(new String(ch, start, length)); //Appending nodes } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equals(TAG_PUBMED_CONTENT)){ if(documentStack!=null && !documentStack.isEmpty()){ //we are inside a document element PubmedDocument currentDocument = documentStack.peek(); if(flag_abstract_part){ //Setting temp to start at the 11th character to avoid spaces and line breaks. String temp = content.toString().substring(10); if(currentDocument.getAbstract_text() != null){//To avoid adding null to the result. currentDocument.setAbstract_text(currentDocument.getAbstract_text() + temp); }else{ currentDocument.setAbstract_text(temp); } flag_abstract_part = false; } else if(flag_journal){ String temp = content.toString().replace("\n", ""); temp = temp.substring(8); //removing space and line breaks currentDocument.setJournal(temp); flag_journal = false; }else if(flag_title){ //Setting temp to start at the 9th character to avoid spaces and line breaks. String temp = content.toString().substring(8); currentDocument.setTitle(temp); flag_title = false; }else if(flag_id){ String temp = content.toString().replace("\n", ""); temp = temp.substring(4); currentDocument.setId(temp); flag_id = false; } content = new StringBuilder(); } }else if(qName.equals(TAG_ARRAY)){ flag_abstract_txt = false; }else if (qName.equals(TAG_DOCUMENT)) {//<doc> flag_doc = false; } } public List<PubmedDocument> getResults(){ return documentStack; } public void print(List<PubmedDocument> documents) { for (PubmedDocument doc : documents){ System.out.println(doc); } } }
package com.huazia.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * * @author HuaZai * @contact who.seek.me@java98k.vip * <ul> * @description TODO * </ul> * @className MicroserviceConfigClientApp_4001 * @package com.huazia.springcloud * @createdTime 2018年05月31日 下午7:07:07 * * @version V1.0.0 */ @SpringBootApplication public class MicroserviceConfigClientApp_4001 { public static void main(String[] args) { SpringApplication.run(MicroserviceConfigClientApp_4001.class, args); } }
/* * 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 ui; /** * * @author causticroot */ public class display extends javax.swing.JFrame { /** * Creates new form display */ public display() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTableProducts = new javax.swing.JTable(); jTextFieldCod = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jTextFieldQtd = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jButtonBuy = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTextAreaDisplay = new javax.swing.JTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("STORE SYSTEM"); setBackground(javax.swing.UIManager.getDefaults().getColor("nb.diff.added.color")); setResizable(false); jTableProducts.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { { new Integer(1), "Manga rosa", new Double(44.99)}, { new Integer(2), "Jack herer", new Double(61.55)}, { new Integer(3), "Bubblegum", new Double(39.99)}, { new Integer(4), "Magnum OG", new Double(64.45)} }, new String [] { "CÓDIGO", "PRODUTO", "PREÇO" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.Double.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jTableProducts.setRowMargin(0); jScrollPane1.setViewportView(jTableProducts); jLabel1.setText("Código:"); jLabel2.setText("Qtd:"); jLabel3.setText("WEED HOUSE'S OF JERUZA"); jButtonBuy.setBackground(new java.awt.Color(0, 102, 51)); jButtonBuy.setForeground(new java.awt.Color(0, 0, 0)); jButtonBuy.setText("Efetuar compra"); jButtonBuy.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonBuyActionPerformed(evt); } }); jTextAreaDisplay.setEditable(false); jTextAreaDisplay.setColumns(20); jTextAreaDisplay.setFont(new java.awt.Font("Baekmuk Dotum", 1, 18)); // NOI18N jTextAreaDisplay.setRows(1); jScrollPane2.setViewportView(jTextAreaDisplay); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldCod, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldQtd, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(17, 17, 17) .addComponent(jButtonBuy, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGroup(layout.createSequentialGroup() .addGap(113, 113, 113) .addComponent(jLabel3) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3) .addGap(10, 10, 10) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextFieldCod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jTextFieldQtd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonBuy)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents double price_product = 0.0;//Guarda o preço do produto pego na tabela int code_product = 0;//Guarda o código do produto inserido pelo usuário int amount_product = 0;//Guarda a quantidade de produtos inserido pelo usuário double total_purchase = 0.0;//Armazena o preço do produto * quantidade String name_product = "";//Guarda o nome do produto correspondente ao código da tabela private void jButtonBuyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuyActionPerformed code_product = Integer.parseInt(jTextFieldCod.getText());//Pega o valor do código de produto digitado amount_product = Integer.parseInt(jTextFieldQtd.getText());//Pega a quantidade de produtos digitados for(int i = 0; i < jTableProducts.getRowCount(); i++) { if(code_product == (Integer)jTableProducts.getModel().getValueAt(i, 0))//Compara o código inserido com o código da linha i { name_product = (String)jTableProducts.getModel().getValueAt(i, 1);//Armazena o valor da coluna produto correspondente a linha i price_product = (Double)jTableProducts.getModel().getValueAt(i, 2);//Armazena o valor da coluna preço correspondente a linha i } } total_purchase = price_product * amount_product;//Calcula o total da compra, mutiplicando o valor do produto pela quantidade jTextAreaDisplay.setText(String.valueOf(name_product + " x " + amount_product + " - total: " + total_purchase));//Retorna o nome, quantidade e o total da compra }//GEN-LAST:event_jButtonBuyActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new display().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonBuy; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator1; private javax.swing.JTable jTableProducts; private javax.swing.JTextArea jTextAreaDisplay; private javax.swing.JTextField jTextFieldCod; private javax.swing.JTextField jTextFieldQtd; // End of variables declaration//GEN-END:variables }
package com.study.repository; import com.study.entity.BOrder; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface BOrderRepository extends JpaRepository<BOrder, Long> { @Query(nativeQuery = true, value = "select * from b_order where id=:id") Object findOrderById(@Param("id") Long id); @Query(nativeQuery = true, value = "select * from b_order where company_id=:companyId") Object[] findOrderByCompanyId(@Param("companyId") Integer companyId); @Query(nativeQuery = true, value = "select * from b_order where company_id=:companyId and id=:id") Object findOrderByCompanyIdAndId(@Param("companyId") Integer companyId, @Param("id") Long id); @Query(nativeQuery = true, value = "select * from b_order where name=:name") Object[] findOrderByName(@Param("name") String name); }
/*Joshua Palmer Z23280034 * COP 4331 001 * Homework 2 Question 4 */ package hw2; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class UPCScanner { /**used to get input from keyboard*/ private Scanner scanner; /**regex to test valid UPC numbers, or the 'pay' button*/ private final Pattern upcPattern = Pattern.compile("^\\d{12}$|^p$"); public UPCScanner() { scanner = new Scanner(System.in); } /** * Checks whether a given UPC is valid. * @param upc UPC number to be tested * @return True if valid, False if invalid */ private boolean validUPC(String upc) { Matcher matcher = upcPattern.matcher(upc); return matcher.matches(); } /** * Gets input from the console and returns it * if it is a valid UPC number * @return user input if valid UPC, or empty string * if invalid */ public String scan() { String result = scanner.nextLine().trim(); return validUPC(result) ? result : ""; } }
package cl.laPalmera.DTO; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import org.apache.log4j.Logger; import cl.laPalmera.connection.ConnectionLaPalmera; public class CabezaPedidoDTO { private static final Logger LOGGER = Logger.getLogger(CabezaPedidoDTO.class); private String numeroPedido=""; private String nombreCliente=""; private String fechaPedido=""; private String horaPedido=""; private String precioTotalPedido=""; private String confirmacionPedido=""; private String dedicatoriaPedido=""; private String observacionPedido=""; public int grabar() { int i = 0; try { ConnectionLaPalmera connLaPalmera = new ConnectionLaPalmera(); Connection conn = connLaPalmera.conectionMySql(); if (conn != null) { Statement stmt = conn.createStatement(); String sql = "insert into CabezaPedido(nombrecliente,fechapedido,horapedido,preciototalpedido,confirmacionpedido,dedicatoriapedido,observacionpedido) values ("; sql = sql + "'"+nombreCliente +"',"; sql = sql + "'"+fechaPedido +"',"; sql = sql + "'"+horaPedido +"',"; sql = sql + precioTotalPedido +","; sql = sql + "'"+confirmacionPedido +"',"; sql = sql + "'"+dedicatoriaPedido +"',"; sql = sql + "'"+observacionPedido +"')"; //LOGGER.debug(sql); i = stmt.executeUpdate(sql); if (i == 1) LOGGER.debug("OK"); stmt.close(); conn.close(); } } catch (Exception e) { LOGGER.error(e,e); return (i); } return (i); } public int modificar() { int i = 0; try { ConnectionLaPalmera connLaPalmera = new ConnectionLaPalmera(); Connection conn = connLaPalmera.conectionMySql(); if (conn != null) { Statement stmt = conn.createStatement(); String sql = "update cabezapedido set "; sql = sql + "numeropedido = "+numeroPedido +", "; sql = sql + "nombrecliente = "+"'"+nombreCliente +"', "; sql = sql + "fechapedido = "+"'"+fechaPedido +"', "; sql = sql + "horapedido = "+"'"+horaPedido +"', "; sql = sql + "preciototalpedido = "+precioTotalPedido +", "; sql = sql + "confirmacionPedido = "+"'"+confirmacionPedido +"', "; sql = sql + "dedicatoriaPedido = "+"'"+dedicatoriaPedido +"', "; sql = sql + "observacionPedido = "+"'"+observacionPedido +"' where numeropedido = "+numeroPedido+""; //LOGGER.debug(sql); i = stmt.executeUpdate(sql); if (i == 1) LOGGER.debug("OK"); stmt.close(); conn.close(); } } catch (Exception e) { LOGGER.error(e,e); return (i); } return (i); } public int eliminar() { int i = 0; try { ConnectionLaPalmera connLaPalmera = new ConnectionLaPalmera(); Connection conn = connLaPalmera.conectionMySql(); if (conn != null) { Statement stmt = conn.createStatement(); String sql = "delete from cabezapedido where "; sql = sql + "numeropedido = "+numeroPedido +""; //LOGGER.debug(sql); i = stmt.executeUpdate(sql); if (i == 1) LOGGER.debug("OK"); stmt.close(); conn.close(); } } catch (Exception e) { LOGGER.error(e,e); return (i); } return (i); } public String buscarUltimo() { try { ConnectionLaPalmera connLaPalmera = new ConnectionLaPalmera(); Connection conn = connLaPalmera.conectionMySql(); if (conn != null) { Statement stmt = conn.createStatement(); String sql = "select * from cabezapedido"; //LOGGER.debug(sql); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { LOGGER.debug("Lo encontro"); numeroPedido=rs.getString(1); LOGGER.debug(numeroPedido); } rs.close(); stmt.close(); conn.close(); } } catch (Exception e) { LOGGER.error(e,e); } return numeroPedido; } public boolean buscar() { boolean resultado = false; try { ConnectionLaPalmera connLaPalmera = new ConnectionLaPalmera(); Connection conn = connLaPalmera.conectionMySql(); if (conn != null) { Statement stmt = conn.createStatement(); String sql = "select * from cabezapedido where numeropedido = "+numeroPedido+""; //LOGGER.debug(sql); ResultSet rs = stmt.executeQuery(sql); if (rs.next()) { LOGGER.debug("Lo encontro"); numeroPedido= rs.getString(1); nombreCliente= rs.getString(2); fechaPedido=rs.getString(3); horaPedido=rs.getString(4); precioTotalPedido=rs.getString(5); confirmacionPedido=rs.getString(6); dedicatoriaPedido=rs.getString(7); observacionPedido=rs.getString(8); resultado = true; } rs.close(); stmt.close(); conn.close(); } } catch (Exception e) { LOGGER.error(e,e); } return resultado; } public String getConfirmacionPedido() { return confirmacionPedido; } public void setConfirmacionPedido(String confirmacionPedido) { this.confirmacionPedido = confirmacionPedido; } public String getDedicatoriaPedido() { return dedicatoriaPedido; } public void setDedicatoriaPedido(String dedicatoriaPedido) { this.dedicatoriaPedido = dedicatoriaPedido; } public String getFechaPedido() { return fechaPedido; } public void setFechaPedido(String fechaPedido) { this.fechaPedido = fechaPedido; } public String getHoraPedido() { return horaPedido; } public void setHoraPedido(String horaPedido) { this.horaPedido = horaPedido; } public String getNombreCliente() { return nombreCliente; } public void setNombreCliente(String nombreCliente) { this.nombreCliente = nombreCliente; } public String getNumeroPedido() { return numeroPedido; } public void setNumeroPedido(String numeroPedido) { this.numeroPedido = numeroPedido; } public String getObservacionPedido() { return observacionPedido; } public void setObservacionPedido(String observacionPedido) { this.observacionPedido = observacionPedido; } public String getPrecioTotalPedido() { return precioTotalPedido; } public void setPrecioTotalPedido(String precioTotalPedido) { this.precioTotalPedido = precioTotalPedido; } }
package com.tdr.registrationv3.bean; import com.contrarywind.interfaces.IPickerViewData; public class OptionsBean implements IPickerViewData { private String name; private Object value; public OptionsBean() { } public OptionsBean(String name, Object value) { this.name = name; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } @Override public String getPickerViewText() { return name; } }
package in.stevemann.tictactoe.services; import in.stevemann.tictactoe.entities.Game; import in.stevemann.tictactoe.entities.Player; import in.stevemann.tictactoe.entities.QGame; import in.stevemann.tictactoe.enums.GameStatus; import in.stevemann.tictactoe.enums.GridType; import in.stevemann.tictactoe.enums.PieceType; import in.stevemann.tictactoe.pojos.Board; import in.stevemann.tictactoe.repositories.GameRepository; import lombok.AllArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.web.server.ResponseStatusException; @Service @AllArgsConstructor public class GameService { private final GameRepository gameRepository; private final PlayerService playerService; private Game save(Game game) { return gameRepository.save(game); } public Game findGame(String gameCode) { return gameRepository.findOne( QGame.game.enabled.isTrue() .and(QGame.game.code.eq(gameCode)) ).orElse(null); } public Game getGame(String gameCode) { Game game = findGame(gameCode); if (game == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Game not found"); return game; } public Game deleteGame(String gameCode) { Game game = getGame(gameCode); game.setEnabled(false); return save(game); } public Game newGame(String firstPlayerUsername, String secondPlayerUsername, GridType gridType) { Player firstPlayer = playerService.getPlayerByUsername(firstPlayerUsername); Player secondPlayer = playerService.getPlayerByUsername(secondPlayerUsername); return newGame(firstPlayer, secondPlayer, gridType); } public Game newGame(Player firstPlayer, Player secondPlayer, GridType gridType) { Game game = new Game(); game.setFirstPlayer(firstPlayer); game.setSecondPlayer(secondPlayer); game.setGridType(gridType); game.setStatus(GameStatus.IN_PROGRESS); return save(game); } private Game updateGameStatus(Game game, PieceType pieceType) { if (PieceType.X.equals(pieceType)) { game.setStatus(GameStatus.FIRST_PLAYER_WON); } if (PieceType.O.equals(pieceType)) { game.setStatus(GameStatus.SECOND_PLAYER_WON); } return save(game); } // returns if game is still in progress public boolean isGameInProgress(Board board, PieceType pieceType, int position) { // return false if game is not in progress or paused if (!board.getGame().getStatus().equals(GameStatus.IN_PROGRESS) && !board.getGame().getStatus().equals(GameStatus.PAUSED)) { return false; } int row = (position - 1) / board.getGame().getGridType().getSize(); int col = (position - (row * board.getGame().getGridType().getSize())) - 1; PieceType wonBy = checkGameWonBy(board, pieceType, row, col); if (wonBy != null) { board.setGame(updateGameStatus(board.getGame(), wonBy)); } else { //check draw int moveCount = 0; if (!CollectionUtils.isEmpty(board.getGame().getMoves())) { moveCount = board.getGame().getMoves().size(); } if (moveCount == (Math.pow(board.getGame().getGridType().getSize(), 2) - 1)) { board.getGame().setStatus(GameStatus.DRAW); save(board.getGame()); return false; // game over on draw } } return wonBy == null; } // Returns PieceType that won. Else returns null private PieceType checkGameWonBy(Board board, PieceType pieceType, int row, int col) { int s = pieceType.getValue(); //check column for a win int n = board.getGame().getGridType().getSize(); for (int boardColumn = 0; boardColumn < n; boardColumn++) { if (board.getBoard()[row][boardColumn] != s) break; if (boardColumn == n - 1) { return pieceType; } } //check row for a win for (int boardRow = 0; boardRow < n; boardRow++) { if (board.getBoard()[boardRow][col] != s) break; if (boardRow == n - 1) { return pieceType; } } //check diagonal for a win if (row == col) { for (int diag = 0; diag < n; diag++) { if (board.getBoard()[diag][diag] != s) break; if (diag == n - 1) { return pieceType; } } } //check anti diagonal for a win if (row + col == n - 1) { for (int diag = 0; diag < n; diag++) { if (board.getBoard()[diag][(n - 1) - diag] != s) break; if (diag == n - 1) { return pieceType; } } } return null; } public Game pauseGameByCode(String gameCode) { return pauseGame(findGame(gameCode)); } public Game pauseGame(Game game) { if (game == null || !game.getStatus().equals(GameStatus.IN_PROGRESS)) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Game not found or game already completed."); System.out.println("Pausing the game now. You can resume the game using game code: " + game.getCode()); game.setStatus(GameStatus.PAUSED); return save(game); } public Game resumeGame(String gameCode) { return resumeGame(findGame(gameCode)); } public Game resumeGame(Game game) { if (game == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Game not found."); if (GameStatus.PAUSED.equals(game.getStatus())) { game.setStatus(GameStatus.IN_PROGRESS); game = save(game); } return game; } }
package ru.ifmo.diploma.synchronizer.protocol.handshake; import ru.ifmo.diploma.synchronizer.protocol.handshake.Credentials; import ru.ifmo.diploma.synchronizer.protocol.handshake.HandshakeMessage; import java.util.Map; /** * Created by ksenia on 25.05.2017. */ public class RoutingTable extends HandshakeMessage { private Map<String, Credentials> authorizationTable; public RoutingTable(String fromAddr, Map<String, Credentials> authorizationTable) { super(fromAddr); this.authorizationTable = authorizationTable; } public Map<String, Credentials> getAuthorizationTable() { return authorizationTable; } }
package com.app.drashti.drashtiapp; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.app.drashti.drashtiapp.Model.Donate; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by BaNkEr on 20-11-2016. */ public class MyDonateAdapter extends RecyclerView.Adapter<MyDonateAdapter.DonateHolder> { public Context mContext; public ArrayList<Donate> mDonates; public MyDonateAdapter(Context mContext, ArrayList<Donate> mDonates) { this.mContext = mContext; this.mDonates = mDonates; } @Override public DonateHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.row_donate,parent,false); return new DonateHolder(view); } @Override public void onBindViewHolder(DonateHolder holder, int position) { Donate donate = mDonates.get(position); Picasso.with(mContext).load(donate.getF_image()).into(holder.imgPRofile); holder.txtName.setText(donate.getF_name()); holder.txtDescription.setText(donate.getF_description()); holder.txtQuantity.setText(donate.getF_quantity()); holder.txtDatePicker.setText(donate.getF_pickupDate()); } @Override public int getItemCount() { return mDonates.size(); } public class DonateHolder extends RecyclerView.ViewHolder{ private ImageView imgPRofile; private TextView txtName; private TextView txtDescription; private TextView txtQuantity; private TextView txtDatePicker; public DonateHolder(View itemView) { super(itemView); imgPRofile = (ImageView)itemView.findViewById( R.id.imgPRofile ); txtName = (TextView)itemView.findViewById( R.id.txtName ); txtDescription = (TextView)itemView.findViewById( R.id.txtDescription ); txtQuantity = (TextView)itemView.findViewById( R.id.txtQuantity ); txtDatePicker = (TextView)itemView.findViewById( R.id.txtDatePicker ); } } }
/* * Dryuf framework * * ---------------------------------------------------------------------------------- * * Copyright (C) 2000-2015 Zbyněk Vyškovský * * ---------------------------------------------------------------------------------- * * LICENSE: * * This file is part of Dryuf * * Dryuf is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * Dryuf is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with Dryuf; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * @author 2000-2015 Zbyněk Vyškovský * @link mailto:kvr@matfyz.cz * @link http://kvr.matfyz.cz/software/java/dryuf/ * @link http://github.com/dryuf/ * @license http://www.gnu.org/licenses/lgpl.txt GNU Lesser General Public License v3 */ package net.dryuf.comp.devel.mvp; import java.io.IOException; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.apache.commons.io.IOUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import net.dryuf.comp.devel.form.DevelDryufSqlForm; import net.dryuf.core.Options; import net.dryuf.io.FileData; import net.dryuf.meta.ActionDef; import net.dryuf.mvp.Presenter; public class DevelDryufSqlPresenter extends net.dryuf.mvp.BeanFormPresenter<DevelDryufSqlForm> { private PlatformTransactionManager transactionManagerDr; @PersistenceContext(unitName="dryuf") protected EntityManager em; public DevelDryufSqlPresenter(Presenter parentPresenter, Options options) { super(parentPresenter, options); transactionManagerDr = getCallerContext().getBeanTyped("transactionManager-dryuf", PlatformTransactionManager.class); } @Override public DevelDryufSqlForm createBackingObject() { return new DevelDryufSqlForm(); } public boolean performRunSql(ActionDef action) throws IOException { DevelDryufSqlForm develDryufSqlForm = getBackingObject(); TransactionStatus txStatus = transactionManagerDr.getTransaction(new DefaultTransactionDefinition()); int ran = 0; String statement = null; try { if (develDryufSqlForm.getSqlFile() != null) { FileData sqlFile = getRequest().getFile(this.getFormFieldName("sqlFile")); for (String statement_: IOUtils.toString(sqlFile.getInputStream(), "UTF-8").split(";\\s*\n")) { statement = statement_; em.createNativeQuery(statement).executeUpdate(); ran++; } } if (develDryufSqlForm.getSql() != null) { for (String statement_: develDryufSqlForm.getSql().split(";\\s*\n")) { statement = statement_; em.createNativeQuery(statement).executeUpdate(); ran++; } } } catch (Exception ex) { transactionManagerDr.rollback(txStatus); throw new RuntimeException(ex.toString()+", when running "+statement, ex); } transactionManagerDr.commit(txStatus); this.addMessage(MSG_Info, "successfully ran "+ran+" statements"); return true; } }
package com.yc.education.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.yc.education.model.purchase.*; import com.yc.education.model.sale.*; import com.yc.education.model.stock.CheckStock; import com.yc.education.model.stock.CheckStockProduct; import javafx.scene.layout.Pane; import javafx.stage.Stage; /** * @author BlueSky * @Date 11:47 2018-08-21 */ public class StageManager { /** * * @auther: BlueSky */ public static Map<String, Stage> STAGE = new HashMap<String, Stage>(); public static Map<String, Object> CONTROLLER = new HashMap<String, Object>(); public static Map<String,Pane> ORDERCONTENT = new HashMap<String, Pane>(); //询价单导出存入 public static InquiryOrder inquiryOrderInfo = null; //询价单导出导出询价产品 public static List<InquiryProduct> inquiryProductsInfo = new ArrayList<>(); //采购订单 public static PurchaseOrders purchaseOrders = null; //采购订单产品导出 public static List<PurchaseProduct> purchaseProducts = new ArrayList<>(); //在途库存导入采购入库 public static List<TransportationProduct> transportationProducts = new ArrayList<>(); //盘库作业产品导入库存异动作业产品 public static List<CheckStockProduct> checkStockProducts = new ArrayList<>(); //销售-报价单 public static SaleQuotation saleQuotation = null; //销售-网上订单 public static SaleOnlineOrder saleOnlineOrder = null; //销售-订货单 public static SalePurchaseOrder salePurchaseOrder = null; //销售-销货单 public static SaleGoods saleGoods = null; //销售-销货退货单 public static SaleReturnGoods saleReturnGoods = null; //在途库存-采购入库 public static TransportationInventory transportationInventory = null; //盘库作业-库存异动作业 public static CheckStock checkStock = null; // 集合 public static List<?> PRODUCT_LIST = new ArrayList<>(); //限制右侧船体打开关闭 public static boolean rightWin = false; /** * 清空所有集合和对象 */ public static void clear(){ StageManager.inquiryOrderInfo = null; StageManager.inquiryProductsInfo = new ArrayList<>(); StageManager.purchaseOrders = null; StageManager.purchaseProducts = new ArrayList<>(); StageManager.transportationProducts = new ArrayList<>(); StageManager.saleOnlineOrder = null; StageManager.salePurchaseOrder = null; StageManager.checkStockProducts = new ArrayList<>(); StageManager.saleQuotation = null; StageManager.saleGoods = null; StageManager.saleReturnGoods = null; StageManager .transportationInventory = null; StageManager .checkStock = null; StageManager.PRODUCT_LIST = new ArrayList<>(); } }
package com.isg.ifrend.wrapper.mli.request.account; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="GetAccount") public class GetAccount { private String accountNumber; private String customerNumber; private String cardNumber; public String getAccountNumber() { return accountNumber; } public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } public String getCustomerNumber() { return customerNumber; } public void setCustomerNumber(String customerNumber) { this.customerNumber = customerNumber; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } }
import java.io.Serializable; public class Movie implements Serializable { String name; int created_year; String created_location; String type; double cost; Movie(String name, int created_year, String created_location, String type, double cost){ this.name = name; this.cost = cost; this.created_location = created_location; this.created_year = created_year; this.type = type; } public int getCreated_year() { return created_year; } public double getCost() { return cost; } public String getCreated_location() { return created_location; } public String getName() { return name; } public String getType() { return type; } public void setCost(double cost) { this.cost = cost; } public void setCreated_location(String created_location) { this.created_location = created_location; } public void setCreated_year(int created_year) { this.created_year = created_year; } public void setName(String name) { this.name = name; } public void setType(String type) { this.type = type; } public String getInfo() { return ("Movie title: "+this.getName()+"\nCreated year: " +this.getCreated_year()+"\nCreated loacation: " +this.getCreated_location() + "\nType: "+this.getType()+"\nCost: "+this.getCost()); } }
import java.util.StringTokenizer; public class StringUtils { /** * zad 18/1 * * @param text tekst * @return liczba cyfr */ public static int countDigits(String text) { int result = 0; for (int i = 0; i < text.length(); i++) { if (Character.isDigit(text.charAt(i))) { result++; } } return result; } /** * zad 18/2 * * @param text jakis tekst * @return liczba malych liter */ public static int countSmallLetters(String text) { int result = 0; for (int i = 0; i < text.length(); i++) { if (Character.isLetter(text.charAt(i))) { if (Character.isLowerCase(text.charAt(i))) { result++; } } } return result; } /** * zad 18/3 * * @param text tekst z duzymi literami * @return liczba duzych liter */ public static int countCapitalLetters(String text) { int result = 0; for (int i = 0; i < text.length(); i++) { if (Character.isLetter(text.charAt(i))) { if (Character.isUpperCase(text.charAt(i))) { result++; } } } return result; } /** * zad 18/4 * * @param text ciag znakow * @return liczba ani liter ani cyfr */ public static int countNonLettersAndNonDigits(String text) { int result = 0; for (int i = 0; i < text.length(); i++) { if (!Character.isLetterOrDigit(text.charAt(i))) { result++; } } return result; } /** * zad 18/5 * * @param text tekst * @param character szukany znak * @return liczba wystapien znaku */ public static int countCharacters(String text, char character) { int result = 0; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == character) { result++; } } return result; } /** * zad 18/6 * * @param text zdanie * @return ciag pierwszych liter */ public static String abbreviation(String text) { text = text.trim(); String result; if(text.isEmpty()){ result = ""; }else { result = String.valueOf(text.charAt(0)); for (int i = 1; i < text.length() - 1; i++) { if (Character.isSpaceChar(text.charAt(i))) { if (!Character.isSpaceChar(text.charAt(i + 1))) { result += text.charAt(i + 1); } } } } return result.toUpperCase(); } /** * zad 18/7 * * @param text podany tekst * @return tekst od tylu */ public static String reverseString(String text) { String result = ""; for (int i = text.length() - 1; i >= 0; i--) { result += text.charAt(i); } return result; } /** * zad 18/8 * sprawdza czy zdanie jest palindromem * * @param text zdanie * @return palindrom lub nie */ public static boolean isPalindrome(String text) { int end = text.length() - 1; int front = 0; while (front < end) { if (text.charAt(front) != text.charAt(end)) { return false; } front++; end--; } return true; } /** * zad 18/9 * * @param text ciag znakow * @param index indeks * @return znak pod indeksem */ public static char reverseIndexOf(String text, int index) { return text.charAt(text.length() - index - 1); } /** * zad 18/10 * * @param text jakis tekst * @param parity parzyste czy nie * @param start poczatek * @return parzyste lub nie */ public static String filterByEvenOrOdd(String text, boolean parity, int start) { String result = ""; int p; if (parity) { p = 0; } else p = 1; for (int i = start; i < text.length(); i++) { if (i % 2 == p) { result += text.charAt(i); } } return result; } /** * zad 18/11 * * @param text tekst * @param text2 tekst ze wspolnymi znakami * @return liczba wspolnych znakow */ public static int countCommonCharactersFromBeginning(String text, String text2) { int common = 0; int min = Math.min(text.length(),text2.length()); for (int i = 0; i < min; i++) { if (text2.charAt(i) == text.charAt(i)) { common += 1; } } return common; } /** * zad 18/12 * * @param Text tekst * @param anotherText drugi tekst * @return sprawdza czy tekst zawiera drugi tekst */ public static boolean isTrimmableTo(String Text, String anotherText) { return Text.contains(anotherText); } /** * zad 18/13 * * @param Text tekst * @param anotherText drugi tekst * @return liczy wystapienia drugiego tekstu w tekscie */ public static int countOccurrences(String Text, String anotherText) { int occurences = 0; String[] tab = Text.split(" "); for(int i = 0; i < tab.length; i++){ if(anotherText.equals(tab[i])){ occurences++; } } return occurences; } /** * zad 18/14 * * @param text tekst poczatkowy * @param toReplace slowo do zastepowania * @return tekst z zastąpionym slowem */ public static String censorByReplacing(String text, String toReplace) { String text2 = text.replaceAll(toReplace, "<censored>"); return text2; } /** * zad 18/15 * * @param text tekst poczatkowy * @param remove slowo do usuniecia * @return tekst bez slow do usuniecia */ public static String censorByRemoving(String text, String remove) { String text2 = text.replaceAll(remove + " ", ""); return text2; } /** * zad 18/16 * * @param text tekst * @return tekst odwrocony */ public static String reverseWords(String text) { String[] tab = text.split(" "); String word; for (int w = 0; w < tab.length / 2; w++) { word = tab[w]; tab[w] = tab[tab.length - 1 - w]; tab[tab.length - 1 - w] = word; } return String.join(" ", tab); } /** * zad 18/17 * * @param number liczba typu long * @return liczba cyfr liczby number */ public static int numberOfDigits(long number) { return String.valueOf(number).length(); } /** * zad 18/18 * * @param text ciag typu string * @return zwraca czy podany ciag jest typu int */ public static boolean isDecInteger(String text) { return text.matches("[-]?([1-9][0-9]{0,8}|[0])[lL]?"); } /** * zad 18/19 * * @param text ciag znakow * @return sprawdza czy ciag jest zapisem int */ public static boolean isHexInteger(String text) { return text.matches("[-]?[0][xX][0-9a-fA-F]{0,8}[Ll]?"); } /** * zad 18/20 * * @param text * @return */ public static boolean isNumber(String text) { return text.matches("[-]?[0-9][,][0-9]{0,8}"); } //ZADANIE 19 /** * zad 19/1 * * @param text tekst * @return tekst bez niepotrzebnych spacji */ public static StringBuilder removeUnwantedSpaces(StringBuilder text) { // wycinamy spacje z poczatku while (text.charAt(0) == ' ') { text.deleteCharAt(0); } // wycinamy spacje z konca while (text.charAt(text.length() - 1) == ' ') { text.deleteCharAt(text.length() - 1); } // wycinamy spacje miedzy wyrazami int i = 0; while (i < text.length()) { if (Character.isSpaceChar(text.charAt(i)) && Character.isSpaceChar(text.charAt(i + 1))) { text.deleteCharAt(i); } else { i++; } } return text; } /** * zad 19/2 * * @param text tekst stringbuilder * @return tekst rozdzielony spacjami */ public static StringBuilder distribute(StringBuilder text) { for (int i = text.length() - 1; i > 0; i--) { text.insert(i, " "); } return text; } /** * zad 19/3 * * @param text tekst typu stringbuilder * @return tekst bez komentarza */ public static StringBuilder removeComment(StringBuilder text) { for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == '/' && text.charAt(i + 1) == '/') { text.delete(i, text.length()); } } return text; } /** * zad 19/4 * * @param text tekst stringbuilder * @param comment komentarz stringbuilder * @return tekst z dodanym na koncu komentarzem */ public static StringBuilder addComment(StringBuilder text, StringBuilder comment) { removeUnwantedSpaces(text); text.append(" // "); text.insert(text.length(), comment); return text; } /** * zad 19/5 * * @param text tekst stringbulider * @return sprawdza czy text jest palindromem */ public static boolean isPalindrome(StringBuilder text) { removeUnwantedSpaces(text); return (text == text.reverse()); } /** * zad 19/6 * * @param text * @return */ public static StringBuilder Polynomials(StringBuilder text) { return text; } //ZADANIE 20 /** * zad 20/1 * * @param text * @return */ public static String distribute(String text) { return text; } /** * zad 20/2 * * @param text * @return */ public static String removeComment(String text) { return text; } //ZADANIE 21 /** * zad 21/1 * * @param text tekst * @return skrot tekstu */ public static String abbreviationA(String text) { StringBuilder wynik = new StringBuilder(); StringTokenizer wyrazy = new StringTokenizer(text); while (wyrazy.hasMoreTokens()) { wynik.append(wyrazy.nextToken().charAt(0)); } return (wynik.toString()).toUpperCase(); } /** * zad 21/2 * * @param text * @param znak * @return */ public static int countWordsWithAChar(String text, char znak) { int result = 0; StringTokenizer wyrazy = new StringTokenizer(text, " "); String znakJakoString = String.valueOf(znak); while (wyrazy.hasMoreTokens()) { if (wyrazy.nextToken().contains(znakJakoString)) { result++; } } return result; } /** * zad 21/3 * * @param text * @return */ public static String reverseWordsA(String text) { StringBuilder result = new StringBuilder(); StringTokenizer wyrazy = new StringTokenizer(text, " "); String text2 = ""; if (!text.isEmpty()) { while (wyrazy.hasMoreTokens()) { result.insert(0, wyrazy.nextToken() + " "); } text2 = result.toString().substring(0, result.length() - 1); } return text2; } /** * zad 21/4 * * @param text tekst * @param remove slowo do usuniecia * @return tekst bez slowa */ public static StringBuilder censorByRemovingA(String text, String remove) { StringBuilder result = new StringBuilder(); StringTokenizer wyrazy = new StringTokenizer(text, " "); while(wyrazy.hasMoreTokens()){ String next = wyrazy.nextToken(); if(next.equals(remove)){ }else { result.insert(result.length(),next + " "); } } return removeUnwantedSpaces(result); } /** * zad 21/5 * * @param text lancuch do sprawdzenia * @return */ public static boolean isTraditionalDecInteger(String text) { return true; } /** * zad 21/6 * zmienia male na duze litery i odwrotnie * * @param text tekst * @return wynik */ public static StringBuilder changeCase(String text) { StringBuilder result = new StringBuilder(); StringTokenizer litery = new StringTokenizer(text, ""); for (int i = 0; i < text.length(); i++) { if (Character.isLowerCase(text.charAt(i))) { result.append(Character.toUpperCase(text.charAt(i))); } else { result.append(Character.toLowerCase(text.charAt(i))); } } return result; } }
/* * 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 jogo; /** * * @author 2info2021 */ import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import javax.swing.ImageIcon; public class Cenario { private int altura = 20; private int largura = 20; private int x = 0; private int y = 0; private Image fundo; public Cenario() { fundo = new ImageIcon(this.getClass().getResource("/imagens/cenario")).getImage().getScaledInstance(largura, altura, 1); x = 0; y = 0; largura = 0; altura = 0; } public Cenario(int x, int y, int largura, int altura) { this.x = x; this.y = y; this.largura = largura; this.altura = altura; fundo = new ImageIcon(this.getClass().getResource("/imagens/cenario.png")).getImage().getScaledInstance(largura, altura, 1); } public Rectangle getLimites() { return new Rectangle((int) getX(), (int) getY(), getLargura(), getAltura()); } public int getAltura() { return altura; } public void setAltura(int altura) { this.altura = altura; setFundo(new ImageIcon(this.getClass().getResource("/imagens/cenario")).getImage().getScaledInstance(getLargura(), altura, 1)); } public int getLargura() { return largura; } public void setLargura(int largura) { this.largura = largura; setFundo(new ImageIcon(this.getClass().getResource("/imagens/cenario")).getImage().getScaledInstance(largura, getAltura(), 1)); } /** * @return the x */ public int getX() { return x; } /** * @param x the x to set */ public void setX(int x) { this.x = x; } /** * @return the y */ public int getY() { return y; } /** * @param y the y to set */ public void setY(int y) { this.y = y; } /** * @return the fundo */ public Image getFundo() { return fundo; } /** * @param fundo the fundo to set */ public void setFundo(Image fundo) { this.fundo = fundo; } }