blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
cd6e20cbb40a0dee9f49856d5fffa41230f8ed05 | Java | Muhammad0224/Test_bot | /src/main/java/uz/pdp/online/TestBot.java | UTF-8 | 46,045 | 1.90625 | 2 | [] | no_license | package uz.pdp.online;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.*;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendDocument;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.send.SendPhoto;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage;
import org.telegram.telegrambots.meta.api.objects.Document;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardRemove;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import uz.pdp.online.helper.Generator;
import uz.pdp.online.helper.GsonHistoryHelper;
import uz.pdp.online.helper.GsonSubjectHelper;
import uz.pdp.online.helper.GsonUserHelper;
import uz.pdp.online.model.*;
import uz.pdp.online.model.history.ActiveHistory;
import uz.pdp.online.model.history.CheckQuestion;
import uz.pdp.online.model.history.History;
import uz.pdp.online.model.response.Response;
import uz.pdp.online.model.subject.Answer;
import uz.pdp.online.model.subject.Question;
import uz.pdp.online.model.subject.Subject;
import uz.pdp.online.sender.InlineKeyboardSender;
import uz.pdp.online.sender.ReplyKeyboardSender;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;
import java.util.*;
public class TestBot extends TelegramLongPollingBot {
private final String API_TOKEN = "1896664287:AAEHp8iMOAmsOHwUHLJQL0_KfvU_Jk7ObiM";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
File subjectFile = new File("src/main/resources/base/subjects.txt");
File userFile = new File("src/main/resources/base/users.txt");
File historyFile = new File("src/main/resources/base/histories.txt");
List<User> users = new ArrayList<>();
List<Subject> subjects = new ArrayList<>();
List<History> histories = new ArrayList<>();
User admin = getUsersList().get(0);
boolean createSubject = false;
String subjectName = null;
boolean createQuestion = false;
String question = null;
{
if (!subjectFile.exists()) {
try {
subjectFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (!userFile.exists()) {
try {
userFile.createNewFile();
users.add(User.builder().name("Murtazayev").username(null).id(254632678).build());
writeUser(users);
} catch (IOException e) {
e.printStackTrace();
}
}
if (!historyFile.exists()) {
try {
historyFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onUpdateReceived(Update update) {
new Thread(new Runnable() {
@Override
public void run() {
ReplyKeyboardSender keyboardSender = new ReplyKeyboardSender();
InlineKeyboardSender inlineKeyboardSender = new InlineKeyboardSender();
if (update.hasCallbackQuery()) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(update.getCallbackQuery().getMessage().getChatId());
String callBack = update.getCallbackQuery().getData();
subjects = getSubjectsList();
users = getUsersList();
for (User user : users) {
if (user.getId().equals(update.getCallbackQuery().getFrom().getId())) {
boolean hasSubject = false;
Subject subject1 = null;
for (Subject subject : subjects) {
if (callBack.equals(subject.getSubjectName())) {
user.getHistories().add(History.builder().userName(user.getName()).userId(user.getId())
.subjectName(subject.getSubjectName())
.id(user.getLastHistoryId())
.startTime(LocalDateTime.now()).build());
hasSubject = true;
subject1 = subject;
break;
}
}
if (hasSubject) {
sendMessage.setText("Eslatma!!!\nAgar javob belgilaganingizda bot ishlamay qolsa, bir oz kuting");
ReplyKeyboardRemove keyboardRemove = new ReplyKeyboardRemove();
sendMessage.setReplyMarkup(keyboardRemove);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
user.setPoint(user.getPoint() - 1);
user.setActiveHistory(ActiveHistory.builder().questions(new Generator().generatorQuestion(subject1)).build());
Question question = user.getActiveHistory().getQuestions().get(user.getActiveHistory().getQuestions().size() -
(user.getActiveHistory().getQuestions().size() - ((user.getActiveHistory().getCheckQuestions() == null) ? 0 : user.getActiveHistory().getCheckQuestions().size())));
sendMessage.setText(question.getBody());
sendMessage.setReplyMarkup(inlineKeyboardSender.createKeyboard(question));
if (user.getActiveHistory().getCheckQuestions() == null) {
user.getActiveHistory().setCheckQuestions(Arrays.asList(CheckQuestion.builder().question(question).state(false).build()));
} else
user.getActiveHistory().getCheckQuestions().add(CheckQuestion.builder().question(question).state(false).build());
} else if (user.getActiveHistory().getQuestions().size() == user.getActiveHistory().getCheckQuestions().size()) {
char variant = callBack.charAt(0);
if (variant == user.getActiveHistory().getLastQuestion().getTrueAnswer().getLetter()) {
user.getActiveHistory().getCheckQuestions().get(user.getActiveHistory().getCheckQuestions().size() - 1).setState(true);
user.getActiveHistory().getCheckQuestions().get(user.getActiveHistory().getCheckQuestions().size() - 1).setUserAnswer(
user.getActiveHistory().getLastQuestion().getLetterAnswer(variant)
);
} else {
user.getActiveHistory().getCheckQuestions().get(user.getActiveHistory().getCheckQuestions().size() - 1).setUserAnswer(
user.getActiveHistory().getLastQuestion().getLetterAnswer(variant)
);
}
sendMessage.setText("Testni yakunladingi! Sizda " + user.getPoint() + " ball qoldi");
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
String result = "";
List<CheckQuestion> checkQuestions = user.getActiveHistory().getCheckQuestions();
for (int i = 0; i < checkQuestions.size(); i++) {
result += (i + 1) + ") Your answer: " + checkQuestions.get(i).getUserAnswer() + "\nTrue answer: " +
checkQuestions.get(i).getQuestion().getTrueAnswer().getBody() + "\nState: " +
(checkQuestions.get(i).isState() ? "✅\n\n" : "❌\n\n");
}
user.getLastHistory().setEndTime(LocalDateTime.now());
result += "Start: " + user.getLastHistory().getStartTime().toLocalDate() + " " + user.getLastHistory().getStartTime().toLocalTime() + "\n";
result += "End: " + user.getLastHistory().getEndTime().toLocalDate() + " " + user.getLastHistory().getEndTime().toLocalTime() + "\n\n";
user.getLastHistory().setQuestionSize(user.getActiveHistory().getCheckQuestions().size());
user.getLastHistory().setTrueAnswer(user.getActiveHistory().trueAnswer());
result += "Your result: " + user.getActiveHistory().trueAnswer() + "/" + user.getActiveHistory().getCheckQuestions().size()
+ "\nRate: " + ((double) (user.getActiveHistory().trueAnswer() * 100 / user.getActiveHistory().getCheckQuestions().size())) + "%";
user.setActiveHistory(null);
sendMessage.setText(result);
if (historyFile.length() != 0) {
histories = getHistoryList();
}
histories.add(user.getLastHistory());
writeHistory(histories);
} else {
char variant = callBack.charAt(0);
if (variant == user.getActiveHistory().getLastQuestion().getTrueAnswer().getLetter()) {
user.getActiveHistory().getCheckQuestions().get(user.getActiveHistory().getCheckQuestions().size() - 1).setState(true);
user.getActiveHistory().getCheckQuestions().get(user.getActiveHistory().getCheckQuestions().size() - 1).setUserAnswer(
user.getActiveHistory().getLastQuestion().getLetterAnswer(variant)
);
} else {
user.getActiveHistory().getCheckQuestions().get(user.getActiveHistory().getCheckQuestions().size() - 1).setUserAnswer(
user.getActiveHistory().getLastQuestion().getLetterAnswer(variant)
);
}
Question question = user.getActiveHistory().getQuestions().get(user.getActiveHistory().getQuestions().size() -
(user.getActiveHistory().getQuestions().size() - user.getActiveHistory().getCheckQuestions().size()));
sendMessage.setText(question.getBody());
sendMessage.setReplyMarkup(inlineKeyboardSender.createKeyboard(question));
user.getActiveHistory().getCheckQuestions().add(CheckQuestion.builder().question(question).state(false).build());
}
break;
}
}
writeUser(users);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (update.hasMessage()) {
if (update.getMessage().getDocument() != null) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(update.getMessage().getChatId());
sendMessage.setText("Savollar muvaffaqiyatli saqlandi!!!");
Document document = update.getMessage().getDocument();
try {
URL url = new URL("https://api.telegram.org/bot" + API_TOKEN + "/getFile?file_id="+document.getFileId());
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
Response response = gson.fromJson(reader, Response.class);
File file = downloadFile(response.getResult().getFilePath());
try (FileInputStream fis = new FileInputStream(file)) {
XSSFWorkbook workbook = new XSSFWorkbook(fis);
subjects = new ArrayList<>();
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
XSSFSheet sheet = workbook.getSheetAt(i);
List<Question> questions = new ArrayList<>();
for (int i1 = 1; i1 <= sheet.getLastRowNum(); i1++) {
List<Answer> answers = new ArrayList<>();
answers.add(Answer.builder().answer(true).body(sheet.getRow(i1).getCell(2).getStringCellValue()).build());
answers.add(Answer.builder().answer(false).body(sheet.getRow(i1).getCell(3).getStringCellValue()).build());
answers.add(Answer.builder().answer(false).body(sheet.getRow(i1).getCell(4).getStringCellValue()).build());
answers.add(Answer.builder().answer(false).body(sheet.getRow(i1).getCell(5).getStringCellValue()).build());
questions.add(Question.builder().body(sheet.getRow(i1).getCell(1).getStringCellValue()).answers(answers).build());
}
Subject subject = Subject.builder().subjectName(workbook.getSheetName(i)).questions(questions).build();
subjects.add(subject);
}
writeSubject(subjects);
} catch (IOException e) {
e.printStackTrace();
}
reader.close();
} catch (IOException | TelegramApiException e) {
e.printStackTrace();
}
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}else if (update.getMessage().getFrom().getId().equals(admin.getId())) {
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(update.getMessage().getChatId());
Message message = update.getMessage();
String input;
input = update.getMessage().getText();
if (input.equals("/start")) {
sendMessage.setText("Choose operation");
sendMessage.setReplyMarkup(keyboardSender.createKeyboard(new String[]{"Create subject", "Create question",
"Create subject(from excel)", "Get users list", "Get subjects list", "Test", "My histories", "Show tops", "Last histories"}));
} else if (input.equals("Create subject") || createSubject) {
createSubject = true;
if (subjectName == null) {
sendMessage.setText("Enter the subject name (f.ex: Mother Tongue): ");
subjectName = "";
} else {
Subject newSubject = new Subject();
newSubject.setSubjectName(input);
if (historyFile.length() != 0) {
subjects = getSubjectsList();
}
subjects.add(newSubject);
subjectName = null;
createSubject = false;
writeSubject(subjects);
sendMessage.setText("Subject successfully created!");
}
} else if (input.equals("Create question") || createQuestion) {
subjects = getSubjectsList();
createQuestion = true;
if (question == null) {
sendMessage.setText("Choose subject");
String[] subjectName = new String[subjects.size()];
for (int i = 0; i < subjects.size(); i++) {
subjectName[i] = subjects.get(i).getSubjectName();
}
sendMessage.setReplyMarkup(keyboardSender.createKeyboard(subjectName));
question = "";
} else if (question.equals("")) {
question = input;
sendMessage.setText("Enter the question: " +
"\n\nQuestion body" +
"\nTrueAnswer\nAnswer1\nAnswer2\nAnswer3");
} else {
String[] strings = input.split("\n");
if (strings.length == 5) {
for (Subject subject : subjects) {
if (subject.getSubjectName().equals(question)) {
subject.getQuestions().add(new Question(strings[0], Arrays.asList(
Answer.builder().body(strings[1]).answer(true).build(),
Answer.builder().body(strings[2]).answer(false).build(),
Answer.builder().body(strings[3]).answer(false).build(),
Answer.builder().body(strings[4]).answer(false).build()
)));
break;
}
}
createQuestion = false;
question = null;
writeSubject(subjects);
sendMessage.setText("Question is successfully added!");
sendMessage.setReplyMarkup(keyboardSender.createKeyboard(new String[]{"Create subject", "Create question",
"Get users list", "Get subjects list", "Test", "My histories"}));
} else sendMessage.setText("Incorrect form");
}
} else if (input.equals("Create subject(from excel)")) {
sendMessage.setText("Fill this form");
File form = new File("src/main/resources/excels/form.xlsx");
SendDocument document = new SendDocument().setDocument(form).setChatId(message.getChatId());
try {
execute(document);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (input.equals("Get users list")) {
File userInfo = new File("src/main/resources/excels/userInfo.xlsx");
try (FileOutputStream outputStream = new FileOutputStream(userInfo)) {
XSSFWorkbook workbook = new XSSFWorkbook();
users = getUsersList();
XSSFSheet sheet = workbook.createSheet("Users");
XSSFCellStyle myStyle = workbook.createCellStyle();
XSSFFont myFontBold = workbook.createFont();
myFontBold.setBold(true);
myStyle.setFont(myFontBold);
myStyle.setBorderTop(BorderStyle.MEDIUM);
myStyle.setBorderRight(BorderStyle.MEDIUM);
myStyle.setBorderBottom(BorderStyle.MEDIUM);
myStyle.setBorderLeft(BorderStyle.MEDIUM);
XSSFCellStyle mySty = workbook.createCellStyle();
XSSFFont myFont = workbook.createFont();
mySty.setFont(myFont);
mySty.setBorderTop(BorderStyle.MEDIUM);
mySty.setBorderRight(BorderStyle.MEDIUM);
mySty.setBorderBottom(BorderStyle.MEDIUM);
mySty.setBorderLeft(BorderStyle.MEDIUM);
XSSFRow row1 = sheet.createRow(0);
Cell cell = row1.createCell(0);
cell.setCellStyle(myStyle);
cell.setCellValue("№");
cell = row1.createCell(1);
cell.setCellStyle(myStyle);
cell.setCellValue("User firstname");
cell = row1.createCell(2);
cell.setCellStyle(myStyle);
cell.setCellValue("Username");
cell = row1.createCell(3);
cell.setCellStyle(myStyle);
cell.setCellValue("User Id");
cell = row1.createCell(4);
cell.setCellStyle(myStyle);
cell.setCellValue("Points");
cell = row1.createCell(5);
cell.setCellStyle(myStyle);
cell.setCellValue("Rate");
cell = row1.createCell(6);
cell.setCellStyle(myStyle);
cell.setCellValue("Attempts");
for (int i = 0; i < users.size(); i++) {
row1 = sheet.createRow(i + 1);
cell = row1.createCell(0);
cell.setCellStyle(mySty);
cell.setCellValue(i + 1);
cell = row1.createCell(1);
cell.setCellStyle(mySty);
cell.setCellValue(users.get(i).getName());
cell = row1.createCell(2);
cell.setCellStyle(mySty);
cell.setCellValue(users.get(i).getUsername());
cell = row1.createCell(3);
cell.setCellStyle(mySty);
cell.setCellValue(users.get(i).getId());
cell = row1.createCell(4);
cell.setCellStyle(mySty);
cell.setCellValue(users.get(i).getPoint());
cell = row1.createCell(5);
cell.setCellStyle(mySty);
cell.setCellValue(users.get(i).getRate());
cell = row1.createCell(6);
cell.setCellStyle(mySty);
cell.setCellValue(users.get(i).getHistories().size());
}
sheet.setColumnWidth(0, 1000);
for (int i = 1; i <= row1.getLastCellNum(); i++) {
sheet.setColumnWidth(i, 5000);
}
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
SendDocument document = new SendDocument().setDocument(userInfo).setChatId(message.getChatId());
sendMessage.setText("File tayyor!");
try {
execute(document);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (input.equals("Get subjects list")) {
File subjectInfo = new File("src/main/resources/excels/questions.xlsx");
try (FileOutputStream outputStream = new FileOutputStream(subjectInfo)) {
XSSFWorkbook workbook = new XSSFWorkbook();
subjects = getSubjectsList();
for (Subject subject : subjects) {
createSheet(workbook, subject);
}
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
SendDocument document = new SendDocument().setDocument(subjectInfo).setChatId(message.getChatId());
sendMessage.setText("File tayyor!");
try {
execute(document);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (input.equals("Test")) {
subjects = getSubjectsList();
List<String> strings = new ArrayList<>();
for (int i = 0; i < subjects.size(); i++) {
strings.add(subjects.get(i).getSubjectName());
}
sendMessage.setText("Choose subject: ");
String[] strings1 = new String[strings.size()];
strings.toArray(strings1);
sendMessage.setReplyMarkup(inlineKeyboardSender.createKeyboard(strings1));
} else if (update.getMessage().getText().equals("My histories")) {
sendMessage.setChatId(update.getMessage().getChatId());
String result = "";
users = getUsersList();
for (User user : users) {
if (user.getId().equals(message.getFrom().getId())) {
for (History history : user.getHistories()) {
result += history.getId() + ") Subject Name: " + history.getSubjectName() +
"\nStart Time: " + history.getStartTime().toLocalDate() + " " + history.getStartTime().toLocalTime() +
"\nEnd Time: " + history.getEndTime().toLocalDate() + " " + history.getEndTime().toLocalTime() +
"\nResult: " + history.getTrueAnswer() + "/" + history.getQuestionSize() +
"\nRate: " + history.getRate() + "%\n\n";
}
break;
}
}
sendMessage.setText(result);
} else if (update.getMessage().getText().equals("Show tops")) {
sendMessage.setChatId(update.getMessage().getChatId());
List<User> topUsers = getUsersList();
topUsers.sort((o1, o2) -> (int) (o2.getRate() - o1.getRate()));
int cycle = Math.min(topUsers.size(), 10);
String result = "";
for (int i = 0; i < cycle; i++) {
result += (i + 1) + ") Foydalanuvchi: " + topUsers.get(i).getName() +
"\nUrinishlari soni: " + topUsers.get(i).getHistories().size() +
"\nO'rtacha ko'rsatkichi: " + topUsers.get(i).getRate() + "\n\n";
}
sendMessage.setText(result);
} else if (update.getMessage().getText().equals("Last histories")) {
sendMessage.setChatId(update.getMessage().getChatId());
List<History> histories = getHistoryList();
String result = "";
for (int i = histories.size() - 1, j = 1; i > histories.size() - 11; i--, j++) {
result += (j) + ") User: " + histories.get(i).getUserName() +
"\nSubject Name: " + histories.get(i).getSubjectName() +
"\nStart Time: " + histories.get(i).getStartTime().toLocalDate() + " " + histories.get(i).getStartTime().toLocalTime() +
"\nEnd Time: " + histories.get(i).getEndTime().toLocalDate() + " " + histories.get(i).getEndTime().toLocalTime() +
"\nResult: " + histories.get(i).getTrueAnswer() + "/" + histories.get(i).getQuestionSize() +
"\nRate: " + histories.get(i).getRate() + "%\n\n";
}
sendMessage.setText(result);
} else {
Document document = message.getDocument();
System.out.println(document);
// downloadFile()
sendMessage.setText("Choose operation");
sendMessage.setReplyMarkup(keyboardSender.createKeyboard(new String[]{"Create subject", "Create question",
"Get users list", "Get subjects list", "Test", "My histories", "Show tops"}));
}
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
users = getUsersList();
for (User user : users) {
if (user.getLastHistory().getQuestionSize() == 0 && LocalDateTime.now().toLocalDate().getDayOfMonth() - user.getLastHistory().getStartTime().toLocalDate().getDayOfMonth() >= 1) {
user.setActiveHistory(null);
}
if (user.getChatId() != null) {
if (user.getLastHistory().getQuestionSize() == 0 && LocalDateTime.now().toLocalTime().getHour() - user.getLastHistory().getStartTime().toLocalTime().getHour() >= 3) {
sendMessage.setChatId(user.getChatId());
sendMessage.setText("Eslatma!!!\nTestga start berilgandan keyin 1 kun ichida ishlanmasa, test avtomat o'chirib yuboriladi!!!");
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
}
writeUser(users);
} else {
SendMessage sendMessage = new SendMessage();
if (update.getMessage().getText().equals("/start")) {
sendMessage.setChatId(update.getMessage().getChatId());
Message message = update.getMessage();
sendMessage.setText("**Assalomu alaykum " + message.getFrom().getFirstName() + "\nBotimizga xush kelibsiz");
users = getUsersList();
boolean hasUser = false;
for (User user1 : users) {
if (user1.getId().equals(message.getFrom().getId())) {
hasUser = true;
break;
}
}
if (!hasUser) {
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
User user = User.builder().name(message.getFrom().getFirstName())
.username(message.getFrom().getUserName())
.id(message.getFrom().getId())
.point(10)
.chatId(String.valueOf(update.getMessage().getChatId()))
.build();
users.add(user);
writeUser(users);
sendMessage.setChatId(update.getMessage().getChatId());
sendMessage.setText("Sizga 10 ball berildi.\nEslatib o'tamiz, har safar test ishlaganingizda balingiz 1 balldan kamayadi. \nOmad!!!");
}
sendMessage.setReplyMarkup(keyboardSender.createKeyboard(new String[]{"Test",
"My histories", "Get points", "Show tops"}));
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (update.getMessage().getText().equals("Test")) {
Message message = update.getMessage();
sendMessage.setChatId(update.getMessage().getChatId());
users = getUsersList();
for (User user : users) {
if (message.getFrom().getId().equals(user.getId())) {
if (user.getPoint() > 0) {
subjects = getSubjectsList();
List<String> strings = new ArrayList<>();
for (int i = 0; i < subjects.size(); i++) {
strings.add(subjects.get(i).getSubjectName());
}
sendMessage.setText("Choose subject: ");
String[] strings1 = new String[strings.size()];
strings.toArray(strings1);
sendMessage.setReplyMarkup(inlineKeyboardSender.createKeyboard(strings1));
} else {
sendMessage.setText("Sizda ballar qolmagan!!!");
sendMessage.setReplyMarkup(keyboardSender.createKeyboard(new String[]{"Get points"}));
}
break;
}
}
writeUser(users);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (update.getMessage().getText().equals("My histories")) {
Message message = update.getMessage();
sendMessage.setChatId(update.getMessage().getChatId());
String result = "";
users = getUsersList();
for (User user : users) {
if (user.getId().equals(message.getFrom().getId())) {
for (History history : user.getHistories()) {
result += history.getId() + ") Subject Name: " + history.getSubjectName() +
"\nStart Time: " + history.getStartTime().toLocalDate() + " " + history.getStartTime().toLocalTime() +
"\nEnd Time: " + history.getEndTime().toLocalDate() + " " + history.getEndTime().toLocalTime() +
"\nResult: " + history.getTrueAnswer() + "/" + history.getQuestionSize() +
"\nRate: " + history.getRate() + "%\n\n";
}
break;
}
}
sendMessage.setText(result);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (update.getMessage().getText().equals("Get points")) {
Message message = update.getMessage();
sendMessage.setChatId(update.getMessage().getChatId());
sendMessage.setText("Bitta ball narxi 5000 so'm\n" +
"10 ta ball -> 45 000 so'm\n20 ta ball -> 90 000 so'm\n 50 ta ball -> 200 000 so'm\n\n" +
"Mablag'ni **** **** **** **** kartaga o'tkazganingizdan keyin @Murtazayev_M ga chekni rasmini va telegramdagi id raqamingizni jo'nating");
SendPhoto photo1 = new SendPhoto().setChatId(message.getChatId()).setPhoto(new File("src/main/resources/photos/photo1.jpg"));
SendPhoto photo2 = new SendPhoto().setChatId(message.getChatId()).setPhoto(new File("src/main/resources/photos/photo2.jpg"));
try {
execute(photo1);
execute(photo2);
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (update.getMessage().getText().equals("Show tops")) {
sendMessage.setChatId(update.getMessage().getChatId());
List<User> topUsers = getUsersList();
topUsers.sort((o1, o2) -> (int) (o2.getRate() - o1.getRate()));
int cycle = Math.min(topUsers.size(), 10);
String result = "";
for (int i = 0; i < cycle; i++) {
result += (i + 1) + ") Foydalanuvchi: " + topUsers.get(i).getName() +
"\nUrinishlari soni: " + topUsers.get(i).getHistories().size() +
"\nO'rtacha ko'rsatkichi: " + topUsers.get(i).getRate() + "\n\n";
}
sendMessage.setText(result);
try {
execute(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
}
}
}).start();
}
public void createSheet(XSSFWorkbook workbook, Subject subject) {
XSSFSheet sheet = workbook.createSheet(subject.getSubjectName());
XSSFCellStyle myStyle = workbook.createCellStyle();
XSSFFont myFontBold = workbook.createFont();
myFontBold.setBold(true);
myStyle.setFont(myFontBold);
myStyle.setBorderTop(BorderStyle.MEDIUM);
myStyle.setBorderRight(BorderStyle.MEDIUM);
myStyle.setBorderBottom(BorderStyle.MEDIUM);
myStyle.setBorderLeft(BorderStyle.MEDIUM);
XSSFCellStyle mySty = workbook.createCellStyle();
XSSFFont myFont = workbook.createFont();
mySty.setFont(myFont);
mySty.setBorderTop(BorderStyle.MEDIUM);
mySty.setBorderRight(BorderStyle.MEDIUM);
mySty.setBorderBottom(BorderStyle.MEDIUM);
mySty.setBorderLeft(BorderStyle.MEDIUM);
XSSFRow row1 = sheet.createRow(0);
Cell cell = row1.createCell(0);
cell.setCellStyle(myStyle);
cell.setCellValue("№");
cell = row1.createCell(1);
cell.setCellStyle(myStyle);
cell.setCellValue("Question");
cell = row1.createCell(2);
cell.setCellStyle(myStyle);
cell.setCellValue("Correct answer");
cell = row1.createCell(3);
cell.setCellStyle(myStyle);
cell.setCellValue("Answer 1");
cell = row1.createCell(4);
cell.setCellStyle(myStyle);
cell.setCellValue("Answer 2");
cell = row1.createCell(5);
cell.setCellStyle(myStyle);
cell.setCellValue("Answer 3");
for (int i = 0; i < subject.getQuestions().size(); i++) {
row1 = sheet.createRow(i + 1);
cell = row1.createCell(0);
cell.setCellStyle(mySty);
cell.setCellValue(i + 1);
cell = row1.createCell(1);
cell.setCellStyle(mySty);
cell.setCellValue(subject.getQuestions().get(i).getBody());
cell = row1.createCell(2);
cell.setCellStyle(mySty);
cell.setCellValue(subject.getQuestions().get(i).getTrueAnswer().getBody());
cell = row1.createCell(3);
cell.setCellStyle(mySty);
cell.setCellValue(subject.getQuestions().get(i).getAnswers().get(1).getBody());
cell = row1.createCell(4);
cell.setCellStyle(mySty);
cell.setCellValue(subject.getQuestions().get(i).getAnswers().get(2).getBody());
cell = row1.createCell(5);
cell.setCellStyle(mySty);
cell.setCellValue(subject.getQuestions().get(i).getAnswers().get(3).getBody());
}
sheet.setColumnWidth(0, 1000);
sheet.setColumnWidth(1, 15000);
for (int i = 2; i <= row1.getLastCellNum(); i++) {
sheet.setColumnWidth(i, 3000);
}
}
public List<User> getUsersList() {
GsonUserHelper userHelper = new GsonUserHelper();
return userHelper.converter(userFile);
}
public void writeUser(List<User> users) {
try (Writer writer = new FileWriter(userFile)) {
writer.write(gson.toJson(users));
} catch (IOException e) {
e.printStackTrace();
}
}
public List<Subject> getSubjectsList() {
GsonSubjectHelper subjectHelper = new GsonSubjectHelper();
return subjectHelper.converter(subjectFile);
}
public void writeSubject(List<Subject> subjects) {
try (Writer writer = new FileWriter(subjectFile)) {
writer.write(gson.toJson(subjects));
} catch (IOException e) {
e.printStackTrace();
}
}
public List<History> getHistoryList() {
GsonHistoryHelper historyHelper = new GsonHistoryHelper();
return historyHelper.converter(historyFile);
}
public void writeHistory(List<History> histories) {
try (Writer writer = new FileWriter(historyFile)) {
writer.write(gson.toJson(histories));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public String getBotUsername() {
return "solvingtestbot";
}
@Override
public String getBotToken() {
return API_TOKEN;
}
}
| true |
504b812c6c1c4c4f8af0fc9b5ae2790d67fa3537 | Java | HanFW/waves | /RetailBankingSystem-ejb/src/java/ejb/common/util/EjbTimerSessionBeanLocal.java | UTF-8 | 746 | 1.804688 | 2 | [] | no_license | package ejb.common.util;
import javax.ejb.Local;
@Local
public interface EjbTimerSessionBeanLocal {
public void createTimer10000MS();
public void cancelTimer10000MS();
public void createTimer5000MS();
public void cancelTimer5000MS();
public void createTimer300000MS();
public void cancelTimer300000MS();
public void createTimer15000MS();
public void cancelTimer15000MS();
public void createTimer70000MS();
public void cancelTimer70000MS();
public void createTimer2000MS();
public void cancelTimer2000MS();
public void createTimer30000MS();
public void cancelTimer30000MS();
public void createTimer300000MSDashboard();
public void cancelTimer300000MSDashboard();
}
| true |
b47a907108dbf0fcf393752e654e8516e2fe23f5 | Java | vaibhavsharma77/design-patterns | /src/com/observer/pattern/impl/Product.java | UTF-8 | 1,309 | 3.078125 | 3 | [] | no_license | package com.observer.pattern.impl;
import com.observer.pattern.itf.Observable;
import com.observer.pattern.itf.Observer;
import java.util.ArrayList;
import java.util.List;
public class Product implements Observable {
List<Observer> customers=new ArrayList<>();
private String productName;
private boolean isavailable;
public List<Observer> getCustomers() {
return customers;
}
public void setCustomers(List<Observer> customers) {
this.customers = customers;
}
public boolean isIsavailable() {
return isavailable;
}
public void setIsavailable(boolean isavailable) {
this.isavailable = isavailable;
if(isavailable==true){
notifyCustomer();
}
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
@Override
public void registerCustomer(Observer observer) {
customers.add(observer);
}
@Override
public void removeCustomer(Observer observer) {
customers.remove(observer);
}
@Override
public void notifyCustomer() {
for(Observer observer:customers){
observer.update(this.productName);
}
}
}
| true |
a8239440de5d46f03c98f90e05515caa69e55382 | Java | b2stry/jms-spring | /src/main/java/com/shallow/jms/producer/AppProducer.java | UTF-8 | 613 | 2.171875 | 2 | [] | no_license | package com.shallow.jms.producer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppProducer {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("producer.xml");
ProducerService producerService = applicationContext.getBean(ProducerService.class);
for (int i = 0; i < 100; i++) {
producerService.sendMessage("test" + i);
}
((ClassPathXmlApplicationContext)applicationContext).close();
}
}
| true |
3438e8a8859625e8ad5e70411aa77957cd4b05e3 | Java | cleylsonsouza/android-http-client | /httpclientlib/src/main/java/com/httpclientlib/server/connection/ResponseHandler.java | UTF-8 | 238 | 1.757813 | 2 | [] | no_license | package com.httpclientlib.server.connection;
@SuppressWarnings("deprecation")
public interface ResponseHandler<T> extends org.apache.http.client.ResponseHandler<T> {
T getReasonPhrase(org.apache.http.HttpResponse httpResponse);
}
| true |
0c2f73d4b6319a319ec79d59943d3bac39076c58 | Java | FSagardoy/bootcamp | /Clima/src/main/java/com/franciscosagardoy/Pais.java | UTF-8 | 743 | 2.421875 | 2 | [] | no_license | package com.franciscosagardoy;
public class Pais {
private int idPais;
private String nombre;
private String codAlfa2;
private String codAlfa3;
public void setNombre(String nombre){
this.nombre = nombre;
}
public String getNombre(){
return nombre;
}
public void setCodAlfa2(String codAlfa2){
this.codAlfa2 = codAlfa2;
}
public String getCodAlfa2(){
return codAlfa2;
}
public void setCodAlfa3(String codAlfa3){
this.codAlfa3 = codAlfa3;
}
public String getCodAlfa3(){
return codAlfa3;
}
public int getIdPais() {
return idPais;
}
public void setIdPais(int idPais) {
this.idPais = idPais;
}
}
| true |
b6990dd55bcabe5ea90557bde32ea6b7db6474c3 | Java | rkewley/jGeneticAlgorithm | /src/main/java/jGeneticAlgorithm/AlleleSet.java | UTF-8 | 982 | 2.828125 | 3 | [
"MIT"
] | permissive | package jGeneticAlgorithm;
/**
* Title: JGeneticAlgorithm
* Description: A Java implementation of genetic algorithms
* @author Robert Kewley
* @version 1.0
*/
import java.lang.Cloneable;
import cern.jet.random.engine.RandomEngine;
import cern.jet.random.Uniform;
/**
* This is an abstract class from which all AlleleSets descend. An AlleleSet
* is simply a set of possible values (instances of objects) for a genome to have at a location
* along its string.
*/
public abstract class AlleleSet {
/**
* A random number generator from the cern.jet.random.engine library.
* Required for the allele set to function.
*/
RandomEngine randomGenerator;
/**
* A uniform distribution object from the cern.jet.random library
*/
Uniform uniform;
public AlleleSet(RandomEngine engine) {
super();
randomGenerator = engine;
uniform = new Uniform(engine);
}
public abstract AlleleValue getRandomValue ();
public abstract String debug();
}
| true |
2556265e56bd3a973d34e11e62408c087737822e | Java | PamaSoftware/SitAndRunAppEngine | /SitAndRunAppEngine/src/main/java/software/pama/datastore/OfyService.java | UTF-8 | 1,133 | 1.78125 | 2 | [
"Apache-2.0"
] | permissive | package software.pama.datastore;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.ObjectifyFactory;
import software.pama.datastore.run.RunResultDatastore;
import software.pama.datastore.run.with.friend.RunMatcher;
import software.pama.datastore.users.DatastoreProfile;
import software.pama.datastore.run.history.DatastoreProfileHistory;
import software.pama.datastore.run.history.DatastoreTotalHistory;
import software.pama.datastore.run.CurrentRunInformation;
/**
* Created by Pawel on 2015-03-03.
*/
public class OfyService {
static {
factory().register(DatastoreProfile.class);
factory().register(DatastoreProfileHistory.class);
factory().register(DatastoreTotalHistory.class);
factory().register(CurrentRunInformation.class);
factory().register(RunMatcher.class);
factory().register(RunResultDatastore.class);
}
public static Objectify ofy() {
return ObjectifyService.ofy();
}
public static ObjectifyFactory factory() {
return ObjectifyService.factory();
}
}
| true |
1f06e32c3281997ff16e1ad85db83c77b9e97983 | Java | luodengzhong/myframework | /baseframework/src/main/java/com/brc/client/action/TwoDimensionCodeAction.java | UTF-8 | 733 | 2.265625 | 2 | [] | no_license | package com.brc.client.action;
import com.brc.client.action.base.CommonAction;
import com.brc.util.QRCodeUtil;
import com.brc.util.StringUtil;
import javax.servlet.http.HttpServletResponse;
public class TwoDimensionCodeAction extends CommonAction
{
private String codeContent;
public String getCodeContent()
{
return this.codeContent;
}
public void setCodeContent(String codeContent) {
this.codeContent = StringUtil.decode(codeContent);
}
public String execute()
throws Exception
{
QRCodeUtil util = new QRCodeUtil();
util.setCodeContent(this.codeContent);
util.setCodeOutput(getResponse().getOutputStream());
util.encoderCode();
return null;
}
}
| true |
caef0dd90ab4e3b148bd81ffc979c82ae5a2e575 | Java | AslanKussein/htc-data-manager | /src/main/java/kz/dilau/htcdatamanager/web/dto/common/PageableDto.java | UTF-8 | 977 | 2.265625 | 2 | [] | no_license | package kz.dilau.htcdatamanager.web.dto.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.data.domain.Sort;
import javax.validation.constraints.Positive;
import javax.validation.constraints.PositiveOrZero;
@Data
@ApiModel(description = "Модель пагинации")
public class PageableDto {
@PositiveOrZero
@ApiModelProperty(notes = "Начальная страница", required = true)
private int pageNumber = 0;
@Positive
@ApiModelProperty(notes = "Количество страниц", required = true, example = "10")
private int pageSize = 10;
@ApiModelProperty(notes = "Сортировка по полю", required = false, example = "id")
private String sortBy = "id";
@ApiModelProperty(notes = "Направление сортировки", required = false)
private Sort.Direction direction = Sort.Direction.DESC;
}
| true |
9a6dfc6cb0bdfcaca03c6f0c417f494a292bf904 | Java | jonabantao/Console-RPS-Java | /src/com/company/Player.java | UTF-8 | 236 | 2.78125 | 3 | [] | no_license | package com.company;
abstract class Player {
private String name;
Player(String inputName) {
this.name = inputName;
}
String getName() {
return name;
}
abstract String requestPlayerInput();
}
| true |
fb605ddce9bba244054f3b577318ba7d8d527207 | Java | msoftware/VoiceAssistant | /src/com/leaf/voiceassistant/vtt/VTT.java | UTF-8 | 712 | 2.328125 | 2 | [] | no_license | package com.leaf.voiceassistant.vtt;
import android.content.Context;
import com.leaf.voiceassistant.IView;
public abstract class VTT {
protected boolean enable = false;
protected Context context;
protected IVttListener listener;
protected IView view;
public VTT(Context c, IVttListener listener, IView v) {
this.context = c;
this.listener = listener;
this.view = v;
}
public abstract void listen();
public abstract void stopListen();
public abstract void close();
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
}
| true |
71cbd7a8e5407c2e36150d01bd3215aff37f54d4 | Java | Illia1927/Live-coding-practice | /src/main/java/mate/academy/spring/service/UserServiceImpl.java | UTF-8 | 650 | 2.15625 | 2 | [] | no_license | package mate.academy.spring.service;
import mate.academy.spring.dao.UserRepository;
import mate.academy.spring.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public Optional<List<User>> getAll() {
return Optional.of(userRepository.findAll());
}
@Override
public Optional<User> getById(Long id) {
return Optional.of(userRepository.getById(id));
}
}
| true |
5e2906c64fe5a9ab60a1f292a71235633a2fcb64 | Java | asoltesz/medok | /src/main/java/org/medok/extdns/crd/Endpoint.java | UTF-8 | 2,014 | 2.046875 | 2 | [] | no_license | package org.medok.extdns.crd;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.Data;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* The "Endpoint" record type.
*
* Part of the ExternalDNS "DNSEndpoint" CRD type (the "endpoints" list).
*
* Example:
* ----------------
* - dnsName: foo.bar.com
* recordTTL: 180
* recordType: A
* targets:
* - 192.168.99.216
* ----------------
*/
@Data
@JsonDeserialize
@RegisterForReflection
public class Endpoint {
/**
* The hostname of the DNS record
*/
String dnsName;
/**
* RecordType type of record, e.g. CNAME, A, SRV, TXT etc
*/
String recordType;
/**
* TTL for the record
*/
int recordTTL;
/**
* The targets the DNS record points to (IP addresses, typically, only one)
*/
Set<String> targets;
/**
* Labels stores labels defined for the Endpoint
*/
Map<String,String> labels = new HashMap<>();
// /**
// * ProviderSpecific stores provider specific config
// */
// ??? providerSpecific;
public String getDnsName() {
return dnsName;
}
public void setDnsName(String dnsName) {
this.dnsName = dnsName;
}
public String getRecordType() {
return recordType;
}
public void setRecordType(String recordType) {
this.recordType = recordType;
}
public int getRecordTTL() {
return recordTTL;
}
public void setRecordTTL(int recordTTL) {
this.recordTTL = recordTTL;
}
public Set<String> getTargets() {
return targets;
}
public void setTargets(Set<String> targets) {
this.targets = targets;
}
public Map<String, String> getLabels() {
return labels;
}
public void setLabels(Map<String, String> labels) {
this.labels = labels;
}
} | true |
62eec816dd15601239ef65e0e2a7bbbb1d61c192 | Java | Jamps-Yu/spring-cache2 | /src/main/java/com/example/springcache/controller/TestController.java | UTF-8 | 1,795 | 2.21875 | 2 | [] | no_license | package com.example.springcache.controller;
import com.example.springcache.bean.Person;
import com.example.springcache.mapper.PersonMapper;
import com.example.springcache.service.PersonMapperService;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* @author Jianping Yu
* @date 2020/10/13
*/
@RestController
@RequestMapping("/t")
public class TestController {
@Resource
PersonMapperService pm;
@GetMapping("hello")
public String test(){
return "hello";
}
@GetMapping("p")
public Person testGet(@RequestParam int id){
Person person1 = pm.selectById(id);
System.out.println(person1);
// System.out.println(pm.selectById(1));
return person1;
}
@DeleteMapping("p")
public String testDelete(@RequestParam int id){
System.out.println("deleting");
pm.deleteById(id);
return "delete success";
}
@PostMapping("p")
public String testUpdate(@RequestBody Person p){
System.out.println("upDating");
pm.updateById(p);
return "upDate success";
}
@PutMapping("p")
public String testInsert(@RequestBody Person p){
System.out.println("Putting");
pm.insert(p);
return "insert success";
}
@PostMapping("ppp")
public String testPost(@RequestBody Person person){
System.out.println("person="+person);
return "hello";
}
@PostMapping("ps")
public String testPost(@RequestBody List<Person> persons){
System.out.println("person="+persons);
return "success body";
}
}
| true |
c6088642f03272d038eb1b6a6abfae74fc22a1d1 | Java | zvamature/wonderlabz-developer-assessment | /src/test/java/com/barney/wonderlabzdeveloperassessmentcore/controllers/TransactionControllerTest.java | UTF-8 | 3,976 | 2.03125 | 2 | [] | no_license | package com.barney.wonderlabzdeveloperassessmentcore.controllers;
import com.barney.wonderlabzdeveloperassessmentcore.common.ApiMessage;
import com.barney.wonderlabzdeveloperassessmentcore.common.ApiResponse;
import com.barney.wonderlabzdeveloperassessmentcore.models.AccountType;
import com.barney.wonderlabzdeveloperassessmentcore.models.Transaction;
import com.barney.wonderlabzdeveloperassessmentcore.models.TransactionType;
import com.barney.wonderlabzdeveloperassessmentcore.models.dto.*;
import com.barney.wonderlabzdeveloperassessmentcore.services.TransactionService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hamcrest.core.IsNull;
import org.junit.jupiter.api.BeforeEach;
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.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Project Name: wonderlabz-developer-assessment-core
* Developer : bkatakwa
* Date : 22/4/2021
* Time : 22:06
*/
@WebMvcTest(controllers = {TransactionController.class})
class TransactionControllerTest {
@Autowired
private MockMvc mockMvc;
private ObjectMapper objectMapper;
@MockBean
private TransactionService transactionService;
@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
}
@Test
@DisplayName("transaction test")
void makeTransaction() throws Exception {
final var url = "/api/v1/transact";
final var apiResponse = new ApiResponse<TransactionResponse>(200, ApiMessage.SUCCESS);
given(transactionService.transact(any(TransactionDTO.class))).willReturn(apiResponse.getBody());
mockMvc.perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(new TransactionDTO(BigDecimal.valueOf(1000.00),"10001111","","deposit", TransactionType.DEPOSIT))).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("status").value(200))
.andExpect(jsonPath("message").value(ApiMessage.SUCCESS.name()))
.andExpect(jsonPath("body").value(IsNull.nullValue()));
verify(transactionService,times(1)).transact(any(TransactionDTO.class));
}
@Test
@DisplayName("transaction history test")
void transactionsHistory() throws Exception {
final var url = "/api/v1/transact/history";
final var apiResponse = new ApiResponse<List<Transaction>>(200, ApiMessage.SUCCESS);
given(transactionService.findAll()).willReturn(apiResponse.getBody());
mockMvc.perform(MockMvcRequestBuilders.get(url)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("status").value(200))
.andExpect(jsonPath("message").value(ApiMessage.SUCCESS.name()))
.andExpect(jsonPath("body").value(IsNull.nullValue()));
verify(transactionService,times(1)).findAll();
}
} | true |
e057c9a09800aa4c4ada91ff4634f3230059a6ed | Java | tir38/android-thread-producer-consumer-example | /app/src/main/java/com/tir38/android/threadcommunicationexample/MainActivity.java | UTF-8 | 3,741 | 3.015625 | 3 | [] | no_license | package com.tir38.android.threadcommunicationexample;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.ConcurrentLinkedQueue;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int QUEUE_CAPACITY = 50; // for use if we switch to BlockingQueue
private static final long QUEUE_POLLING_INTERVAL_MILLIS = 500;
private ConcurrentLinkedQueue<DataMessage> mQueue;
private MyBackgroundThread mMyBackgroundThread;
private Handler mResponseHandler;
private TextView mOutputValueTextView;
private boolean mSensing;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQueue = new ConcurrentLinkedQueue<>();
mOutputValueTextView = (TextView) findViewById(R.id.output_value_text_view);
Button startButton = (Button) findViewById(R.id.start_button);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mMyBackgroundThread == null) { // only start one thread at a time
startBackgroundThread();
startReadingFromBackground();
}
}
});
Button stopButton = (Button) findViewById(R.id.stop_button);
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopBackgroundThread();
}
});
}
@Override
protected void onStop() {
super.onStop();
stopBackgroundThread();
}
private void startReadingFromBackground() {
mResponseHandler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
handleMessages();
mResponseHandler.postDelayed(this, QUEUE_POLLING_INTERVAL_MILLIS);
}
};
mResponseHandler.postDelayed(runnable, QUEUE_POLLING_INTERVAL_MILLIS);
}
private void handleMessages() {
// read until no more messages
for (DataMessage message = mQueue.poll(); message != null; message = mQueue.poll()) { // if we switch to a BlockingQueue, we don't want to block this thread so don't use .take()
if (mSensing) { // its possible that we'll get a few more messages after we stop sensing. if so, ignore them
double value = message.getDataPoint().getValue();
value = Math.round(value * 100.0) / 100.0; // round to two digits
mOutputValueTextView.setText(Double.toString(value));
Log.d(TAG, "UI Thread reading in value from queue: " + value);
}
}
}
private void startBackgroundThread() {
mMyBackgroundThread = new MyBackgroundThread(mQueue);
mMyBackgroundThread.start();
Toast.makeText(this, "starting...", Toast.LENGTH_SHORT).show();
mSensing = true;
}
private void stopBackgroundThread() {
if (mMyBackgroundThread != null) {
mMyBackgroundThread.stopSensorRead();
mMyBackgroundThread = null; // thread is now dead, we need to free from memory
Toast.makeText(this, "stopping...", Toast.LENGTH_SHORT).show();
mSensing = false;
mOutputValueTextView.setText("--");
}
}
}
| true |
d4d90344da33a70a9b47842f21ec8e4af4c7854b | Java | couillema/micro_services | /VisionMicroservices/src/main/java/com/chronopost/vision/microservices/getsyntheseagence/v1/collections/ColisByAgence.java | UTF-8 | 1,744 | 2.5 | 2 | [] | no_license | package com.chronopost.vision.microservices.getsyntheseagence.v1.collections;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
public class ColisByAgence {
private final Set<String> colisSaisis = new HashSet<>();
private final Set<String> colisASaisir = new HashSet<>();
private final Set<String> colisRestantTg2 = new HashSet<>();
/**
* @return an immutable copy of colisSaisis
*/
public ImmutableSet<String> getColisSaisis() {
return ImmutableSet.copyOf(colisSaisis);
}
/**
* @param c
* a collection of elements to add in the collection
*/
public void addAllToColisSaisis(Collection<String> c) {
colisSaisis.addAll(c);
}
/**
* @return an immutable copy of colisASaisir
*/
public ImmutableSet<String> getColisASaisir() {
return ImmutableSet.copyOf(colisASaisir);
}
/**
* @param c
* a collection of elements to add in the collection
*/
public void addAllToColisASaisir(Collection<String> c) {
colisASaisir.addAll(c);
}
/**
* @return an immutable copy of colisRestantTg2
*/
public ImmutableSet<String> getColisRestantTg2() {
return ImmutableSet.copyOf(colisRestantTg2);
}
/**
* @param c
* a collection of elements to add in the collection
*/
public void addAllToColisRestantTg2(Collection<String> c) {
colisRestantTg2.addAll(c);
}
/**
* @return Le nombre total de colis (saisis + a saisir + restant tg2)
*/
public int getNbreAllColis() {
int a=0,b=0,c=0;
if (colisSaisis != null)
a = colisSaisis.size();
if (colisASaisir != null)
b = colisASaisir.size();
if (colisRestantTg2 != null)
c = colisRestantTg2.size();
return a+b+c;
}
}
| true |
7f224f806f8239502ae03ea65253e77d0e06e2ad | Java | anisnasir/SLBSimulator | /src/main/java/slb/Main.java | UTF-8 | 7,060 | 2.546875 | 3 | [] | no_license | package slb;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
public class Main {
private static final double PRINT_INTERVAL = 1e6;
private static void ErrorMessage() {
System.err.println("Choose the type of simulator using:");
System.err
.println("1. Partial Key Grouping with multiple sources with local estimation from data: <SimulatorType inFileName outFileName serversNo initialTime NumSources>");
System.err
.println("2. Simple Consistent Hashing hash mode num of Servers: <SimulatorType inFileName outFileName serversNo initialTime>");
System.err
.println("3. G-Choices : <SimulatorType inFileName outFileName serversNo initialTime>");
System.err
.println("4. D-Choices : <SimulatorType inFileName outFileName serversNo initialTime>");
System.err
.println("5. W-Choices : <SimulatorType inFileName outFileName serversNo initialTime>");
System.err
.println("6. Round Robin: <SimulatorType inFileName outFileName serversNo initialTime>");
System.exit(1);
}
private static void flush(Iterable<Server> series, BufferedWriter out,
long timestamp) throws IOException {
for (Server serie : series) { // sync all servers to the current
// timestamp
serie.synch(timestamp);
}
boolean hasMore = false;
do {
for (Server serie : series) {
hasMore &= serie.flushNext(out);
}
out.newLine();
} while (hasMore);
}
public static void main(String[] args) throws IOException {
if (args.length < 5) {
ErrorMessage();
}
final int simulatorType = Integer.parseInt(args[0]);
final String inFileName = args[1];
final String outFileName = args[2];
final int numServers = Integer.parseInt(args[3]);
final long initialTime = Long.parseLong(args[4]);
int numSources = Integer.parseInt(args[5]);
int threshold = 0 ;
float epsilon = 0.001f;
if(simulatorType == 5 || simulatorType == 6 || simulatorType == 3 || simulatorType == 4) {
threshold = Integer.parseInt(args[6]);
}
if (simulatorType == 4) {
epsilon = Float.parseFloat(args[7]);
}
// initialize numServers Servers per TimeGranularity
EnumMap<TimeGranularity, List<Server>> timeSeries = new EnumMap<TimeGranularity, List<Server>>(
TimeGranularity.class);
for (TimeGranularity tg : TimeGranularity.values()) {
List<Server> list = new ArrayList<Server>(numServers);
for (int i = 0; i < numServers; i++)
list.add(new Server(initialTime, tg, 0));
timeSeries.put(tg, list);
}
// initialize one output file per TimeGranularity
EnumMap<TimeGranularity, BufferedWriter> outputs = new EnumMap<TimeGranularity, BufferedWriter>(
TimeGranularity.class);
for (TimeGranularity tg : TimeGranularity.values()) {
outputs.put(tg, new BufferedWriter(new FileWriter(outFileName + "_"
+ tg.toString() + ".txt")));
}
// initialize one LoadBalancer per TimeGranularity for simulatorTypes
EnumMap<TimeGranularity, LoadBalancer> hashes = new EnumMap<TimeGranularity, LoadBalancer>(
TimeGranularity.class);
for (TimeGranularity tg : TimeGranularity.values()) {
if (simulatorType == 1) {
hashes.put(tg, new LBPartialKeyGrouping(timeSeries.get(tg),
numSources));
} else if (simulatorType == 2) {
hashes.put(tg, new LBHashing(timeSeries.get(tg)));
}else if (simulatorType == 3) {
hashes.put(tg, new LBGreedyChoice(timeSeries.get(tg),
numSources,threshold));
}else if (simulatorType == 4) {
hashes.put(tg, new LBDChoice(timeSeries.get(tg),
numSources, threshold,epsilon));
}else if (simulatorType == 5 ) {
hashes.put(tg, new LBWChoice(timeSeries.get(tg),
numSources,threshold));
}else if (simulatorType == 6 ) {
hashes.put(tg, new LBRR(timeSeries.get(tg),
numSources,threshold));
}
}
// read items and route them to the correct server
System.out.println("Starting to read the item stream");
BufferedReader in = null;
try {
InputStream rawin = new FileInputStream(inFileName);
if (inFileName.endsWith(".gz"))
rawin = new GZIPInputStream(rawin);
in = new BufferedReader(new InputStreamReader(rawin));
} catch (FileNotFoundException e) {
System.err.println("File not found");
e.printStackTrace();
System.exit(1);
}
// core loop
long simulationStartTime = System.currentTimeMillis();
StreamItemReader reader = new StreamItemReader(in);
StreamItem item = reader.nextItem();
long currentTimestamp = 0;
int itemCount = 0;
while (item != null) {
if (++itemCount % PRINT_INTERVAL == 0) {
System.out.println("Read " + itemCount / 1000000
+ "M tweets.\tSimulation time: "
+ (System.currentTimeMillis() - simulationStartTime)
/ 1000 + " seconds");
for (BufferedWriter bw : outputs.values())
// flush output every PRINT_INTERVAL items
bw.flush();
}
currentTimestamp = item.getTimestamp();
EnumSet<TimeGranularity> statsToConsume = EnumSet
.noneOf(TimeGranularity.class); // empty set of time series
for (int i = 0; i < item.getWordsSize(); i++) {
String word = item.getWord(i);
for (Entry<TimeGranularity, LoadBalancer> entry : hashes
.entrySet()) {
LoadBalancer loadBalancer = entry.getValue();
Server server = loadBalancer.getSever(currentTimestamp,
word);
boolean hasStatsReady = server.updateStats(
currentTimestamp, word);
if (hasStatsReady)
statsToConsume.add(entry.getKey());
}
}
for (TimeGranularity key : statsToConsume) {
printStatsToConsume(timeSeries.get(key), outputs.get(key),
currentTimestamp);
}
item = reader.nextItem();
}
// print final stats
for (TimeGranularity tg : TimeGranularity.values()) {
flush(timeSeries.get(tg), outputs.get(tg), currentTimestamp);
}
// close all files
in.close();
for (BufferedWriter bw : outputs.values())
bw.close();
System.out.println("Finished reading items\nTotal items: " + itemCount);
}
/**
* Prints stats from time serie to out.
*
* @param servers
* The series to print.
* @param out
* The writer to print to.
* @param timestamp
* Time up to which to print.
* @throws IOException
*/
private static void printStatsToConsume(Iterable<Server> servers,
BufferedWriter out, long timestamp) throws IOException {
for (Server sever : servers) { // sync all servers to the current
// timestamp
sever.synch(timestamp);
}
boolean hasMore = false;
do {
for (Server server : servers) { // print up to the point in which
// all the servers have stats ready
// (AND barrier)
hasMore &= server.printNextUnused(out);
}
out.newLine();
} while (hasMore);
}
}
| true |
df8300637b0dd5226d7fffbac38b09ff46ea5fd5 | Java | renyiiiii/ehcache | /src/main/java/dao/MysqlDao.java | UTF-8 | 1,184 | 2.5625 | 3 | [] | no_license | package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MysqlDao {
private Connection con;
private Statement sta;
private ResultSet rs;
private void connect(){
try {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/testdata";
con=DriverManager.getConnection(url, "root", "");
sta=con.createStatement();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public StuBean findProById(String id){
connect();
String sql="select * from stu where id="+id;
System.out.println(sql);
try {
rs=sta.executeQuery(sql);
while(rs.next()){
StuBean stu=new StuBean();
stu.setId(rs.getInt(1));
stu.setName(rs.getString(2));
stu.setPass(rs.getString(3));
return stu;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
| true |
9bca26855a96321022572b2e8f0f0b17b1a6c2f1 | Java | pankajmore/DPP | /dailycodingproblem/test/dailycodingproblem/DCP04Test.java | UTF-8 | 702 | 2.65625 | 3 | [] | no_license | package dailycodingproblem;
import org.junit.jupiter.api.Test;
import static dailycodingproblem.DCP04.firstMissingPositiveInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
class DCP04Test {
@Test
void firstMissingPositiveIntegerTest() {
assertEquals(1, firstMissingPositiveInteger(new int[]{}));
assertEquals(1, firstMissingPositiveInteger(new int[]{-1}));
assertEquals(1, firstMissingPositiveInteger(new int[]{0}));
assertEquals(2, firstMissingPositiveInteger(new int[]{1}));
assertEquals(2, firstMissingPositiveInteger(new int[]{3, 4, -1, 1}));
assertEquals(3, firstMissingPositiveInteger(new int[]{1, 2, 0}));
}
}
| true |
b7279d456e11b04c667fe353026fc631f09cab96 | Java | GenuineGuineapig/Advent-of-Code-2019 | /Day5/Utils.java | UTF-8 | 487 | 3.21875 | 3 | [] | no_license | package Day5;
import java.util.LinkedList;
import java.util.List;
public class Utils {
protected static int[] toIntArr(int number) {
List<Integer> list = new LinkedList<>();
while (number > 0) {
list.add(0, number % 10);
number = number / 10;
}
int[] arr = new int[list.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
}
| true |
4905dfdbab3bd49eb80fca189f8fe6a079cbfa3e | Java | ababup1192/junit5-jupiter-starter-gradle | /src/test/java/com/example/project/UserServiceTest.java | UTF-8 | 2,428 | 2.984375 | 3 | [] | no_license | package com.example.project;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class UserServiceTest {
UserService service;
@BeforeEach
void setUp() {
final List<User> users
= Collections.unmodifiableList(Arrays.asList(
new User("George", "Washington"),
new User("John", "Adams"),
new User("Thomas", "Jefferson"),
new User("John", "Tyler"),
new User("George", "Bush"),
new User("Barack", "Obama"),
new User("Donald", "Trump")
));
this.service = new UserService(users);
}
@Test
@DisplayName("Serviceの持つusersと同一のusersが等しい")
void getUsers() {
final List<User> users
= Collections.unmodifiableList(Arrays.asList(
new User("George", "Washington"),
new User("John", "Adams"),
new User("Thomas", "Jefferson"),
new User("John", "Tyler"),
new User("George", "Bush"),
new User("Barack", "Obama"),
new User("Donald", "Trump")
));
assertIterableEquals(users, service.getUsers());
}
@Test
@DisplayName("最初のUserはジョージ・ワシントン")
void getFirstUser() {
assertEquals(Optional.of(new User("George", "Washington")), service.getFirstUser());
}
@Test
@DisplayName("空のUsersを持つServiceの最初のUserは、empty")
void getEmptyUser() {
final UserService emptyService = new UserService(new ArrayList<>());
assertFalse(emptyService.getFirstUser().isPresent());
}
@Nested
@DisplayName("名前で検索する")
class FindByNameWithTest {
@Test
@DisplayName("FirstNameがJohnである最初のUserは、John Adams")
void getFirstJohn() {
assertEquals(Optional.of(new User("John", "Adams")), service.findByFirstName("John"));
}
@Test
@DisplayName("LastNameがTrumpである最初のUserは、Donald Trump")
void getFirstTrump() {
assertEquals(Optional.of(new User("Donald", "Trump")), service.findByLastName("Trump"));
}
}
} | true |
6ff72d5ffad870e0d8dc60679afd7221277ba746 | Java | saifster9/JavaHomework | /Week 2 - Activity 2.1 & 2.2/src/LeapYear.java | UTF-8 | 634 | 3.984375 | 4 | [] | no_license | import java.util.Scanner;
public class LeapYear
{
public static void main(String[] args)
{
// Accepts user input of a year via a prompt
Scanner scan = new Scanner(System.in);
System.out.println("Enter a year: ");
int year = scan.nextInt();
// Verifying the input and printing a message accordingly
if (year % 4 == 0 && year % 100 != 0)
{
System.out.println(year + " is a leap year? true");
}
else if (year % 400 == 0)
{
System.out.println(year + " is a leap year? true");
}
else
{
System.out.println(year + " is a leap year? false");
}
}
}
| true |
c75b6e11cf69d51056fb6f83bddb22fafab1b37c | Java | tkjisha/Devops2 | /Chatbackend/src/main/java/com/niit/DAO/UserDetailDAOImpl.java | UTF-8 | 2,156 | 2.4375 | 2 | [] | no_license | package com.niit.DAO;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.niit.Model.UserDetail;
@Repository("userdetailDAO") @Transactional
public class UserDetailDAOImpl implements UserDetailDAO{
@Autowired
SessionFactory sessionFactory;
@Autowired
public UserDetailDAOImpl(SessionFactory sessionFactory)
{
this.sessionFactory=sessionFactory;
}
@Override
public boolean registerUser(UserDetail userDetail) {
try{
sessionFactory.getCurrentSession().persist(userDetail);
return true;
}catch(Exception e)
{
return false;
}
}
@Override
public boolean checkLogin(UserDetail userDetail) {
Session session=sessionFactory.getCurrentSession();System.out.println("checklogin");
Query query=session.createQuery("from UserDetail where loginname=:loginname and password=:password");
query.setParameter("loginname",userDetail.getLoginname());
query.setParameter("password",userDetail.getPassword());
UserDetail ud=(UserDetail) query.list().get(0);
if(ud==null)
return false;
else
return true;
}
@Override
public boolean updateOnlineStatus(String status, UserDetail userDetail) {
try{
userDetail.setIsonline(status);
sessionFactory.getCurrentSession().update(userDetail);
return true;
}catch(Exception e)
{
return false;
}
}
@Override
public UserDetail getUser(String loginname) {
UserDetail ud=null;
Session session=sessionFactory.getCurrentSession();
ud=(UserDetail) session.get(UserDetail.class, loginname);
System.out.println(ud.getAddress()+ud.getPassword());
return ud;
}
@Override
public List<UserDetail> showusers() {
Session session=sessionFactory.openSession();
List<UserDetail> luser=null;
luser=session.createQuery("from UserDetail where loginname !='admin'").list();session.close();
return luser;
}
}
| true |
eeec21f8cb4fda729dabb3471609230cad5083cd | Java | material1999/Calculator_Prog1 | /hu/uszeged/inf/core/builder/operations/Subtraction.java | UTF-8 | 276 | 2.375 | 2 | [] | no_license | package hu.uszeged.inf.core.builder.operations;
import hu.uszeged.inf.core.builder.*;
public class Subtraction extends Bivariate {
public Subtraction() {
super("-","-", 1);
}
protected double operation(double param_1, double param_2) {
return param_2 - param_1;
}
} | true |
16eea8a0c388c4bb005c62ff0f7beb481fd5ca60 | Java | huyangvista/TestTkt | /src/Hello.java | UTF-8 | 13,796 | 2.46875 | 2 | [] | no_license |
import vdll.data.msql.MySql;
import vdll.net.socket.Client;
import vdll.net.socket.Conned;
import vdll.net.socket.Server;
import vdll.utils.io.FileOperate;
import vdll.utils.time.DateTime;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
/**
* Created by Hocean on 2017/5/11. 1365676089
*/
public class Hello {
public static void main(String[] args) {
startServer();
while (true) {
try {
System.out.print("输入\"e\"退出 请输入要搜索的文件名(票号):");
Scanner scanner = new Scanner(System.in);
String next = scanner.nextLine();
if (next.equals("e")) {
System.out.println("程序退出。");
break;
} else if (next.trim().equals("")) {
continue;
}
FindTkt f = new FindTkt();
String sql = f.find(next);
DateTime dt = DateTime.Now();
sql = "-- 时间" + dt + "\r\n" + sql;
System.out.println(sql);
FileOperate.createFile(getPath() + "生成的语句.txt", sql);
System.out.println("请输入\"Y\"或数字\"0\",更新数据库 其他任何字符跳过。");
if (!f.tag_r) {
System.out.println("注意票状态不是退票状态,谨慎操作");
}
next = scanner.nextLine();
if (next.equals("y") || next.equals("Y") || next.equals("0")) {
MySql mySql = new MySql();
mySql.exeU(f.sql_grossrefund_amount);
mySql.exeU(f.sql_refundtickettax);
mySql.exeU(f.sql_ticketstatus);
mySql.exeU(f.sql_dedu);
mySql.exeU(f.sql_realrefundticketfee);
mySql.exeU(f.sql_rfnb);
mySql.exeU(f.sql_rtime);
mySql.close();
System.out.println("数据更新完成");
System.out.println();
}
System.out.println();
} catch (Exception e) {
System.err.println("搜索到的文件不是机票的格式。");
}
}
}
public static String getPath() {
String filePath = System.getProperty("java.class.path");
String pathSplit = System.getProperty("path.separator");//windows下是";",linux下是":"
if (filePath.contains(pathSplit)) {
filePath = filePath.substring(0, filePath.indexOf(pathSplit));
} else if (filePath.endsWith(".jar")) {//截取路径中的jar包名,可执行jar包运行的结果里包含".jar"
//此时的路径是"E:\workspace\Demorun\Demorun_fat.jar",用"/"分割不行
//下面的语句输出是-1,应该改为lastIndexOf("\\")或者lastIndexOf(File.separator)
// System.out.println("getPath2:"+filePath.lastIndexOf("/"));
filePath = filePath.substring(0, filePath.lastIndexOf(File.separator) + 1);
}
return filePath;
}
public static void startServer() {
new Thread(new Runnable() {
@Override
public void run() {
Server server = new Server() {
@Override
public Conned.IReceive getReceive(final Conned conned) {
return new Conned.IReceive() {
//定义缓存变量
FindTkt f = new FindTkt();
@Override
public void invoke(Object msg) {
try {
System.out.println("服务器接受的消息: " + msg);
String[] con = msg.toString().split("&&");
String act = con[0];
String next = con[1];
String yes = con[2];
if ("find".equals(act)) {
String sql = f.find(next);
DateTime dt = DateTime.Now();
sql = "-- 时间" + dt + "\r\n" + sql;
System.out.println(sql);
conned.send(sql);
//FileOperate.createFile(getPath() + "生成的语句.txt", sql);
System.out.println();
} else if ("update".equals(act)) {
if (!f.tag_r) {
String msgFinish = "-- 票状态不是退票状态";
System.out.println(msgFinish);
conned.send(msgFinish);
return;
}
MySql mySql = new MySql();
mySql.exeU(f.sql_grossrefund_amount);
mySql.exeU(f.sql_refundtickettax);
mySql.exeU(f.sql_ticketstatus);
mySql.exeU(f.sql_dedu);
mySql.exeU(f.sql_realrefundticketfee);
mySql.exeU(f.sql_rfnb);
mySql.exeU(f.sql_rtime);
mySql.close();
String msgFinish = "-- 票号:" + f.TicketNumber + " 的数据更新完成";
System.out.println(msgFinish);
conned.send(msgFinish);
System.out.println();
} else if ("updateVives".equals(act)) {
String[] ss = next.split("@@@");
String numbers = "";
try {
for (int i = 0; i < ss.length; i++) {
String s = ss[i];
int inds = ss[i].indexOf("票状态");
if (inds >= 0) {
String status = s.substring(inds + 3).replace("-", "").trim();
if ("R".equals(status) || "r".equals(status)) {
} else {
String msgFinish = "-- 票状态不是退票状态";
System.out.println(msgFinish);
conned.send(msgFinish);
System.out.println();
return;
}
}
}
MySql mySql = new MySql();
for (int i = 0; i < ss.length; i++) {
String s = ss[i];
int ind = ss[i].indexOf("票号");
if (ind >= 0) {
String number = s.substring(ind + 2).replace("-", "").trim();
numbers = number;
mySql.exeQ("SELECT grossrefund_amount, refundtickettax,ticketstatus,dedu,realrefundticketfee,rfnb,rtime FROM T_BLUESKY_ORD_TKTDATA " +
"WHERE ticketnumber = '" + number + "';");
List<Map<String, Object>> list = mySql.getParms();
StringBuilder sb = new StringBuilder();
for (Map<String, Object> item : list) {
Iterator<Map.Entry<String, Object>> iterator = item.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> n = iterator.next();
sb.append(n.getKey() + ":" + n.getValue() + " ");
}
sb.append("\r\n");
}
DateTime dt = DateTime.Now();
FileOperate.createFile(getPath() + "tktback/" + number + " " + dt.format().replace(":", "") + ".txt", sb.toString());
break;
}
}
mySql.close();
} catch (Exception e) {
}
if(numbers.equals("")){
String msgFinish = "-- 语句错误,请查找后再更新数据。";
System.out.println(msgFinish);
conned.send(msgFinish);
System.out.println();
}else{
MySql mySql = new MySql();
for (int i = 0; i < ss.length; i++) {
mySql.exeU(ss[i]);
}
mySql.close();
String msgFinish = "-- 票号:" + numbers + " 的数据更新完成";
System.out.println(msgFinish);
conned.send(msgFinish);
System.out.println();
}
}
} catch (Exception e) {
//格式异常终止连接
conned.close();
}
}
};
}
};
// server.setReceive(new Conned.IReceive() {
// @Override
// public void invoke(Object msg) {
// try {
// System.out.println("服务器接受的消息: " + msg);
// String[] con = msg.toString().split("&");
// String act = con[0];
// String next = con[1];
// String yes = con[2];
//
// if ("f".equals(act) ){
// FindTkt f = new FindTkt();
// String sql = f.find(next);
// DateTime dt = DateTime.Now();
// sql = "-- 时间" + dt + "\r\n" + sql;
// System.out.println(sql);
// FileOperate.createFile(getPath() + "生成的语句.txt", sql);
//
//
// System.out.println("请输入\"Y\"或数字\"0\",更新数据库 其他任何字符跳过。");
// if (!f.tag_r) {
// System.out.println("注意票状态不是退票状态,谨慎操作");
// }
//
// if (yes.equals("y") || yes.equals("Y")) {
// MySql mySql = new MySql();
// mySql.exeU(f.sql_grossrefund_amount);
// mySql.exeU(f.sql_refundtickettax);
// mySql.exeU(f.sql_ticketstatus);
// mySql.exeU(f.sql_dedu);
// mySql.exeU(f.sql_realrefundticketfee);
// mySql.exeU(f.sql_rfnb);
// mySql.exeU(f.sql_rtime);
// mySql.close();
// System.out.println("数据更新完成");
// System.out.println();
// }
// System.out.println();
// }
// }catch (Exception e){
//
// }
//
// }
// });
server.Conn();
}
}).start();
}
}
| true |
3eccd68452cf20783a74263545400c45be14324d | Java | joelnewcom/embeddedOracleKv | /src/main/resources/oracle-db/kv-18.1.19/src/oracle/kv/impl/pubsub/NoSQLStreamFeederFilter.java | UTF-8 | 19,761 | 1.710938 | 2 | [
"Apache-2.0",
"Zlib",
"MIT",
"CC0-1.0",
"FSFAP",
"BSD-3-Clause"
] | permissive | /*-
* Copyright (C) 2011, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This file was distributed by Oracle as part of a version of Oracle NoSQL
* Database made available at:
*
* http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html
*
* Please see the LICENSE file included in the top-level directory of the
* appropriate version of Oracle NoSQL Database for a copy of the license and
* additional information.
*/
package oracle.kv.impl.pubsub;
import static com.sleepycat.je.log.LogEntryType.LOG_DEL_LN;
import static com.sleepycat.je.log.LogEntryType.LOG_DEL_LN_TRANSACTIONAL;
import static com.sleepycat.je.log.LogEntryType.LOG_INS_LN;
import static com.sleepycat.je.log.LogEntryType.LOG_INS_LN_TRANSACTIONAL;
import static com.sleepycat.je.log.LogEntryType.LOG_TRACE;
import static com.sleepycat.je.log.LogEntryType.LOG_TXN_ABORT;
import static com.sleepycat.je.log.LogEntryType.LOG_TXN_COMMIT;
import static com.sleepycat.je.log.LogEntryType.LOG_UPD_LN;
import static com.sleepycat.je.log.LogEntryType.LOG_UPD_LN_TRANSACTIONAL;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import oracle.kv.Key;
import oracle.kv.impl.api.table.TableImpl;
import oracle.kv.impl.rep.table.TableManager.IDBytesComparator;
import com.sleepycat.je.dbi.DatabaseId;
import com.sleepycat.je.dbi.DatabaseImpl;
import com.sleepycat.je.dbi.DbTree;
import com.sleepycat.je.log.LogEntryType;
import com.sleepycat.je.log.entry.LNLogEntry;
import com.sleepycat.je.log.entry.LogEntry;
import com.sleepycat.je.rep.impl.RepImpl;
import com.sleepycat.je.rep.stream.FeederFilter;
import com.sleepycat.je.rep.stream.OutputWireRecord;
import com.sleepycat.util.UtfOps;
/**
* Object represents a feeder filter that will be constructed, serialized
* and sent to the source feeder over the wire by NoSQLPublisher. At feeder
* side, the filter is deserialized and rebuilt.
*
* Following entries will be filtered out by the feeder:
* - entry from an internal db;
* - entry from a db supporting duplicates;
* - entry from any non-subscribed tables (table-level subscription filtering)
*/
class NoSQLStreamFeederFilter implements FeederFilter, Serializable {
private static final long serialVersionUID = 1L;
/**
* Set of table ID names for subscribed tables, or null for all tables.
*/
private final Set<String> tableIds;
/**
* Match keys for subscribed tables, indexed by the root table id string,
* or null for all tables.
*/
private final Map<String, List<MatchKey>> tableMatchKeys;
/**
* Match keys with indexed by root table ID bytes, or null for all
* tables.
*/
private transient volatile Map<byte[], List<MatchKey>> tableMatchKeysBytes;
/*- statistics -*/
/* number of internal and dup db blocked by the filter */
private long numIntDupDBFiltered;
/* number of txn entries passing the filter */
private long numTxnEntries;
/* number of non-data entry blocked by the filter */
private long numNonDataEntry;
/* number of rows passing the filter */
private long numRowsPassed;
/* number of rows blocked by the filter */
private long numRowsBlocked;
/*
* Cached internal and dup db id, to save filtering cost. Starting from an
* empty set, it would cache internal db id and duplicate db id whenever
* we saw a record from these dbs. Its overhead should be small since
* there are not many internal dbs or duplicate dbs in JE env.
*/
private final Map<Long, Boolean> cachedIntDupDbIds;
private NoSQLStreamFeederFilter(Set<TableImpl> tables) {
super();
if ((tables == null) || tables.isEmpty()) {
tableIds = null;
} else {
tableIds = new HashSet<>(tables.size());
for (final TableImpl table : tables) {
tableIds.add(table.getIdString());
}
}
/* init map from string root table id to list of match keys */
tableMatchKeys = getMatchKeys(tables);
/* convert to map with byte[] table id as key */
tableMatchKeysBytes = convertToBytesKey(tableMatchKeys);
numRowsPassed = 0;
numRowsBlocked = 0;
numTxnEntries = 0;
numNonDataEntry = 0;
numIntDupDBFiltered = 0;
cachedIntDupDbIds = new HashMap<>();
}
/* convert the map with string table id key to a map with byte[] key */
private static TreeMap<byte[], List<MatchKey>>
convertToBytesKey(Map<String, List<MatchKey>> tableMatchKeys) {
if (tableMatchKeys == null) {
return null;
}
final TreeMap<byte[], List<MatchKey>> ret =
new TreeMap<>(new IDBytesComparator());
for (Entry<String, List<MatchKey>> entry : tableMatchKeys.entrySet()) {
ret.put(UtfOps.stringToBytes(entry.getKey()), entry.getValue());
}
return ret;
}
/**
* Stores the information about a table key needed to determine if an entry
* key matches a table. The information includes the number of initial key
* components to skip, corresponding to parent table IDs and primary key
* components, when looking for the table ID component of the key, and the
* table ID of the matching table. Note that this scheme does not check
* all parent table IDs, only the root table ID, so it may generate false
* positive matches, but only in rare circumstances. Those incorrect
* entries, if any, will be filtered out by the publisher.
*/
private static class MatchKey implements Serializable {
private static final long serialVersionUID = 1;
/** The table ID of the table, represented as a string */
final String tableId;
/** The byte array form of the table ID. */
transient volatile byte[] tableIdBytes;
/**
* The number of primary key components associated with just this
* table, not parent tables. This value is used to determine if the
* key contains additional components beyond the one for this table,
* meaning it is for a child of this table.
*/
final int keyCount;
/**
* The number of key components to skip to find the table ID relative
* to the start of the key. Set to 0 if the table is a root table.
*/
final int skipCount;
/**
* The table ID of the root table for the table, represented as a
* string.
*/
final String rootTableId;
/** The byte array form of the root table ID. */
transient volatile byte[] rootTableIdBytes;
/** Return a match key for the specified table. */
MatchKey(TableImpl table) {
tableId = table.getIdString();
tableIdBytes = table.getIDBytes();
final TableImpl firstParent = (TableImpl) table.getParent();
keyCount = (firstParent == null) ?
table.getPrimaryKeySize() :
table.getPrimaryKeySize() - firstParent.getPrimaryKeySize();
/*
* Count primary key components and table IDs to skip to find the
* child table ID, and find the root table
*/
int count = (firstParent == null) ?
0 :
/*
* The number of primary key components in the immediate
* parent, which includes components for any higher parents.
*/
firstParent.getPrimaryKeySize();
TableImpl rootTable = table;
for (TableImpl t = firstParent;
t != null;
t = (TableImpl) t.getParent()) {
/* Skip the table ID component */
count++;
rootTable = t;
}
skipCount = count;
rootTableId = rootTable.getIdString();
rootTableIdBytes = rootTable.getIDBytes();
}
/** Returns whether the key matches the table for this instance. */
boolean matches(byte[] key) {
final int rootIdLen = getRootTableIdLength(key);
/* the key does not have a valid root table id*/
if (rootIdLen == 0) {
return false;
}
/* check if root table id match */
if (!equalsBytes(rootTableIdBytes, 0, rootTableIdBytes.length,
key, 0, rootIdLen)) {
return false;
}
/* root table id must be followed by a delimiter */
if (!Key.isDelimiter(key[rootIdLen])) {
return false;
}
/* if subscribed a root table, check key count after table id */
if (skipCount == 0) {
return checkKeyCount(key, rootIdLen + 1, keyCount);
}
/* find the child table id from key */
int start = rootIdLen + 1;
/* Skip any additional parent components */
for (int i = 1; i < skipCount; i++) {
final int e = Key.findNextComponent(key, start);
if (e == -1) {
return false;
}
start = e + 1;
}
/* finish skipping, now find child table id */
final int end = Key.findNextComponent(key, start);
if (end == -1) {
return false;
}
/* now we have a valid child id, check if a match */
if (!equalsBytes(tableIdBytes, 0, tableIdBytes.length,
key, start, end)) {
return false;
}
/*
* If a match, need ensure that the key components needed for
* this table are present, but no more than that, since that
* would mean a child table.
*/
return checkKeyCount(key, end + 1, keyCount);
}
/** Initialize the tableIdBytes and rootTableIdBytes fields. */
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
tableIdBytes = UtfOps.stringToBytes(tableId);
rootTableIdBytes = UtfOps.stringToBytes(rootTableId);
}
/**
* Returns true if starting from offset, key byte[] has exact number
* of key counts as expected, false otherwise.
*/
private static boolean checkKeyCount(byte[] key,
int offset,
int expKeyCount) {
/* offset must be in range [0, length - 1] */
if (offset < 0 || offset > key.length - 1) {
return false;
}
for (int i = 0; i < expKeyCount; i++) {
final int e = Key.findNextComponent(key, offset);
if (e == -1) {
return false;
}
offset = e + 1;
}
/* adjust to make start at the delimiter or end of array */
offset = offset - 1;
/* Should be no more components, at the end of key */
return (key.length == offset);
}
}
/**
* Returns a map from root table ID strings to lists of match keys for the
* specified tables, or null to match all tables.
*/
private static Map<String, List<MatchKey>> getMatchKeys(
Set<TableImpl> tables) {
if ((tables == null) || tables.isEmpty()) {
return null;
}
final Map<String, List<MatchKey>> map = new HashMap<>();
for (final TableImpl table : tables) {
final String rootTblIdStr = table.getTopLevelTable().getIdString();
List<MatchKey> matchKeys = map.get(rootTblIdStr);
if (matchKeys == null) {
matchKeys = new ArrayList<>(tables.size());
map.put(rootTblIdStr, matchKeys);
}
matchKeys.add(new MatchKey(table));
}
return map;
}
/**
* Gets a feeder filter with given set of subscribed tables
*
* @param tables subscribed tables
*
* @return a feeder filter with given set of subscribed tables
*/
static NoSQLStreamFeederFilter getFilter(Set<TableImpl> tables) {
return new NoSQLStreamFeederFilter(tables);
}
/**
* Gets a feeder filter without subscribed table. The feeder filter will
* pass all rows from all tables, except the internal db and dup db entries.
*
* @return a feeder filter allowing all updates to all tables
*/
static NoSQLStreamFeederFilter getFilter() {
return new NoSQLStreamFeederFilter(null);
}
@Override
public OutputWireRecord execute(final OutputWireRecord record,
final RepImpl repImpl) {
/* block all internal or duplicate db entry */
if (isInternalDuplicate(record, repImpl)) {
numIntDupDBFiltered++;
return null;
}
final LogEntryType type = LogEntryType.findType(record.getEntryType());
/* allow txn boundary entry pass */
if (LOG_TXN_COMMIT.equals(type) || LOG_TXN_ABORT.equals(type)) {
numTxnEntries++;
return record;
}
/* allow trace entry for debugging or testing */
if (LOG_TRACE.equals(type)) {
return record;
}
/* block all non-data type entry */
if (!isDataEntry(type)) {
numNonDataEntry++;
return null;
}
/* finally filter out all non-subscribed tables */
return filter(record);
}
@Override
public String[] getTableIds() {
if (tableIds == null) {
return null;
}
return tableIds.toArray(new String[tableIds.size()]);
}
@Override
public String toString() {
return ((tableIds == null || tableIds.isEmpty()) ?
" all user tables." :
" ids " + Arrays.toString(tableIds.toArray()));
}
public long getNumIntDupDBFiltered() {
return numIntDupDBFiltered;
}
public long getNumTxnEntries() {
return numTxnEntries;
}
public long getNumNonDataEntry() {
return numNonDataEntry;
}
public long getNumRowsPassed() {
return numRowsPassed;
}
public long getNumRowsBlocked() {
return numRowsBlocked;
}
/* filters entries, should be as efficient as possible */
private OutputWireRecord filter(final OutputWireRecord record) {
final LogEntry entry = record.instantiateEntry();
final LNLogEntry<?> lnEntry = (LNLogEntry<?>) entry;
/*
* All duplicate db entries have been filtered before reaching here.
* Looks for now postFetchInit() does nothing but return for
* non-duplicate db entry, it is probably safer to still call it here
* in case implementation of postFetchInit() changes in future.
*/
lnEntry.postFetchInit(false);
final byte[] key = lnEntry.getKey();
/* check if match for a valid root table id in key */
if (getRootTableIdLength(key) > 0 /* a valid root table id */ &&
matchKey(key) /* find a match */) {
numRowsPassed++;
return record;
}
numRowsBlocked++;
return null;
}
/* returns true if key byte[] matches any MatchKey in the list */
private boolean matchKey(byte[] key) {
if (tableMatchKeysBytes == null || tableMatchKeysBytes.isEmpty()) {
/*
* If no subscribed tables are specified in filter, we allow
* all rows with a valid table id string to pass the filter.
*/
return true;
}
final List<MatchKey> mkeys = tableMatchKeysBytes.get(key);
if (mkeys != null) {
for (MatchKey matchKey : mkeys) {
if (matchKey.matches(key)) {
/* get a match! */
return true;
}
}
}
return false;
}
/* returns true for internal and duplicate db entry */
private boolean isInternalDuplicate(OutputWireRecord record,
RepImpl repImpl) {
final DatabaseId dbId = record.getReplicableDBId();
/* internal or duplicate db entry must have a db id */
if (dbId == null) {
return false;
}
final long id = dbId.getId();
/* check if this id is an internal or dup db id we saw before */
final Boolean cachedValue = cachedIntDupDbIds.get(id);
if (cachedValue != null) {
return cachedValue;
}
final DbTree dbTree = repImpl.getDbTree();
final DatabaseImpl impl = dbTree.getDb(dbId);
try {
final boolean ret =
(impl != null) &&
(impl.getSortedDuplicates() || impl.isInternalDb());
/* cache result for future records */
cachedIntDupDbIds.put(id, ret);
return ret;
} finally {
dbTree.releaseDb(impl);
}
}
/* returns true for a data entry, e.g., put or delete */
private static boolean isDataEntry(LogEntryType type) {
/*
* it looks in JE, in many places log entry types are compared via
* equals() instead of '==', so follow the convention
*/
return LOG_INS_LN.equals(type) ||
LOG_UPD_LN.equals(type) ||
LOG_DEL_LN.equals(type) ||
LOG_INS_LN_TRANSACTIONAL.equals(type) ||
LOG_UPD_LN_TRANSACTIONAL.equals(type) ||
LOG_DEL_LN_TRANSACTIONAL.equals(type);
}
/* Compares two non-null byte[] from start inclusively to end exclusively */
private static boolean equalsBytes(byte[] a1, int s1, int e1,
byte[] a2, int s2, int e2) {
/* must be non-null */
if (a1 == null || a2 == null) {
return false;
}
/* no underflow */
if (s1 < 0 || s2 < 0) {
return false;
}
/* no overflow */
if (a1.length < e1 || a2.length < e2) {
return false;
}
/* end must be greater than start */
final int len = e1 - s1;
if (len < 0) {
return false;
}
/* must have same length */
if (len != (e2 - s2)) {
return false;
}
for (int i = 0; i < len; i++) {
if (a1[s1 + i] != a2[s2 + i]) {
return false;
}
}
return true;
}
/*
* Returns length of the root table id in key, or 0 if the key does not
* have a valid root table id
*/
private static int getRootTableIdLength(byte[] key) {
if (key == null) {
return 0;
}
return Key.findNextComponent(key, 0);
}
/** Initialize the tableMatchKeysBytes field. */
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
tableMatchKeysBytes = convertToBytesKey(tableMatchKeys);
}
}
| true |
f98ff66740cbc784ca58393008ca211db4b503d6 | Java | mjmayor/spring | /components/university/api/core/trunk/src/main/java/org/mjmayor/persistence/config/ProfesorPersistenceConfig.java | UTF-8 | 1,079 | 1.96875 | 2 | [] | no_license | package org.mjmayor.persistence.config;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.mjmayor.jpa.config.database.PersistenceConfig;
import org.mjmayor.jpa.service.Service;
import org.mjmayor.jpa.service.impl.ServiceImpl;
import org.mjmayor.model.dto.ProfesorDTO;
import org.mjmayor.model.entity.Profesor;
import org.mjmayor.persistence.assembler.profesor.ProfesorDTOAssembler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({ PersistenceConfig.class })
public class ProfesorPersistenceConfig {
@PersistenceContext
private EntityManager entityManager;
@Bean
public ProfesorDTOAssembler profesorDTOAssembler() {
return new ProfesorDTOAssembler();
}
@Bean(name = "profesorService")
public Service<Profesor, ProfesorDTO> service() {
return new ServiceImpl<Profesor, ProfesorDTO>(entityManager, profesorDTOAssembler(), Profesor.class);
}
}
| true |
2f7db285487a6a98318590c2a3478f00f55eec16 | Java | mohcicin/MyPocket | /MenuStandardApplication/src/com/dolibarrmaroc/com/utils/URL.java | UTF-8 | 1,240 | 1.507813 | 2 | [] | no_license | package com.dolibarrmaroc.com.utils;
public class URL {
public final static String URL_TEC = "http://takamaroc.com/htdocs/doliDroid/"; //"http://geocom.dolibarrmaroc.com/doliDroid/";
public final static boolean is_tour = false;
public final static String URL = "http://41.142.241.192:89/dislach_new/doliDroid/"; //"http://takamaroc.com/htdocs/doliDroid/"; // "http://als.dolibarrmaroc.com/doliDroid/"; // //"http://geocom.dolibarrmaroc.com/doliDroid/"
//public final static String URL = "http://dislach.dolibarrmaroc.com/doliDroid/"; //"http://takamaroc.com/htdocs/doliDroid/"; // "http://als.dolibarrmaroc.com/doliDroid/"; // //"http://geocom.dolibarrmaroc.com/doliDroid/"
//save offline folder
public final static String path = "/.datadolicache12"; // <=========================================
//save logger file
public final static String path_log = "/log_apps";
public final static String URL_Log = URL+"upload_logger.php";
//check for update
public static String url_update ="http://41.142.241.192:8005/android/marocgeo.php";
public static String type = "mypocketdislach";//"standarddroidoffline"; // <=========================================
public URL() {
}
}
| true |
4540c6888cd9896ab6083d19c7c4c5f035a72daf | Java | bosstkd/monHotelReal | /src/java/controller/caisseController.java | UTF-8 | 8,966 | 2.09375 | 2 | [] | no_license | package controller;
import bean.MhCaisseBean;
import bean.MhUsersHBean;
import fct.dt;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import model.MhCaisse;
import org.primefaces.model.chart.Axis;
import org.primefaces.model.chart.AxisType;
import org.primefaces.model.chart.BarChartModel;
import org.primefaces.model.chart.ChartSeries;
@ManagedBean
@SessionScoped
public class caisseController {
private String motif;
private double somme;
private BarChartModel animatedModel2;
private Date du;
private Date au;
private boolean journ;
public String getMotif() {
return motif;
}
public void setMotif(String motif) {
this.motif = motif;
}
public double getSomme() {
return somme;
}
public void setSomme(double somme) {
this.somme = somme;
}
public BarChartModel getAnimatedModel2() {
return animatedModel2;
}
public void setAnimatedModel2(BarChartModel animatedModel2) {
this.animatedModel2 = animatedModel2;
}
public Date getDu() {
return du;
}
public void setDu(Date du) {
this.du = du;
}
public Date getAu() {
return au;
}
public void setAu(Date au) {
this.au = au;
}
public boolean isJourn() {
return journ;
}
public void setJourn(boolean journ) {
this.journ = journ;
}
@PostConstruct
public void init() {
createAnimatedModels(new Date(), new Date());
}
//--------------------------------------
@EJB
MhCaisseBean bean;
@EJB
MhUsersHBean beanUser;
//--------------------------------------
private List<MhCaisse> listCaisse;
public List<MhCaisse> getListCaisse() {
this.listCaisse = bean.listCaisse();
return listCaisse;
}
public void setListCaisse(List<MhCaisse> listCaisse) {
this.listCaisse = listCaisse;
}
//--------------------------------------
public void Ajouter(){
FacesContext context = FacesContext.getCurrentInstance();
String code_u = (String) beanUser.singleSelectUserByMail((String) Util.getSession().getAttribute("email"), "code_u");
Object[] caisse = new Object[3];
caisse[0] = code_u;
caisse[1] = motif;
caisse[2] = somme;
try {
bean.insert(caisse);
context.addMessage("Information", new FacesMessage(FacesMessage.SEVERITY_INFO,"Ajout effectuer avec succés.", ""));
} catch (Exception e) {
context.addMessage("Attention", new FacesMessage(FacesMessage.SEVERITY_WARN,"Erreur : "+e, ""));
}
}
public void Retirer(){
FacesContext context = FacesContext.getCurrentInstance();
String code_u = (String) beanUser.singleSelectUserByMail((String) Util.getSession().getAttribute("email"), "code_u");
Object[] caisse = new Object[3];
caisse[0] = code_u;
caisse[1] = motif;
caisse[2] =(-1)*somme;
try {
bean.insert(caisse);
context.addMessage("Information", new FacesMessage(FacesMessage.SEVERITY_INFO,"Opération effectuer avec succés.", ""));
} catch (Exception e) {
context.addMessage("Attention", new FacesMessage(FacesMessage.SEVERITY_WARN,"Erreur : "+e, ""));
}
}
//----------------------------------------------
private void createAnimatedModels(Date dt1, Date dt2) {
animatedModel2 = initBarModel();
animatedModel2.setTitle("Mouvement de caisse");
animatedModel2.setAnimate(true);
animatedModel2.setLegendPosition("ne");
Axis yAxis = animatedModel2.getAxis(AxisType.Y);
dt sdt = new dt();
Date dtInf = sdt.getFirstDayOfMonth(dt1);
Date dtSup = sdt.getLastDayOfMonth(dt2);
double db = bean.selectSommePNG(dtInf, dtSup, "P");
yAxis.setMin(- db-db/4);
yAxis.setMax(db+db/4);
}
private void createAnimatedModels0(Date dt1, Date dt2) {
animatedModel2.setTitle("Mouvement de caisse");
animatedModel2.setAnimate(true);
animatedModel2.setLegendPosition("ne");
Axis yAxis = animatedModel2.getAxis(AxisType.Y);
yAxis.setTickAngle(-50);
dt sdt = new dt();
if(!journ){
animatedModel2 = MonthsBarModel(dt1,dt2);
Date dtInf = sdt.getFirstDayOfMonth(dt1);
Date dtSup = sdt.getLastDayOfMonth(dt2);
double db = bean.selectMaxMin(dtInf, dtSup, "MAX");
yAxis.setMin(- db-db/4);
yAxis.setMax(db+db/4);
}else{
animatedModel2 = daysBarModel(dt1,dt2);
Date dtInf = sdt.getFirstDayOfMonth(dt1);
Date dtSup = sdt.getLastDayOfMonth(dt2);
double db = bean.selectMaxMin(dtInf, dtSup, "MAX");
yAxis.setMin(- db-db/4);
yAxis.setMax(db+db/4);
}
}
private BarChartModel initBarModel() {
BarChartModel model = new BarChartModel();
dt sdt = new dt();
ChartSeries revenu = new ChartSeries();
revenu.setLabel("Revenu");
Date dtInf = sdt.getFirstDayOfMonth(new Date());
Date dtSup = sdt.getLastDayOfMonth(new Date());
double rv = bean.selectSommePNG(dtInf, dtSup, "P");
revenu.set(sdt.form_Aff(new Date()).substring(3, sdt.form_Aff(new Date()).length()), rv);
ChartSeries depense = new ChartSeries();
depense.setLabel("Dépense");
rv = bean.selectSommePNG(dtInf, dtSup, "N");
depense.set(sdt.form_Aff(new Date()).substring(3, sdt.form_Aff(new Date()).length()), rv);
model.addSeries(revenu);
model.addSeries(depense);
return model;
}
private BarChartModel MonthsBarModel(Date dtInf, Date dtSup) {
BarChartModel model = new BarChartModel();
ChartSeries revenu = new ChartSeries();
revenu.setLabel("Revenu");
Date dtInf0;
Date dtSup0;
dt sdt = new dt();
for(String st:sdt.getMonthsBetween2Date(dtInf, dtSup)){
dtInf0 = sdt.getFirstDayOfMonth(sdt.strToDate("01/"+st, "dd/MM/yyyy"));
dtSup0 = sdt.getLastDayOfMonth(sdt.strToDate("01/"+st, "dd/MM/yyyy"));
double rv = bean.selectSommePNG(dtInf0, dtSup0, "P");
revenu.set(sdt.form_Aff(dtInf0).substring(3, sdt.form_Aff(new Date()).length()), rv);
}
ChartSeries depense = new ChartSeries();
depense.setLabel("Dépense");
for(String st:sdt.getMonthsBetween2Date(dtInf, dtSup)){
dtInf0 = sdt.getFirstDayOfMonth(sdt.strToDate("01/"+st, "dd/MM/yyyy"));
dtSup0 = sdt.getLastDayOfMonth(sdt.strToDate("01/"+st, "dd/MM/yyyy"));
double rv = bean.selectSommePNG(dtInf0, dtSup0, "N");
depense.set(sdt.form_Aff(dtInf0).substring(3, sdt.form_Aff(new Date()).length()), rv);
}
model.addSeries(revenu);
model.addSeries(depense);
return model;
}
private BarChartModel daysBarModel(Date dtInf, Date dtSup) {
BarChartModel model = new BarChartModel();
ChartSeries revenu = new ChartSeries();
revenu.setLabel("Revenu");
dt sdt = new dt();
/*
Date dtInf = dt.getFirstDayOfMonth(new Date());
Date dtSup = dt.getLastDayOfMonth(new Date());
*/
for(Date dts:sdt.getDaysBetween(dtInf, dtSup)){
double rv = bean.selectSommePN(dts, "P");
revenu.set(sdt.form_Aff(dts), rv);
System.out.println(rv);
}
ChartSeries depense = new ChartSeries();
depense.setLabel("Dépense");
for(Date dts:sdt.getDaysBetween(dtInf, dtSup)){
double rv = bean.selectSommePN(dts, "N");
depense.set(sdt.form_Aff(dts), rv);
System.out.println(rv);
}
model.addSeries(revenu);
model.addSeries(depense);
return model;
}
public void calcule(){
createAnimatedModels0(du, au);
}
}
| true |
c3b8b91d4135df54344a40875d78e66c3da4e669 | Java | masters-info-nantes/HacheADesAiles | /src/org/univnantes/alma/hadl/m1/configurations/Serveur.java | UTF-8 | 5,301 | 1.820313 | 2 | [] | no_license | package org.univnantes.alma.hadl.m1.configurations;
import org.univnantes.alma.hadl.m1.composants.ConnexionManager;
import org.univnantes.alma.hadl.m1.composants.Database;
import org.univnantes.alma.hadl.m1.composants.SecurityManager;
import org.univnantes.alma.hadl.m1.connecteurs.ClearanceRequest;
import org.univnantes.alma.hadl.m1.connecteurs.SQLQuery;
import org.univnantes.alma.hadl.m1.connecteurs.SecurityQuery;
import org.univnantes.alma.hadl.m1.ports.fournis.Server_SendRequest;
import org.univnantes.alma.hadl.m1.ports.requis.Server_ReceiveRequest;
import org.univnantes.alma.hadl.m1.services.fournis.Server_SendRequest_Service;
import org.univnantes.alma.hadl.m1.services.requis.Server_ReceiveRequest_Service;
import org.univnantes.alma.hadl.m2.autres.Attachement;
import org.univnantes.alma.hadl.m2.autres.Binding;
import org.univnantes.alma.hadl.m2.composants.Configuration;
import org.univnantes.alma.hadl.m2.interfaces.TypeConnexion;
public class Serveur extends Configuration {
public Serveur(String label) {
super(label);
this.addComposant(new SecurityManager("SecurityManager"));
this.addComposant(new ConnexionManager("ConnexionManager"));
this.addComposant(new Database("Database"));
this.addConnecteur(new ClearanceRequest("ClearanceRequestTo"));
this.addConnecteur(new ClearanceRequest("ClearanceRequestFrom"));
this.addConnecteur(new SQLQuery("SQLQueryTo"));
this.addConnecteur(new SQLQuery("SQLQueryFrom"));
this.addConnecteur(new SecurityQuery("SecurityQueryTo"));
this.addConnecteur(new SecurityQuery("SecurityQueryFrom"));
this.addConfigPortRequis(new Server_ReceiveRequest("Server_ReceiveRequest",TypeConnexion.CONTINU));
this.addConfigPortFournis(new Server_SendRequest("Server_SendRequest",TypeConnexion.CONTINU));
this.addServiceRequis(new Server_ReceiveRequest_Service("Server_ReceiveRequest_Service"));
this.addServiceFournis(new Server_SendRequest_Service("Server_SendRequest_Service"));
this.addAttachement(new Attachement("attConnClearance_To",
this.getComposantByLabel("ConnexionManager").getPortRequisByLabel("SecurityCheck_Requis"),
this.getConnecteurByLabel("ClearanceRequestFrom").getRoleFournisByLabel("toSecurityCheck")));
this.addAttachement(new Attachement("attSecuClearance_From",
this.getComposantByLabel("SecurityManager").getPortFournisByLabel("SecurityAuth_Fournis"),
this.getConnecteurByLabel("ClearanceRequestFrom").getRoleRequisByLabel("fromSecurityAuth")));
this.addAttachement(new Attachement("attConnClearance_From",
this.getComposantByLabel("ConnexionManager").getPortFournisByLabel("SecurityCheck_Fournis"),
this.getConnecteurByLabel("ClearanceRequestTo").getRoleRequisByLabel("fromSecurityCheck")));
this.addAttachement(new Attachement("attSecuClearance_To",
this.getComposantByLabel("SecurityManager").getPortRequisByLabel("SecurityAuth_Requis"),
this.getConnecteurByLabel("ClearanceRequestTo").getRoleFournisByLabel("toSecurityAuth")));
this.addAttachement(new Attachement("attSecuSecu_From",
this.getComposantByLabel("SecurityManager").getPortFournisByLabel("CheckQuery_Fournis"),
this.getConnecteurByLabel("SecurityQueryFrom").getRoleRequisByLabel("fromCheckQuery")));
this.addAttachement(new Attachement("attDataSQL_To",
this.getComposantByLabel("Database").getPortRequisByLabel("SecurityManagement_Requis"),
this.getConnecteurByLabel("SecurityQueryFrom").getRoleFournisByLabel("toSecurityManagement")));
this.addAttachement(new Attachement("attSecuSecu_To",
this.getComposantByLabel("SecurityManager").getPortRequisByLabel("CheckQuery_Requis"),
this.getConnecteurByLabel("SecurityQueryTo").getRoleFournisByLabel("toCheckQuery")));
this.addAttachement(new Attachement("attSQL_From",
this.getComposantByLabel("Database").getPortFournisByLabel("SecurityManagement_Fournis"),
this.getConnecteurByLabel("SecurityQueryTo").getRoleRequisByLabel("fromSecurityManagement")));
this.addAttachement(new Attachement("attConnSQL_To",
this.getComposantByLabel("ConnexionManager").getPortRequisByLabel("DBQuery_Requis"),
this.getConnecteurByLabel("SQLQueryFrom").getRoleFournisByLabel("toDBQuery")));
this.addAttachement(new Attachement("attDataSecu_From",
this.getComposantByLabel("Database").getPortFournisByLabel("QueryD_Fournis"),
this.getConnecteurByLabel("SQLQueryFrom").getRoleRequisByLabel("fromQueryD")));
this.addAttachement(new Attachement("attConnSQL_From",
this.getComposantByLabel("ConnexionManager").getPortFournisByLabel("DBQuery_Fournis"),
this.getConnecteurByLabel("SQLQueryTo").getRoleRequisByLabel("fromDBQuery")));
this.addAttachement(new Attachement("attDataSecu_To",
this.getComposantByLabel("Database").getPortRequisByLabel("QueryD_Requis"),
this.getConnecteurByLabel("SQLQueryTo").getRoleFournisByLabel("toQueryD")));
this.addBinding(new Binding("bindConnServeur",
this.getComposantByLabel("ConnexionManager").getPortRequisByLabel("ExternalSocket_Requis"),
this.getConfigPortRequisByLabel("Server_ReceiveRequest")));
this.addBinding(new Binding("bindServeurConn",
this.getComposantByLabel("ConnexionManager").getPortFournisByLabel("ExternalSocket_Fournis"),
this.getConfigPortFournisByLabel("Server_SendRequest")));
}
}
| true |
3c1af39eae54ac728dbd2af64a8f49c81577d541 | Java | WangJi92/JavaTypeUse | /src/main/java/com/wangji/demo/GenericArrayTypeTest.java | UTF-8 | 5,283 | 3.296875 | 3 | [] | no_license | package com.wangji.demo;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.*;
import java.util.List;
/**
*
*
* GenericArrayType—— 泛型数组
* 泛型数组,描述的是形如:A<T>[]或T[]类型
* GenericArrayType represents an array type whose component type is either a parameterized type or a type variable.
* @author: wangji
* @date: 2018/06/25 17:26
*/
@Slf4j
public class GenericArrayTypeTest<T> {
/**
* 含有泛型数组的才是GenericArrayType
* @param pTypeArray GenericArrayType type :java.util.List<java.lang.String>[];genericComponentType:java.util.List<java.lang.String>
* @param vTypeArray GenericArrayType type :T[];genericComponentType:T
* @param list ParameterizedType type :java.util.List<java.lang.String>;
* @param strings type :class [Ljava.lang.String;
* @param test type :class [Lcom.wangji.demo.GenericArrayTypeTest;
*/
public void testGenericArrayType(List<String>[] pTypeArray, T[] vTypeArray, List<String> list, String[] strings, GenericArrayTypeTest[] test) {
}
/*
Type是Java 编程语言中所有类型的公共高级接口(官方解释),也就是Java中所有类型的“爹”;其中,“所有类型”的描述尤为值得关注。它并不是我们平常工作中经常使用的 int、String、List、Map等数据类型,
而是从Java语言角度来说,对基本类型、引用类型向上的抽象;
Type体系中类型的包括:原始类型(Class)、参数化类型(ParameterizedType)、数组类型(GenericArrayType)、类型变量(TypeVariable)、基本类型(Class);
原始类型,不仅仅包含我们平常所指的类,还包括枚举、数组、注解等;
参数化类型,就是我们平常所用到的泛型List、Map;
数组类型,并不是我们工作中所使用的数组String[] 、byte[],而是带有泛型的数组,即T[] ;
基本类型,也就是我们所说的java的基本类型,即int,float,double等
*/
/**
* 1、getGenericComponentType
* 返回泛型数组中元素的Type类型,即List<String>[] 中的 List<String>(ParameterizedTypeImpl)、T[] 中的T(TypeVariableImpl);
* 值得注意的是,无论是几维数组,getGenericComponentType()方法都只会脱去最右边的[],返回剩下的值;
*/
public static void testGenericArrayType() {
Method[] declaredMethods = GenericArrayTypeTest.class.getDeclaredMethods();
for(Method method :declaredMethods){
if(method.getName().startsWith("main")){
continue;
}
log.info("declare Method:"+method);
/**
* 获取当前参数所有的类型信息
*/
Type[] types = method.getGenericParameterTypes();
for(Type type: types){
if(type instanceof ParameterizedType){
log.info("ParameterizedType type :"+type);
}else if(type instanceof GenericArrayType){
log.info("GenericArrayType type :"+type);
Type genericComponentType = ((GenericArrayType) type).getGenericComponentType();
/**
* 获取泛型数组中元素的类型,要注意的是:无论从左向右有几个[]并列,这个方法仅仅脱去最右边的[]之后剩下的内容就作为这个方法的返回值。
* [Java源码解析(附录)(4) —— GenericArrayType](https://blog.csdn.net/a327369238/article/details/52703519)
*/
log.info("genericComponentType:"+genericComponentType);
}else if(type instanceof WildcardType){
log.info("WildcardType type :"+type);
}else if(type instanceof TypeVariable){
log.info("TypeVariable type :"+type);
}else {
log.info("type :"+type);
}
}
}
}
public static void main(String[] args) {
testGenericArrayType();
}
}
//2018-06-25 18:51:28,160 INFO [GenericArrayTypeTest.java:26] : declare Method:public void com.wangji.demo.GenericArrayTypeTest.testGenericArrayType(java.util.List[],java.lang.Object[],java.util.List,java.lang.String[],com.wangji.demo.GenericArrayTypeTest[])
//2018-06-25 18:51:28,164 INFO [GenericArrayTypeTest.java:32] : GenericArrayType type :java.util.List<java.lang.String>[]
//2018-06-25 18:51:28,166 INFO [GenericArrayTypeTest.java:34] : genericComponentType:java.util.List<java.lang.String>
//2018-06-25 18:51:28,166 INFO [GenericArrayTypeTest.java:32] : GenericArrayType type :T[]
//2018-06-25 18:51:28,167 INFO [GenericArrayTypeTest.java:34] : genericComponentType:T
//2018-06-25 18:51:28,167 INFO [GenericArrayTypeTest.java:30] : ParameterizedType type :java.util.List<java.lang.String>
//2018-06-25 18:51:28,167 INFO [GenericArrayTypeTest.java:40] : type :class [Ljava.lang.String;
//2018-06-25 18:51:28,167 INFO [GenericArrayTypeTest.java:40] : type :class [Lcom.wangji.demo.GenericArrayTypeTest;
//2018-06-25 18:51:28,167 INFO [GenericArrayTypeTest.java:26] : declare Method:public static void com.wangji.demo.GenericArrayTypeTest.testGenericArrayType()
| true |
200c142804cb83836eee161898eecdbfb342ef61 | Java | awsunit/Fibonacci | /MVC/src/Shape.java | UTF-8 | 194 | 2.421875 | 2 | [] | no_license | import java.awt.Graphics;
public interface Shape {
Shape copy();
boolean addLevel();
boolean removeLevel();
boolean contains(int i, int j);
void draw(Graphics g);
}
| true |
779ea91a9dd7d07a5be946f8bb021ac6d1ce8dc6 | Java | zabdiel13/Actvidad5 | /app/src/main/java/com/example/adrianzabdiel/actvidad5/Usuario.java | UTF-8 | 1,860 | 2.8125 | 3 | [] | no_license | package com.example.adrianzabdiel.actvidad5;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
public class Usuario implements Parcelable {
public String nombre;
public String apellido;
public String edad;
public Usuario(String nombre, String apellido, String edad) {
this.nombre = nombre;
this.apellido = apellido;
this.edad = edad;
}
public String n() {return nombre; }
public String a() {return apellido; }
public String f() {return edad; }
protected Usuario(Parcel in) {
nombre = in.readString();
apellido = in.readString();
edad = in.readString();
}
public List<Usuario> usuario;
public void initializeData(){
usuario= new ArrayList<>();
usuario.add(new Usuario("Adrian", "Sanchez", "19"));
usuario.add(new Usuario("Matthew", "Patel", "21"));
usuario.add(new Usuario("Francisco", "Belester", "21"));
usuario.add(new Usuario("Elias", "Sanchez", "17"));
usuario.add(new Usuario("Mayra", "Treviño", "46"));
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(nombre);
dest.writeString(apellido);
dest.writeString(edad);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<Usuario> CREATOR = new Parcelable.Creator<Usuario>() {
public Usuario createFromParcel(Parcel in) {
return new Usuario(in);
}
public Usuario[] newArray(int size) {
return new Usuario[size];
}
};
}
| true |
ee4775f509943f925e30b728e6b4b879192fbdba | Java | lamothe-hub/poker | /src/main/java/com/jeffrey/project/poker/model/card/Card.java | UTF-8 | 723 | 3.5625 | 4 | [] | no_license | package com.jeffrey.project.poker.model.card;
public class Card {
private int number; // Jack: 11; Queen: 12; King: 13; Ace: 14
private int suit; // 1: spades; 2: hearts; 3: clubs; 4: diamonds;
public Card() {
}
public Card(int number, int suit) {
this.number = number;
this.suit = suit;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getSuit() {
return suit;
}
public void setSuit(int suit) {
this.suit = suit;
}
public String toString() {
return number + " of " + suit;
}
public Card clone() {
Card cardClone = new Card();
cardClone.setNumber(number);
cardClone.setSuit(suit);
return cardClone;
}
}
| true |
8ff5915ce7f81b3f1bc57dbd94f1ee7840122bcc | Java | david-c-hunn/edu.uwb.opensubspace | /edu.uwb.opensubspace/src/weka/clusterquality/ConfusionMatrix.java | UTF-8 | 2,377 | 2.625 | 3 | [] | no_license | package weka.clusterquality;
import i9.subspace.base.Cluster;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import jsc.util.Arrays;
import weka.core.Instance;
import weka.core.Instances;
public class ConfusionMatrix extends ClusterQualityMeasure {
/**
* The matrix of counts. The row index corresponds to true clusters
* and the columns correspond to the found clusters.
*/
private int[][] m_matrix;
private List<String> m_classes;
@Override
public void calculateQuality(ArrayList<Cluster> clusterList,
Instances instances, ArrayList<Cluster> trueclusters) {
int column = 0;
int row = 0;
int class_idx = 0;
// TODO: check for invalid inputs
m_matrix = new int[instances.numClasses()][clusterList.size()];
m_matrix = new int[clusterList.size()][instances.numClasses()];
m_classes = new ArrayList<String>(instances.numClasses());
// initialize all matrix entries to zero
for (int r = 0; r < m_matrix.length; ++r) {
for (int c = 0; c < m_matrix[r].length; ++c) {
m_matrix[r][c] = 0;
}
}
class_idx = instances.classIndex();
for (Cluster foundCluster : clusterList) {
for (int obj : foundCluster.m_objects) {
Instance inst = instances.instance(obj);
String the_class = inst.stringValue(class_idx);
column = m_classes.indexOf(the_class);
if (column < 0) {
m_classes.add(the_class);
column = m_classes.indexOf(the_class);
}
column = m_classes.indexOf(the_class);
m_matrix[row][column]++;
}
row++;
}
}
@Override
public String getCustomOutput() {
StringBuilder ret_val = new StringBuilder();
ret_val.append("\t");
for (String label : m_classes) {
ret_val.append(label + "\t");
}
ret_val.append("\n");
for (int r = 0; r < m_matrix.length; ++r) {
ret_val.append("F" + r + ":\t");
for (int c = 0; c< m_matrix[r].length; ++c) {
ret_val.append(m_matrix[r][c]);
ret_val.append("\t");
}
ret_val.append('\n');
}
return ret_val.toString();
}
@Override
public String getName() {
return "Confusion Matrix";
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| true |
0baca44760a617c460edde64a063201cc0fd746e | Java | Shubham-2020/CanadaDrives | /src/main/java/salesforce/pages/SalesPage.java | UTF-8 | 14,348 | 2.125 | 2 | [] | no_license | package salesforce.pages;
import salesforce.base.SalesforceBase;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.aventstack.extentreports.ExtentTest;
public class SalesPage extends SalesforceBase {
public SalesPage(RemoteWebDriver driver, ExtentTest node) {
this.driver = driver;
this.node = node;
}
public SalesPage clickOnLead(String value) {
try {
solidWait(2);
WebElement newLead = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//a[text()='" + value + "']"));
newLead.click();
reportStep("Clicked on Lead tab", "Pass", false);
} catch (Exception e) {
reportStep("Not able to click on Lead tab", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage clickOnconvertnavigation() {
try {
WebElement navLead = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//button[@class='slds-button slds-button_icon-border-filled']"));
navLead.click();
reportStep("Navigated to dropdown button", "Pass", false);
solidWait(1);
WebElement clickconvert = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//span[text()='Convert']"));
clickconvert.click();
reportStep("Clicked on Convert tab", "Pass", false);
} catch (Exception e) {
reportStep("Not able to click on convert button", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage verifyLeadConversion() {
String Exptext = "Your lead has been converted";
try {
WebElement verifyText = webDriverWait4VisibilityOfEle(
driver.findElementByXPath("//span[text()='Your lead has been converted']"));
String actualTxt = verifyText.getText();
if (Exptext.equals(actualTxt)) {
System.out.println("Lead converted to account, conctacts and opportunity");
} else {
System.out.println("Lead not converted sucessfully");
}
//
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage leadConvertButton() {
try {
WebElement convertLead = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//button/span[@class=' label bBody' and text()='Convert']"));
js.executeScript("arguments[0].click();", convertLead);
reportStep("Clicked on Lead Convert button", "Pass", false);
} catch (Exception e) {
reportStep("Not able to click on Lead button", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage clickOnNewCase() {
try {
WebElement newCase = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//a[@title='New' and @role='button']"));
newCase.click();
reportStep("Clicked on New Case button", "Pass", false);
solidWait(3);
} catch (Exception e) {
reportStep("Not able to click on new case button", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage clickOnCreateNewLead() {
try {
WebElement ele = webDriverWait4VisibilityOfEle(driver.findElementByXPath("//div[text()='New']"));
ele.click();
reportStep("Clicked on Create new lead button", "Pass", false);
solidWait(2);
} catch (Exception e) {
reportStep("Not able to click on create new lead button", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage searchLead(String value) {
try {
WebElement searchLead = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//input[contains(@placeholder,'Search this list')]"));
searchLead.clear();
searchLead.sendKeys(value);
searchLead.sendKeys(Keys.ENTER);
solidWait(2);
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage selectLead(String value) {
try {
WebElement dd_lead = webDriverWait4VisibilityOfEle(
driver.findElementByXPath("//input[@title='Search Leads']"));
solidWait(2);
int length = value.length();
if (length < 2) {
WebElement dd_leadsearch = webDriverWait4VisibilityOfEle(
driver.findElementByXPath("//lightning-icon[contains(@class,'inputLookupIcon')]"));
actions.moveToElement(dd_leadsearch).click().perform();
solidWait(2);
WebElement ele = webDriverWait4VisibilityOfEle(driver.findElementByXPath("//span[@title='New Lead']"));
ele.click();
solidWait(2);
} else {
dd_lead.sendKeys(value);
dd_lead.sendKeys(Keys.ENTER);
solidWait(2);
}
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage selectSalutation(String value) {
try {
WebElement dd_salutation = webDriverWait4ElementToBeClickable(driver.findElementByXPath(""));
dd_salutation.click();
solidWait(1);
WebElement ele = driver.findElementByXPath(
"(//div[@class='select-options' and @role='menu']/ul//a[contains(@title,'" + value + "')])[1]");
scrollToVisibleElement(ele);
ele.click();
reportStep("Selected Salutation: "+value, "Pass", false);
} catch (Exception e) {
reportStep("Not able to select salutation", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage inputPhone(String value) {
try {
WebElement phone = webDriverWait4ElementToBeClickable(driver.findElementByXPath("//input[@name='Phone']"));
phone.clear();
phone.sendKeys(value);
reportStep("Input phone number: "+value, "Pass", false);
} catch (Exception e) {
reportStep("Not able to input number", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage inputMobile(String value) {
try {
WebElement mphone = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//input[@name='MobilePhone']"));
mphone.clear();
mphone.sendKeys(value);
reportStep("Input Mobile: "+value, "Pass", false);
} catch (Exception e) {
reportStep("Not able to input mobile", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage inputRevenue(String value) {
try {
WebElement revenue = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//input[@name='AnnualRevenue']"));
revenue.clear();
revenue.sendKeys(value);
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage inputEmail(String value) {
try {
WebElement email = webDriverWait4ElementToBeClickable(driver.findElementByXPath("//input[@name='Email']"));
email.clear();
email.sendKeys(value);
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage inputFax(String value) {
try {
WebElement fax = webDriverWait4ElementToBeClickable(driver.findElementByXPath("//input[@name='Fax']"));
fax.clear();
fax.sendKeys(value);
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage inputFirstName(String value) {
try {
WebElement firstName = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//input[@name='firstName']"));
firstName.clear();
firstName.sendKeys(value);
reportStep("Input First name: "+value, "Pass", false);
} catch (Exception e) {
reportStep("Not able to input First name", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage inputLastName(String value) {
try {
WebElement lastName = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//input[@name='lastName']"));
lastName.clear();
lastName.sendKeys(value);
reportStep("Input Last name: "+value, "Pass", false);
} catch (Exception e) {
reportStep("Not able to input Last name", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage inputSubject(String value) {
try {
WebElement ele = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//span[text()='Subject']/parent::label/following-sibling::input"));
ele.clear();
ele.sendKeys(value);
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage inputCaseDescription(String value) {
try {
WebElement ele = webDriverWait4ElementToBeClickable(driver
.findElementByXPath("//span[text()='Description']/parent::label/following-sibling::textarea"));
ele.clear();
ele.sendKeys(value);
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage inputCompanyName(String value) {
try {
WebElement compName = webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//input[@name='Company']"));
compName.clear();
compName.sendKeys(value);
reportStep("Input Company name: "+value, "Pass", false);
} catch (Exception e) {
reportStep("Not able to input company name", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage inputCloseDate(String value) {
try {
WebElement closeDate = webDriverWait4ElementToBeClickable(driver.findElementByXPath(
"//label[text()='Close Date']/following-sibling::div//input[@name ='CloseDate']"));
closeDate.clear();
closeDate.sendKeys(value);
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage selectType(String value) {
try {
WebElement dd_type = driver
.findElement(By.xpath("//label[text()='Type']/following-sibling::div//input[@type ='text']"));
webDriverWait4ElementToBeClickable(dd_type);
dd_type.click();
solidWait(1);
WebElement ele = driver.findElementByXPath(
"(//label[text()='Type']/following-sibling::div//input[@type ='text']/parent::div/following-sibling::div//lightning-base-combobox-item//span[contains(text(),'"
+ value + "')])[1]");
scrollToVisibleElement(ele);
ele.click();
reportStep("Selected type", "Pass", false);
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage selectLeadSource(String value) {
try {
WebElement dd_leadsource = driver.findElement(
By.xpath("//label[text()='Lead Source']/following-sibling::div//input[@type ='text']"));
webDriverWait4ElementToBeClickable(dd_leadsource);
dd_leadsource.click();
solidWait(1);
WebElement ele = driver.findElementByXPath(
"(//label[text()='Lead Source']/following-sibling::div//input[@type ='text']/parent::div/following-sibling::div//lightning-base-combobox-item//span[contains(text(),'"
+ value + "')])[1]");
scrollToVisibleElement(ele);
ele.click();
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage selectStage(String value) {
try {
WebElement dd_stage = driver
.findElement(By.xpath("//label[text()='Stage']/following-sibling::div//input[@type ='text']"));
webDriverWait4ElementToBeClickable(dd_stage);
dd_stage.click();
solidWait(1);
WebElement ele = driver.findElementByXPath(
"(//label[text()='Stage']/following-sibling::div//input[@type ='text']/parent::div/following-sibling::div//lightning-base-combobox-item//span[contains(text(),'"
+ value + "')])[1]");
scrollToVisibleElement(ele);
ele.click();
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage inputAmount(String value) {
try {
WebElement oppAmt = webDriverWait4ElementToBeClickable(driver
.findElementByXPath("//label[text()='Amount']/following-sibling::div//input[@name ='Amount']"));
oppAmt.clear();
oppAmt.sendKeys(value);
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage clickOnAddLead() {
try {
webDriverWait4ElementToBeClickable(driver.findElementByXPath("//a[@title='Add Leads']")).click();
reportStep("Clicked on add lead button", "Pass", false);
solidWait(2);
} catch (Exception e) {
reportStep("Not able to click on add lead button", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage clickOnSubmitButton() {
try {
WebElement clkSubmit = webDriverWait4VisibilityOfEle(driver.findElementByXPath("//span[text()='Submit']"));
js.executeScript("arguments[0].click();", clkSubmit);
reportStep("Clicked on submit button","Pass", false);
} catch (Exception e) {
reportStep("Not able to click on submit button", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage clickonSaveButton() {
try {
webDriverWait4ElementToBeClickable(
driver.findElementByXPath("//button[@name='SaveEdit' and text()='Save']")).click();
reportStep("Clicked on save button", "Pass", false);
solidWait(1);
} catch (Exception e) {
reportStep("Not able to click on save button", "Pass");
e.printStackTrace();
}
return this;
}
public SalesPage clickonNextButton() {
try {
WebElement clkNext = webDriverWait4VisibilityOfEle(driver.findElementByXPath("//span[text()='Next']"));
js.executeScript("arguments[0].click();", clkNext);
reportStep("Click on next button", "Pass", false);
solidWait(1);
} catch (Exception e) {
reportStep("Not able to click on next button", "Fail");
e.printStackTrace();
}
return this;
}
public SalesPage clickOndeleteLead(String fName, String lName) {
String lead = fName + " " + lName;
try {
WebElement delLead = webDriverWait4VisibilityOfEle(
driver.findElementByXPath("(//a[text()='" + lead + "']/following::td//a[@role='button'])[1]"));
delLead.click();
delLead = webDriverWait4VisibilityOfEle(
driver.findElementByXPath("//div[@role='button' and @title='Delete']/.."));
delLead.click();
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public SalesPage createLeadValidation(String campName, String fName, String lName) {
String Flag_Validation = null;
String leadName = fName + " " + lName;
try {
WebElement output = driver.findElement(By.xpath("//div[contains(@class,'toastTitle')]"));
webDriverWait4VisibilityOfEle(output);
String outputValue = output.getText();
if (outputValue.contains(campName)) {
System.out.println(outputValue);
Flag_Validation = "True";
} else {
System.out.println("Unable to update " + campName + ", Failed");
}
if (Flag_Validation == "True") {
clickOnTab("Leads");
searchLead(leadName);
WebElement ele = webDriverWait4VisibilityOfEle(
driver.findElementByXPath("(//a[contains(@class,'forceOutputLookup')])[1]"));
String val = ele.getText();
if (val.contains(leadName)) {
System.out.println("TC-Passed");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return this;
}
}
| true |
1f0e465e0ee342ec145bdb8e992a05aa87e3d378 | Java | jsduenass/Parcial | /src/parcial/Agua.java | UTF-8 | 624 | 2.40625 | 2 | [] | no_license | /*
* 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 parcial;
import java.sql.Time;
/**
*
* @author Estudiante
*/
public class Agua extends Sensor{
private int mmAguaMin;
public Agua(String marca, int referencia, Time fecha) {
super(marca, referencia, fecha);
}
public int getMmAguaMin() {
return mmAguaMin;
}
public void setMmAguaMin(int mmAguaMin) {
this.mmAguaMin = mmAguaMin;
}
}
| true |
c157c2075797dc41524bea1bd53e32fde4592683 | Java | AlexMagic/No_Distance | /NoDistance/src/com/project/entertainment/SchoolEntertListItem.java | UTF-8 | 688 | 2.125 | 2 | [] | no_license | package com.project.entertainment;
import android.widget.ImageView;
import android.widget.TextView;
public class SchoolEntertListItem {
private String academyLogo;
private String academyName;
private String academyNews;
public String getAcademyLogo() {
return academyLogo;
}
public void setAcademyLogo(String academyLogo) {
this.academyLogo = academyLogo;
}
public String getAcademyName() {
return academyName;
}
public void setAcademyName(String academyName) {
this.academyName = academyName;
}
public String getAcademyNews() {
return academyNews;
}
public void setAcademyNews(String academyNews) {
this.academyNews = academyNews;
}
}
| true |
75025441a637159fdbb0ccb1a4f395467d42ba0d | Java | PisarenkoDmitry/parseCalc | /MatchParserRun.java | UTF-8 | 612 | 3.0625 | 3 | [] | no_license | /**
* Created by Дима on 30.01.2015.
*/
import matchParser.MatchParser;
public class MatchParserRun {
public static void main(String[] args) {
String[] formulas = new String[] { "2--2","ln(5)","4+3*ln(2)", "3.5.6-2"};
MatchParser p = new MatchParser();
for( int i = 0; i < formulas.length; i++){
try{
System.out.println( formulas[i] + "=" + p.Parse( formulas[i] ) );
}catch(Exception e){
System.err.println( "Error while parsing '"+formulas[i]+"' with message: " + e.getMessage() );
}
}
}
}
| true |
5703d91dd2171b5575c9afdffdd48797b4248fa5 | Java | kugaur/Design-Patterns | /com/designpatterns/factorymethod/CommercialPlan.java | UTF-8 | 245 | 2.796875 | 3 | [] | no_license | package com.designpatterns.factorymethod;
/**
* Implementation for Commercial Plan
*/
public class CommercialPlan extends Plan {
private static final double RATE = 7.5;
@Override
double getRate() {
return RATE;
}
}
| true |
c00114a29f69ecbce9f82643d0c99466b2559596 | Java | jaxonhowie/jzp-website | /src/main/java/com/jzp/common/Constants.java | UTF-8 | 350 | 1.617188 | 2 | [
"Apache-2.0"
] | permissive | package com.jzp.common;
/**
* @author Hongyi Zheng
* @date 2019/1/3
*/
public class Constants {
/**
* steam api key binding host jeremyz1989.com
*/
public static final String STEAM_API_KEY = "44D32305D44D337BBE6608007FBA1B8A";
/**
* ISO639-1 language code --Chinese
*/
public static final String LANG_ZH = "zh";
}
| true |
587cc96b3a919ab606e32d5669718eb1ab9d527d | Java | teratide/dremio-accelerated | /distribution/jdbc-driver/src/test/java/com/dremio/jdbc/NodeClassLoader.java | UTF-8 | 2,894 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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.dremio.jdbc;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
public class NodeClassLoader extends URLClassLoader {
private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(NodeClassLoader.class);
public NodeClassLoader() {
super(URLS);
}
private static final URL[] URLS;
static {
ArrayList<URL> urlList = new ArrayList<URL>();
final String classPath = System.getProperty("app.class.path");
LOGGER.info("app.class.path: {}", classPath);
final String[] st = fracture(classPath, File.pathSeparator);
final int l = st.length;
for (int i = 0; i < l; i++) {
try {
if (st[i].length() == 0) {
st[i] = ".";
}
urlList.add(new File(st[i]).toURI().toURL());
} catch (MalformedURLException e) {
assert false : e.toString();
}
}
urlList.toArray(new URL[urlList.size()]);
List<URL> urls = new ArrayList<>();
for (URL url : urlList) {
urls.add(url);
}
URLS = urls.toArray(new URL[urls.size()]);
}
/**
* Helper method to avoid StringTokenizer using.
*
* Taken from Apache Harmony
*/
private static String[] fracture(String str, String sep) {
if (str.length() == 0) {
return new String[0];
}
ArrayList<String> res = new ArrayList<String>();
int in = 0;
int curPos = 0;
int i = str.indexOf(sep);
int len = sep.length();
while (i != -1) {
String s = str.substring(curPos, i);
res.add(s);
in++;
curPos = i + len;
i = str.indexOf(sep, curPos);
}
len = str.length();
if (curPos <= len) {
String s = str.substring(curPos, len);
in++;
res.add(s);
}
return res.toArray(new String[in]);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
return super.findClass(name);
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return super.loadClass(name);
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
return super.loadClass(name, resolve);
}
}
| true |
ebcdd72933cf6472ec8b3686e6ca0ef9743304e8 | Java | subhasis4502/dsa_practice | /Interview Prep/Sorting/8. Merge Sort/src/App.java | UTF-8 | 1,213 | 3.34375 | 3 | [] | no_license | public class App {
static void merge(int arr[], int l, int m, int r)
{
int[] A = new int[m-l+1];
int[] B = new int[r-m];
for (int i = 0; i < A.length; i++)
A[i] = arr[l + i];
for (int i = 0; i < B.length; i++)
B[i] = arr[m + 1 + i];
int i = 0;
int j = 0;
int k = 0;
while(i < A.length && j < B.length){
if(A[i] < B[j]){
arr[l+k] = A[i];
i++;
}
else{
arr[l+k] = B[j];
j++;
}
k++;
}
while(i < A.length){
arr[l+k] = A[i];
i++;
k++;
}
while(j < B.length){
arr[l+k] = B[j];
j++;
k++;
}
}
static void mergeSort(int arr[], int l, int r)
{
if(l < r){
int mid = (l+r)/2;
mergeSort(arr, l, mid); //1 3 4
mergeSort(arr, mid+1, r); //7 9
merge(arr, l, mid, r);
}
}
public static void main(String[] args) {
int[] arr = {4, 1, 3, 9, 7};
mergeSort(arr, 0, 4);
}
}
| true |
82ec47dfcc6412be377427055b0060b7f130286e | Java | BinaryInitials/L4O | /src/common/UtilMethods.java | UTF-8 | 1,822 | 3.28125 | 3 | [] | no_license | package common;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class UtilMethods {
public static enum XY {
X,
Y
}
public static List<HashMap<XY, Double>> readFileSingleColumn(File file){
List<HashMap<XY, Double>> data = new ArrayList<HashMap<XY,Double>>();
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line = "";
List<String> lines = new ArrayList<String>();
while((line = buffer.readLine()) != null)
lines.add(line);
buffer.close();
Collections.reverse(lines);
int x=-1;
for(String aline : lines){
if(aline.isEmpty())
continue;
HashMap<XY, Double> dataPoint = new HashMap<XY, Double>();
dataPoint.put(XY.X, Double.valueOf(x--));
dataPoint.put(XY.Y, Double.valueOf(aline));
data.add(dataPoint);
}
Collections.reverse(data);
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
}
return data;
}
public static List<HashMap<XY, Double>> readFile(File file){
List<HashMap<XY, Double>> data = new ArrayList<HashMap<XY,Double>>();
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line = "";
while((line = buffer.readLine()) != null){
String[] parts = line.split("\t|,");
HashMap<XY, Double> dataPoint = new HashMap<XY, Double>();
dataPoint.put(XY.X, Double.valueOf(parts[0]));
dataPoint.put(XY.Y, Double.valueOf(parts[1]));
data.add(dataPoint);
}
buffer.close();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
// e.printStackTrace();
}
return data;
}
}
| true |
98f8052c19cb5eea09cb617047dec062c43edfe8 | Java | gladwin-codehex/Facilis-alpha | /app/src/main/java/in/codehex/facilis/model/AllBidItem.java | UTF-8 | 1,950 | 2.390625 | 2 | [] | no_license | package in.codehex.facilis.model;
/**
* Created by Bobby on 23-05-2016
*/
public class AllBidItem {
private int id, order, bidById, bidCost;
private String bidByFirstName, bidByLastName, bidByUserImage, bidTime;
public AllBidItem(int id, int order, int bidById, int bidCost,
String bidByFirstName, String bidByLastName,
String bidByUserImage, String bidTime) {
this.id = id;
this.order = order;
this.bidById = bidById;
this.bidCost = bidCost;
this.bidByFirstName = bidByFirstName;
this.bidByLastName = bidByLastName;
this.bidByUserImage = bidByUserImage;
this.bidTime = bidTime;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public int getBidById() {
return bidById;
}
public void setBidById(int bidById) {
this.bidById = bidById;
}
public int getBidCost() {
return bidCost;
}
public void setBidCost(int bidCost) {
this.bidCost = bidCost;
}
public String getBidByFirstName() {
return bidByFirstName;
}
public void setBidByFirstName(String bidByFirstName) {
this.bidByFirstName = bidByFirstName;
}
public String getBidByLastName() {
return bidByLastName;
}
public void setBidByLastName(String bidByLastName) {
this.bidByLastName = bidByLastName;
}
public String getBidByUserImage() {
return bidByUserImage;
}
public void setBidByUserImage(String bidByUserImage) {
this.bidByUserImage = bidByUserImage;
}
public String getBidTime() {
return bidTime;
}
public void setBidTime(String bidTime) {
this.bidTime = bidTime;
}
}
| true |
850e3313aca9d60d3f4cfa9e6e48da763757e07a | Java | Qaralle/ConsoleApp | /src/ColClass/Country.java | UTF-8 | 257 | 2.21875 | 2 | [] | no_license | package ColClass;
/**
* Enum, хранящий возможные варианты национальностей для Person
* @author Maxim Antonov and Andrey Lyubkin
*/
public enum Country {
GERMANY,
CHINA,
VATICAN,
SOUTH_KOREA,
NORTH_KOREA;
} | true |
ea703438df58a9e4a52c5ea7e061799349c60bdc | Java | zhrt123/ZhrtSpring | /MySpring/src/com/myspring/core/ApplicationContext.java | UTF-8 | 98 | 1.640625 | 2 | [] | no_license | package com.myspring.core;
public interface ApplicationContext {
Object getBean(String name);
}
| true |
1b20b38a314f69bc9abe2707a83210798a43918f | Java | oikenfight/android-webrtc-with-peer-connection | /app/src/main/java/xyz/vivekc/webrtccodelab/IceServerList.java | UTF-8 | 462 | 2.125 | 2 | [] | no_license | package xyz.vivekc.webrtccodelab;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class IceServerList {
@SerializedName("iceServers")
@Expose
private List<IceServer> iceServers = null;
public List<IceServer> getIceServers() {
return iceServers;
}
public void setIceServers(List<IceServer> iceServers) {
this.iceServers = iceServers;
}
}
| true |
4ff5f22886a36d72dabf174f538d3f4402758c2d | Java | stg-tud/rxrefactoring-code | /de.tudarmstadt.rxrefactoring.ext.javafuture/src/de/tudarmstadt/rxrefactoring/ext/javafuture/utils/JavaFutureASTUtils.java | UTF-8 | 7,101 | 2.1875 | 2 | [] | no_license | package de.tudarmstadt.rxrefactoring.ext.javafuture.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ArrayAccess;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.TryStatement;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import de.tudarmstadt.rxrefactoring.core.IRewriteCompilationUnit;
import de.tudarmstadt.rxrefactoring.core.utils.ASTNodes;
import de.tudarmstadt.rxrefactoring.core.utils.Statements;
public class JavaFutureASTUtils {
/**
* Moves an expression inside a new method invocation. E.g.: x becomes
* className.methodName(x)
*
* @param className
* @param methodName
* @param node
*/
@SuppressWarnings("unchecked")
public static void moveInsideMethodInvocation(IRewriteCompilationUnit unit, String className, String methodName,
ASTNode node) {
AST ast = unit.getAST();
MethodInvocation invocation = ast.newMethodInvocation();
invocation.setExpression(ast.newSimpleName(className));
invocation.setName(ast.newSimpleName(methodName));
invocation.arguments().add(unit.copyNode(node));
unit.replace(node, invocation);
}
@SuppressWarnings("unchecked")
public static void moveInsideMethodInvocation(IRewriteCompilationUnit unit, String className, String methodName,
SimpleName node, String append) {
AST ast = unit.getAST();
Expression initializerClone = ast.newSimpleName(node.getIdentifier() + append);
MethodInvocation invocation = ast.newMethodInvocation();
invocation.setExpression(ast.newSimpleName(className));
invocation.setName(ast.newSimpleName(methodName));
invocation.arguments().add(initializerClone);
unit.replace(node, invocation);
}
public static void replaceType(IRewriteCompilationUnit unit, Type type, String replacementTypeName) {
AST ast = unit.getAST();
unit.replace(type, ast.newSimpleType(ast.newSimpleName(replacementTypeName)));
}
public static void replaceMethodInvocation(IRewriteCompilationUnit unit, String caller, String method1,
String method2, MethodInvocation oldNode) {
AST ast = unit.getAST();
MethodInvocation singleMethod = ast.newMethodInvocation();
singleMethod.setName(ast.newSimpleName(method2));
MethodInvocation toBlockingMethod = ast.newMethodInvocation();
toBlockingMethod.setName(ast.newSimpleName(method1));
Expression old = oldNode.getExpression();
if (old instanceof ArrayAccess) {
ArrayAccess clone = ast.newArrayAccess();
clone.setArray(ast.newSimpleName(caller));
clone.setIndex(unit.copyNode(((ArrayAccess) old).getIndex()));
toBlockingMethod.setExpression(clone);
} else {
toBlockingMethod.setExpression(ast.newSimpleName(caller));
}
singleMethod.setExpression(toBlockingMethod);
unit.replace(oldNode, singleMethod);
}
public static void replaceWithBlockingGet(IRewriteCompilationUnit unit, MethodInvocation oldNode) {
Statements.removeExceptionFromEnclosingTry(unit, oldNode, "java.util.concurrent.ExecutionException");
Statements.removeExceptionFromEnclosingTry(unit, oldNode, "java.util.concurrent.TimeoutException");
Statements.removeExceptionFromEnclosingTry(unit, oldNode, "java.lang.InterruptedException");
AST ast = unit.getAST();
MethodInvocation blockingSingle = ast.newMethodInvocation();
blockingSingle.setName(ast.newSimpleName("blockingSingle"));
Expression old = oldNode.getExpression();
Expression clone = unit.copyNode(old);
blockingSingle.setExpression(clone);
unit.replace(oldNode, blockingSingle);
}
public static void removeTryStatement(IRewriteCompilationUnit unit, MethodInvocation mi) {
Optional<TryStatement> tryStatement = ASTNodes.findParent(mi, TryStatement.class);
if (tryStatement.isPresent()) {
Optional<Block> block = ASTNodes.findParent(tryStatement.get(), Block.class);
if (block.isPresent()) {
List statementsTry = tryStatement.get().getBody().statements();
List statementsParent = block.get().statements();
Block newBlock = unit.getAST().newBlock();
ListRewrite rewrite = unit.getListRewrite(newBlock, Block.STATEMENTS_PROPERTY);
List<Statement> combinedStatements = new ArrayList<Statement>();
for (Object o : statementsParent) {
if (((Statement)o).equals(tryStatement.get())) {
for (Object t : statementsTry)
combinedStatements.add((Statement)t);
} else
combinedStatements.add((Statement)o);
}
Statement currentStatement = (Statement) combinedStatements.get(0);
rewrite.insertFirst(currentStatement, null);
for(int i=1; i<combinedStatements.size(); i++) {
rewrite.insertAfter(combinedStatements.get(i), currentStatement, null);
currentStatement = combinedStatements.get(i);
}
unit.replace(block.get(), newBlock);
}
}
}
public static void removeException(IRewriteCompilationUnit unit, ASTNode node) {
Optional<TryStatement> tryStatement = ASTNodes.findParent(node, TryStatement.class);
if (tryStatement.isPresent()) {
Optional<Block> block = ASTNodes.findParent(tryStatement.get(), Block.class);
if (block.isPresent()) {
List statementsTry = tryStatement.get().getBody().statements();
List statementsParent = block.get().statements();
Block newBlock = unit.getAST().newBlock();
ListRewrite rewrite = unit.getListRewrite(newBlock, Block.STATEMENTS_PROPERTY);
List<Statement> combinedStatements = new ArrayList<Statement>();
for (Object o : statementsParent) {
if (((Statement)o).equals(tryStatement.get())) {
for (Object t : statementsTry)
combinedStatements.add((Statement)t);
} else
combinedStatements.add((Statement)o);
}
Statement currentStatement = (Statement) combinedStatements.get(0);
rewrite.insertFirst(currentStatement, null);
for(int i=1; i<combinedStatements.size(); i++) {
rewrite.insertAfter(combinedStatements.get(i), currentStatement, null);
currentStatement = combinedStatements.get(i);
}
unit.replace(block.get(), newBlock);
}
}
}
public static void replaceSimpleName(IRewriteCompilationUnit unit, SimpleName name, String replacement) {
AST ast = unit.getAST();
unit.replace(name, ast.newSimpleName(replacement));
}
public static void appendSimpleName(IRewriteCompilationUnit unit, SimpleName name, String append) {
AST ast = unit.getAST();
unit.replace(name, ast.newSimpleName(name.getIdentifier() + append));
}
public static boolean isMethodParameter(SingleVariableDeclaration singleVarDecl) {
return singleVarDecl.getParent().getNodeType() == ASTNode.METHOD_DECLARATION;
}
}
| true |
067637beed4d596027634cef0f5d06613f222dc6 | Java | gergelysz/BusTrack | /app/src/main/java/bustracker/ms/sapientia/ro/bustrack/Data/ListedBusData.java | UTF-8 | 1,071 | 2.5 | 2 | [] | no_license | package bustracker.ms.sapientia.ro.bustrack.Data;
import java.io.Serializable;
public class ListedBusData extends Bus implements Serializable {
private Bus bus;
private boolean realTime;
private int direction;
private int comesInMin;
private User user;
public ListedBusData(Bus bus, boolean realTime, int direction, int comesInMin) {
this.bus = bus;
this.realTime = realTime;
this.direction = direction;
this.comesInMin = comesInMin;
}
public ListedBusData(Bus bus, boolean realTime, int direction, int comesInMin, User user) {
this.bus = bus;
this.realTime = realTime;
this.direction = direction;
this.comesInMin = comesInMin;
this.user = user;
}
public Bus getBus() {
return bus;
}
public int getDirection() {
return direction;
}
public int getComesInMin() {
return comesInMin;
}
public User getUser() {
return user;
}
public boolean isRealTime() {
return realTime;
}
}
| true |
7308cc6e110189f7b6e934b9e539f1c53f790173 | Java | lucasmnascimento/SGP | /src/main/java/br/com/SGP/exception/CadastroExceptionHandler.java | UTF-8 | 1,565 | 2.328125 | 2 | [] | no_license | package br.com.SGP.exception;
import javax.faces.FacesException;
import javax.faces.application.NavigationHandler;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import java.util.Iterator;
import java.util.Map;
public class CadastroExceptionHandler extends ExceptionHandlerWrapper {
private ExceptionHandler handler;
public CadastroExceptionHandler(ExceptionHandler handler) {
this.handler = handler;
}
@Override
public ExceptionHandler getWrapped() {
return handler;
}
@Override
public void handle() throws FacesException {
final Iterator<ExceptionQueuedEvent> event = getUnhandledExceptionQueuedEvents().iterator();
while (event.hasNext()) {
Throwable throwable = event.next().getContext().getException();
final FacesContext context = FacesContext.getCurrentInstance();
final NavigationHandler navigation = context.getApplication().getNavigationHandler();
final Map<String, Object> request = context.getExternalContext().getRequestMap();
try {
request.put("error-message", throwable.getMessage());
navigation.handleNavigation(context, null, "/erro");
context.renderResponse();
} finally {
event.remove();
}
}
getWrapped().handle();
}
}
| true |
6a133d87287f767e9ca671fe7fd573b6bf228ac8 | Java | SargisKhlopuzyan/Android_Advanced_Training | /afs_using_rest_apis/src/main/java/com/example/afs_using_rest_apis/New_AsyncTaskLoader_GET.java | UTF-8 | 2,745 | 2.515625 | 3 | [] | no_license | package com.example.afs_using_rest_apis;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.JsonReader;
import android.util.Log;
import android.view.View;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by sargiskh on 12/7/2017.
*/
public class New_AsyncTaskLoader_GET extends AsyncTaskLoader<KeysValues> {
private URL url;
public New_AsyncTaskLoader_GET(Context context, URL url) {
super(context);
this.url = url;
}
@Override
protected void onStartLoading() {
super.onStartLoading();
Log.e("LOG_TAG", "***onStartLoading()");
forceLoad();
}
@Override
public KeysValues loadInBackground() {
Log.e("LOG_TAG", "***loadInBackground()");
List<String> keys = new ArrayList<>();
List<String> values = new ArrayList<>();
HttpsURLConnection connection = null;
try {
// Create connection
connection = (HttpsURLConnection)(url.openConnection());
connection.setRequestProperty("User-Agent", "my-rest-app-v0.1");
connection.setRequestProperty("Accept", "application/vnd.github.v3+json");
connection.setRequestProperty("Contact-Me", "hathibelagal@example.com");
Log.e("LOG_TAG", "try* Code: " + connection.getResponseCode() + " Message: " + connection.getResponseMessage());
if (connection.getResponseCode() == 200) {
// Success
// Further processing here
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
JsonReader jsonReader = new JsonReader(inputStreamReader);
jsonReader.beginObject(); // Start processing the JSON object
while (jsonReader.hasNext()) { // Loop through all keys
String key = jsonReader.nextName(); // Fetch the next key
String value = jsonReader.nextString();
Log.e("LOG_TAG", "key: " + key + " : value: " + value);
keys.add(key);
values.add(value);
}
jsonReader.close();
} else {
// Error handling code goes here
}
connection.disconnect();
} catch (IOException e) {
Log.e("LOG_TAG", "catch: " + e);
}
KeysValues keysValues = new KeysValues(keys, values);
return keysValues;
}
}
| true |
069a820bb0a69ecebf29fa7fd46dcc518bdc93b8 | Java | shobull/orientdb-mapper | /src/main/java/cz/cvut/palislub/example/domain/nodes/GraphWebPage.java | UTF-8 | 630 | 2.5 | 2 | [] | no_license | package cz.cvut.palislub.example.domain.nodes;
import cz.cvut.palislub.annotations.Node;
import cz.cvut.palislub.annotations.NodeProperty;
import cz.cvut.palislub.annotations.Unique;
/**
* Created by lubos on 1.3.2015.
*/
@Node(name = "WebPage")
public class GraphWebPage {
@NodeProperty
@Unique
private String path;
public GraphWebPage() {
}
public GraphWebPage(String path) {
this.path = path;
}
public void setPath(String path) {
this.path = path;
}
public String getPath() {
return path;
}
@Override
public String toString() {
return "GraphWebPage{" +
"path='" + path + '\'' +
'}';
}
}
| true |
9f6b8ab9994f4691ea01d1e20ced7f9296e8a364 | Java | michbarsinai/BPBasedLanguageSemantics | /code/BPJContrib/src/bp/contrib/bfs/EvaluationLoop.java | UTF-8 | 1,988 | 2.78125 | 3 | [] | no_license | package bp.contrib.bfs;
import static bp.eventSets.EventSetConstants.none;
import bp.BProgram;
import bp.BThread;
import bp.contrib.bfs.BFuzzySystem.filteringMethod;
import bp.contrib.bfs.events.InitialOpMode;
import bp.contrib.bfs.events.OpModeEvent;
import bp.contrib.bfs.events.StopEvaluation;
import bp.eventSets.EventsOfClass;
import bp.eventSets.RequestableEventSet;
import bp.eventSets.RequestableInterface;
import bp.exceptions.BPJException;
/*
* This is a bThread that simulates a control loop.
* It runs a system step and request all resulting monitored events.
*/
public class EvaluationLoop extends BThread {
private BFuzzySystem bfs;
private filteringMethod filter;
public EvaluationLoop(BFuzzySystem bfs, filteringMethod filter) {
this.bfs = bfs;
this.filter = filter;
}
@Override
public void runBThread() throws BPJException {
interruptingEvents = new EventsOfClass(StopEvaluation.class);
BProgram bp = getBProgram();
// wait for initial state
bp.bSync(none, new EventsOfClass(InitialOpMode.class), none);
while (true) {
bfs.evaluate();
System.out
.println("~~~~~~~~~~~~~~~~~~~New System Step~~~~~~~~~~~~~~~~~~~");
RequestableEventSet monitoredEvents = bfs.getAllMonitoredEvents(filter);
/*
* The idea is to request all events simultaneously, which is
* currently not supported by BPJ. Therefore we apply the following:
* request them one after the other, relying on the fact that these
* are "unblockable" events and therefore all will be triggered.
*
* Although it is possible to pass monitoredEvents as the first
* parameter in the bSync call, but if done so, only one (the first)
* event will be requested, denying the other events the possibility
* of being requested.
*/
for (RequestableInterface e : monitoredEvents) {
bp.bSync(e, new EventsOfClass(OpModeEvent.class), none);
}
}
}
}
| true |
88159fb156185ee32b1bba5077e73df958044485 | Java | test-driven-development/legacy-code-refactor | /src/main/java/com/chikli/demo/onedevdaydetroit/legacycode/domain/IngredientItem.java | UTF-8 | 4,013 | 2.25 | 2 | [] | no_license | /**
*
*/
package com.chikli.demo.onedevdaydetroit.legacycode.domain;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.bind.annotation.XmlTransient;
import com.chikli.demo.onedevdaydetroit.legacycode.domain.type.IngredientItemSizeConversionType;
/**
* @author
*
*/
//@Indexed(index = "fl_indexes/IngredientItem")
public class IngredientItem implements Serializable {
private static final long serialVersionUID = 1L;
protected Integer m_ingredientItemId;
protected String m_name;
protected Set<Ingredient> m_ingredients = new HashSet<Ingredient>();
protected Set<UpcIngredient> m_upcIngredients = new HashSet<UpcIngredient>();
protected Set<IngredientItemPromotion> m_ingredientItemPromotions = new HashSet<IngredientItemPromotion>();
protected Map<IngredientItemSizeConversionType, IngredientItemSizeConversion> m_sizeConversionMap = new HashMap<IngredientItemSizeConversionType, IngredientItemSizeConversion>();
//audit fields
protected Date m_created;
protected Date m_lastUpdate;
// Constructors
/** default constructor */
public IngredientItem(){
}
/** minimal constructor */
public IngredientItem(String pName) {
m_name = pName;
}
/** full constructor */
public IngredientItem(String pName, Set<Ingredient> pIngredients, Set<UpcIngredient> pUpcIngredients, Set<IngredientItemPromotion> pIngredientItemPromotions) {
m_name = pName;
m_ingredients = pIngredients;
m_upcIngredients = pUpcIngredients;
m_ingredientItemPromotions = pIngredientItemPromotions;
}
// Property accessors
public Integer getIngredientItemId() {
return m_ingredientItemId;
}
public void setIngredientItemId(Integer pIngredientItemId) {
m_ingredientItemId = pIngredientItemId;
}
@XmlTransient
public Set<Ingredient> getIngredients() {
return m_ingredients;
}
public void setIngredients(Set<Ingredient> pIngredients) {
m_ingredients = pIngredients;
}
public String getName() {
return m_name;
}
public void setName(String pName) {
m_name = pName;
}
@XmlTransient
public Set<UpcIngredient> getUpcIngredients() {
return m_upcIngredients;
}
public void setUpcIngredients(Set<UpcIngredient> pUpcIngredients) {
m_upcIngredients = pUpcIngredients;
}
@XmlTransient
public Set<IngredientItemPromotion> getIngredientItemPromotions() {
return m_ingredientItemPromotions;
}
public void setIngredientItemPromotions(
Set<IngredientItemPromotion> pIngredientItemPromotion) {
m_ingredientItemPromotions = pIngredientItemPromotion;
}
public void addPromotions(Collection<Promotion> pPromotions){
if (null == pPromotions || pPromotions.isEmpty()) {
return;
}
getIngredientItemPromotions().clear();
//create a IngredientItemPromotion for each Promotion in the set
for (Promotion lPromotion : pPromotions) {
IngredientItemPromotion lIngredientItemPromotion = new IngredientItemPromotion();
lIngredientItemPromotion.setIngredientItem(this);
lIngredientItemPromotion.setPromotion(lPromotion);
lPromotion.getIngredientPromotions().add(lIngredientItemPromotion);
getIngredientItemPromotions().add(lIngredientItemPromotion);
}
}
@XmlTransient
public Map<IngredientItemSizeConversionType, IngredientItemSizeConversion> getSizeConversionMap() {
return m_sizeConversionMap;
}
public void setSizeConversionMap(
Map<IngredientItemSizeConversionType, IngredientItemSizeConversion> pSizeConversionMap) {
m_sizeConversionMap = pSizeConversionMap;
}
@XmlTransient
public Date getCreated() {
return m_created;
}
public void setCreated(Date pCreated) {
m_created = pCreated;
}
@XmlTransient
public Date getLastUpdate() {
return m_lastUpdate;
}
public void setLastUpdate(Date pLastUpdate) {
m_lastUpdate = pLastUpdate;
}
}
| true |
b49545cbc8bfa6f0e4298c496312a8600e2921f2 | Java | ronanhardiman/LLMediaPlayer | /LLMedia/src/com/lq/llmediaPlayer/AsyncTask/AddIdCursorLoader.java | UTF-8 | 1,299 | 2.359375 | 2 | [] | no_license | package com.lq.llmediaPlayer.AsyncTask;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
public class AddIdCursorLoader extends AsyncTaskLoader<Cursor>{
final ForceLoadContentObserver mObserver;
Uri mUri;
String[] mProjection;
String mSelection;
String[] mSelectionArgs;
String mSortOrder;
Cursor mCursor;
public AddIdCursorLoader(Context context) {
super(context);
mObserver = new ForceLoadContentObserver();
}
/**
* Creates a fully-specified CursorLoader. See
* {@link ContentResolver#query(Uri, String[], String, String[], String)
* ContentResolver.query()} for documentation on the meaning of the
* parameters. These will be passed as-is to that call.
*/
public AddIdCursorLoader(Context context, Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
super(context);
mObserver = new ForceLoadContentObserver();
mUri = uri;
mProjection = projection;
mSelection = selection;
mSelectionArgs = selectionArgs;
mSortOrder = sortOrder;
}
@Override
public Cursor loadInBackground() {
// TODO Auto-generated method stub
return null;
}
}
| true |
37693683b63c78f3fde148e0c375d00790d19f18 | Java | tigergithub01/sales | /src/com/sales/service/business/VipCouponLogService.java | UTF-8 | 1,471 | 2.03125 | 2 | [] | no_license | package com.sales.service.business;
import java.util.List;
import com.sales.model.business.VipCouponLog;
import com.sales.util.pager.helper.PageInfo;
import com.sales.util.pager.helper.PaginatedListHelper;
public interface VipCouponLogService {
/**
* deleteByPrimaryKey
* @param id
* @return int
*/
int deleteByPrimaryKey(Long id);
/**
* insert
* @param record
* @return int
*/
int insert(VipCouponLog record);
/**
* insertSelective
* @param record
* @return int
*/
int insertSelective(VipCouponLog record);
/**
* selectByPrimaryKey
* @param id
* @return
*/
VipCouponLog selectByPrimaryKey(Long id);
/**
* selectBySelective
* @param record
* @return
*/
VipCouponLog selectBySelective(VipCouponLog record);
/**
* updateByPrimaryKeySelective
* @param record
* @return
*/
int updateByPrimaryKeySelective(VipCouponLog record);
/**
* updateByPrimaryKey
* @param record
* @return
*/
int updateByPrimaryKey(VipCouponLog record);
/**
* @param record
* @return
*/
public List<VipCouponLog> selectList(
VipCouponLog record);
/**
* selectList
* @param record
* @return
*/
public PaginatedListHelper selectList(
VipCouponLog record,PageInfo pageInfo);
}
| true |
5f8d58445cce5410a986e6e8c033158acbcf852f | Java | plibin/regadb | /pharmadm/src/com/pharmadm/custom/rega/reporteditor/ElementDataOutputVariable.java | UTF-8 | 2,339 | 2.5 | 2 | [] | no_license | /*
* ListDataOutputVariable.java
*
* Created on December 12, 2003, 11:50 AM
*/
/*
* (C) Copyright 2000-2007 PharmaDM n.v. All rights reserved.
*
* This file is licensed under the terms of the GNU General Public License (GPL) version 2.
* See http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
*/
package com.pharmadm.custom.rega.reporteditor;
import com.pharmadm.custom.rega.queryeditor.catalog.DbObject;
import java.util.*;
/**
*
* @author kristof
*
* <p>
* This class supports xml-encoding.
* The following new properties are encoded :
* parent
* pos
* </p>
*/
public class ElementDataOutputVariable extends DataOutputVariable {
private ListDataOutputVariable parent;
private int pos;
/** Creates a new instance of ListDataOutputVariable */
public ElementDataOutputVariable(DbObject object, ListDataOutputVariable parent, int pos) {
super(object);
this.parent = parent;
this.pos = pos;
}
/* For xml-encoding purposes */
public ElementDataOutputVariable() {
}
public String getFormalName() {
return parent.getFormalName() + "." + pos;
}
public int getPos() {
return pos;
}
/* For xml-encoding purposes */
public void setPos(int pos) {
this.pos = pos;
}
public ListDataOutputVariable getParent() {
return parent;
}
/* For xml-encoding purposes */
public void setParent(ListDataOutputVariable parent) {
this.parent = parent;
}
public String getUniqueName() {
return parent.getUniqueName() + "." + pos;
}
public boolean consistsOfSingleObjectListVariable() {
return false;
}
public ValueSpecifier getSpecifier() {
// not supposed to be used : determined by parent
return null;
}
public Object getStoredValue(DataRow row) {
ArrayList parentValue = ((ArrayList)parent.getStoredValue(row));
if (parentValue == null) {
//System.err.println("Null value for " + parent + " (" + parent.getClass() + ")");
return null;
} else if (pos <= parentValue.size()) {
return parentValue.get(pos - 1); // 1-based here, parent is 0-based
} else {
return null;
}
}
}
| true |
bc5008f5963b1cc1fce20d1edd797f9930557b1c | Java | BinSlashBash/xcrumby | /src-v2/org/junit/experimental/theories/internal/ParameterizedAssertionError.java | UTF-8 | 1,490 | 2.453125 | 2 | [] | no_license | /*
* Decompiled with CFR 0_110.
*/
package org.junit.experimental.theories.internal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
public class ParameterizedAssertionError
extends RuntimeException {
private static final long serialVersionUID = 1;
public /* varargs */ ParameterizedAssertionError(Throwable throwable, String string2, Object ... arrobject) {
super(String.format("%s(%s)", string2, ParameterizedAssertionError.join(", ", arrobject)), throwable);
}
public static String join(String string2, Collection<Object> object) {
StringBuffer stringBuffer = new StringBuffer();
object = object.iterator();
while (object.hasNext()) {
stringBuffer.append(ParameterizedAssertionError.stringValueOf(object.next()));
if (!object.hasNext()) continue;
stringBuffer.append(string2);
}
return stringBuffer.toString();
}
public static /* varargs */ String join(String string2, Object ... arrobject) {
return ParameterizedAssertionError.join(string2, Arrays.asList(arrobject));
}
private static String stringValueOf(Object object) {
try {
object = String.valueOf(object);
return object;
}
catch (Throwable var0_1) {
return "[toString failed]";
}
}
public boolean equals(Object object) {
return this.toString().equals(object.toString());
}
}
| true |
550cd48b00cfa48a5447cdb9f7e606c1b627bc11 | Java | zhengwenzhan/java_design | /src/main/java/bridge/BlindingMagicWeapon.java | UTF-8 | 633 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | package bridge;
/**
* Created by zhengwenzhan on 2019-01-28
*/
public class BlindingMagicWeapon extends MagicWeapon {
public BlindingMagicWeapon(BlindingMagicWeaponImpl impl) {
super(impl);
}
@Override
public BlindingMagicWeaponImpl getImpl() {
return (BlindingMagicWeaponImpl) impl;
}
@Override
public void wield() {
getImpl().wieldImpl();
}
@Override
public void swing() {
getImpl().swingImpl();
}
@Override
public void unwield() {
getImpl().unwieldImpl();
}
public void blinding() {
getImpl().blindImpl();
}
}
| true |
96cf4cfd4669f33a302e6546578794c41cd56729 | Java | arpentnoir/nla-demo | /src/main/java/org/springframework/samples/petclinic/loan/LoanController.java | UTF-8 | 3,738 | 1.9375 | 2 | [] | no_license | /*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.loan;
import java.util.Collection;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.user.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
class LoanController {
private static final String VIEWS_LOAN_CREATE_OR_UPDATE_FORM = "loans/createOrUpdateLoanForm";
private final LoanRepository loans;
@Autowired
public LoanController(LoanRepository clinicService) {
this.loans = clinicService;
}
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
@RequestMapping(value = "/loans/new", method = RequestMethod.GET)
public String initCreationForm(User user, ModelMap model) {
Loan loan = new Loan();
user.addLoan(loan);
model.put("loan", loan);
return VIEWS_LOAN_CREATE_OR_UPDATE_FORM;
}
@RequestMapping(value = "/loans/new", method = RequestMethod.POST)
public String processCreationForm(User user, Loan loan, BindingResult result, ModelMap model) {
// if (StringUtils.hasLength(pet.getName()) && pet.isNew() && owner.getPet(pet.getName(), true) != null){
// result.rejectValue("name", "duplicate", "already exists");
// }
if (result.hasErrors()) {
model.put("loan", loan);
return VIEWS_LOAN_CREATE_OR_UPDATE_FORM;
} else {
user.addLoan(loan);
this.loans.save(loan);
return "redirect:/owners/{ownerId}";
}
}
@RequestMapping(value = "/loans/find", method = RequestMethod.GET)
public String initFindForm(Map<String, Object> model) {
model.put("loan", new Loan());
return "loans/findLoans";
}
@RequestMapping(value = "/all-loans", method = RequestMethod.GET)
public String processFindForm(Loan loan, BindingResult result, Map<String, Object> model) {
Collection<Loan> results = this.loans.findAll();
model.put("selections", results);
return "loans/loansList";
}
@RequestMapping(value = "/users/{userID}/loans", method = RequestMethod.GET)
public String processFindForm(User user, BindingResult result, Map<String, Object> model) {
// find users by last name
Collection<Loan> results = this.loans.findByUserId(user.getId());
if (results.isEmpty()) {
// no users found
result.rejectValue("lastName", "notFound", "not found");
return "loans/loansList";
} else {
// multiple users found
model.put("selections", results);
return "loans/loansList";
}
}
}
| true |
63301fd4df1e54b9d81f69f27b765f315157f404 | Java | onionhoney/codesprint | /judge/sessions/2018Individual/williamjlee@ucla.edu/PC_01.java | UTF-8 | 2,059 | 2.96875 | 3 | [] | no_license |
import java.util.*;
import java.io.*;
public class recons {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int c=0;c<t;c++){
int rooms=in.nextInt();
int edge = in.nextInt();
int create=in.nextInt();
//HashSet<Integer>[]can=new [rooms];
HashSet<Integer>[]can = new HashSet[rooms];
for(int i=0;i<rooms;i++)
can[i]=new HashSet<>();
for(int i=0;i<edge;i++){
can[in.nextInt()-1].add(in.nextInt()-1);
}
int[]groups=new int[rooms];
boolean[]v=new boolean[rooms];
int num=0;
for(int i=0;i<rooms;i++){
if(!v[i]){
dfs(i, can, v, groups, num);
num++;
}
}
HashMap<Integer, Integer>hm=new HashMap<>();
for(int i=0;i<groups.length;i++){
if(!hm.containsKey(groups[i])){
hm.put(groups[i], 1);
}else{
hm.put(groups[i], hm.get(groups[i])+1);
}
}
ArrayList<Integer>counts=new ArrayList<>();
for(Integer k: hm.keySet())
counts.add(hm.get(k));
Collections.sort(counts);
int ind=Math.max(0, counts.size()-create-1);
long get=0;
for(int i=0;i<ind;i++)
get+=(counts.get(i)*(counts.get(i)-1))/2;
long sum=0;
for(int i=ind;i<counts.size();i++)
sum+=counts.get(i);
get+=(sum*(sum-1))/2;
System.out.println(get);
}
}
public static void dfs(int room, HashSet<Integer>[]can, boolean[]v, int[]groups, int group){
if(v[room])
return;
v[room]=true;
groups[room]=group;
for(Integer next: can[room]){
if(!v[next])
dfs(next, can, v, groups, group);
}
}
} | true |
abd30759197d2f625c359d42de7a8070f3df3fa7 | Java | shirley1997/java-practice | /ubung2/insurance.java | UTF-8 | 277 | 3.203125 | 3 | [] | no_license | public class Insurance{
public static void main(String[] args){
Insurance insurance1 = new Insurance();
insurance1.insurance(85,3000);
}
static void insurance(int G,int W){
double VB = 1;
if((G>0)&&(W>0)){
VB = G + 0.5*W;
System.out.println(VB);
}
}
} | true |
d067056b7673f4464a8617b051ec760ca82bcbff | Java | BastardoONe/HitCaseShop | /caseshop/src/main/java/com/caseshop/Entity/PhoneCase.java | UTF-8 | 1,249 | 2.4375 | 2 | [] | no_license | package com.caseshop.Entity;
import javax.persistence.*;
@Entity
public class PhoneCase {
@Id
@GeneratedValue
private long phoneCaseId;
public String phoneCaseManufacturer;
public String phoneCaseModel;
public long quantity;
public long getPhoneCaseId() {
return phoneCaseId;
}
public void setPhoneCaseId(long phoneCaseId) {
this.phoneCaseId = phoneCaseId;
}
public String getPhoneCaseManufacturer() {
return phoneCaseManufacturer;
}
public void setPhoneCaseManufacturer(String phoneCaseManafacturer) {
this.phoneCaseManufacturer = phoneCaseManafacturer;
}
public String getPhoneCaseModel() {
return phoneCaseModel;
}
public void setPhoneCaseModel(String phoneCaseModel) {
this.phoneCaseModel = phoneCaseModel;
}
public long getQuantity() {
return quantity;
}
public void setQuantity(long quantity) {
this.quantity = quantity;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PHONE_ID")
private Phone phone;
public String getPhone() {
return phone.getPhoneModel();
}
public void setPhone(Phone phones) {
this.phone = phones;
}
}
| true |
429981b5318aa270186163eb20dcebc21929a708 | Java | zx20110729/BaseSSM | /src/main/java/com/zhou/demo/controller/TestDemo.java | UTF-8 | 891 | 2.140625 | 2 | [] | no_license | package com.zhou.demo.controller;
import com.zhou.demo.entity.User;
import com.zhou.demo.service.impl.UserService;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by ZhouXiang on 2017/2/9 15:28.
*/
@RunWith(SpringJUnit4ClassRunner.class)
// 告诉junit spring配置文件
@ContextConfiguration({ "classpath:spring/ApplicationContext.xml" })
public class TestDemo {
@Autowired
private UserService userService;
private static Logger LOG = Logger.getLogger(TestDemo.class);
@Test
public void test1(){
User user = userService.getUserById(4);
System.out.println(user);
LOG.info(user);
}
}
| true |
eb5582fbf3ad44ff537783db5e11605b9661eefa | Java | skarpushin/swingpm | /src/main/java/ru/skarpushin/swingpm/bindings/ModelSelInListBinding.java | UTF-8 | 2,833 | 1.789063 | 2 | [
"Apache-2.0"
] | permissive | /*******************************************************************************
* Copyright 2015-2023 Sergey Karpushin
*
* 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 ru.skarpushin.swingpm.bindings;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.google.common.base.Preconditions;
import ru.skarpushin.swingpm.modelprops.lists.ModelSelInComboBoxPropertyAccessor;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ModelSelInListBinding implements Binding, ListDataListener, ListSelectionListener {
private final ModelSelInComboBoxPropertyAccessor<?> model;
private JList list;
public ModelSelInListBinding(BindingContext bindingContext, ModelSelInComboBoxPropertyAccessor<?> nodel,
JList list) {
this.model = nodel;
this.list = list;
Preconditions.checkArgument(bindingContext != null);
Preconditions.checkArgument(nodel != null);
Preconditions.checkArgument(list != null);
Preconditions.checkArgument(list.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION);
list.setModel(nodel);
list.setSelectedValue(nodel.getSelectedItem(), true);
list.addListSelectionListener(this);
nodel.addListDataListener(this);
bindingContext.createValidationErrorsViewIfAny(model, list);
}
@Override
public boolean isBound() {
return list != null;
}
@Override
public void unbind() {
model.removeListDataListener(this);
list.removeListSelectionListener(this);
list.setModel(new DefaultListModel());
list = null;
}
@Override
public void intervalAdded(ListDataEvent e) {
list.setSelectedValue(model.getSelectedItem(), true);
}
@Override
public void intervalRemoved(ListDataEvent e) {
list.setSelectedValue(model.getSelectedItem(), true);
}
@Override
public void contentsChanged(ListDataEvent e) {
list.setSelectedValue(model.getSelectedItem(), true);
}
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() || !isBound()) {
return;
}
model.setSelectedItem(list.getSelectedValue());
}
}
| true |
e73823276f7e6a79f144891314037a51d88e6a84 | Java | jaishankarg24/Spring-Framework | /BeanAutoWiringAnnotation+Xml/src/com/abc/beans/Student.java | UTF-8 | 1,152 | 2.703125 | 3 | [] | no_license | package com.abc.beans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Student {
private String sid;
private String sname;
private String sadress;
// Injecting a course object into student object
@Autowired(required = true)
@Qualifier("advanced_java")
private Course course;
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSadress() {
return sadress;
}
public void setSadress(String sadress) {
this.sadress = sadress;
}
public void dispalyDetails() {
System.out.println("Student details are shown below");
System.out.println("Student ID is :" + sid);
System.out.println("Student Name is :" + sname);
System.out.println("Student Address is :" + sadress);
System.out.println("-------------------------------------------------------");
System.out.println("Course details are :" + course);
}
}
| true |
c97334f65122bb235cba83b36dd32dc4890ac29b | Java | saber13812002/DeepCRM | /Code Snippet Repository/Roller/Roller47.java | UTF-8 | 2,079 | 2.40625 | 2 | [] | no_license | public MailProvider() throws StartupException {
String connectionTypeString = WebloggerConfig.getProperty("mail.configurationType");
if ("properties".equals(connectionTypeString)) {
type = ConfigurationType.MAIL_PROPERTIES;
}
String jndiName = WebloggerConfig.getProperty("mail.jndi.name");
mailHostname = WebloggerConfig.getProperty("mail.hostname");
mailUsername = WebloggerConfig.getProperty("mail.username");
mailPassword = WebloggerConfig.getProperty("mail.password");
try {
String portString = WebloggerConfig.getProperty("mail.port");
if (portString != null) {
mailPort = Integer.parseInt(portString);
}
} catch (Exception e) {
LOG.warn("mail server port not a valid integer, ignoring");
}
// init and connect now so we fail early
if (type == ConfigurationType.JNDI_NAME) {
if (jndiName != null && !jndiName.startsWith("java:")) {
jndiName = "java:comp/env/" + jndiName;
}
try {
Context ctx = new InitialContext();
session = (Session) ctx.lookup(jndiName);
} catch (NamingException ex) {
throw new StartupException("ERROR looking up mail-session with JNDI name: " + jndiName);
}
} else {
Properties props = new Properties();
props.put("mail.smtp.host", mailHostname);
if (mailUsername != null && mailPassword != null) {
props.put("mail.smtp.auth", "true");
}
if (mailPort != -1) {
props.put("mail.smtp.port", ""+mailPort);
}
session = Session.getDefaultInstance(props, null);
}
try {
Transport transport = getTransport();
transport.close();
} catch (Exception e) {
throw new StartupException("ERROR connecting to mail server", e);
}
}
| true |
48ca64fc2b5e856d1dd74e8fe4c6b901374f632c | Java | suliyu/evolucionNetflix | /android/support/graphics/drawable/PathParser$PathDataNode.java | UTF-8 | 17,585 | 2.078125 | 2 | [] | no_license | //
// Decompiled by Procyon v0.5.30
//
package android.support.graphics.drawable;
import android.util.Log;
import android.graphics.Path;
public class PathParser$PathDataNode
{
float[] params;
char type;
PathParser$PathDataNode(final char type, final float[] params) {
this.type = type;
this.params = params;
}
PathParser$PathDataNode(final PathParser$PathDataNode pathParser$PathDataNode) {
this.type = pathParser$PathDataNode.type;
this.params = PathParser.copyOfRange(pathParser$PathDataNode.params, 0, pathParser$PathDataNode.params.length);
}
private static void addCommand(final Path path, final float[] array, final char c, final char c2, final float[] array2) {
float n = array[0];
float n2 = array[1];
float n3 = array[2];
float n4 = array[3];
float n5 = array[4];
float n6 = array[5];
int n7 = 0;
switch (c2) {
default: {
n7 = 2;
break;
}
case 'Z':
case 'z': {
path.close();
path.moveTo(n5, n6);
n4 = n6;
n3 = n5;
n2 = n6;
n = n5;
n7 = 2;
break;
}
case 'L':
case 'M':
case 'T':
case 'l':
case 'm':
case 't': {
n7 = 2;
break;
}
case 'H':
case 'V':
case 'h':
case 'v': {
n7 = 1;
break;
}
case 'C':
case 'c': {
n7 = 6;
break;
}
case 'Q':
case 'S':
case 'q':
case 's': {
n7 = 4;
break;
}
case 'A':
case 'a': {
n7 = 7;
break;
}
}
final int n8 = 0;
char c3 = c;
float n10 = 0.0f;
float n11 = 0.0f;
float n12 = 0.0f;
float n71;
for (int i = n8; i < array2.length; i += n7, n71 = n11, c3 = c2, n4 = n10, n6 = n12, n5 = n71) {
switch (c2) {
default: {
final float n9 = n6;
n10 = n4;
n11 = n5;
n12 = n9;
break;
}
case 'm': {
n += array2[i + 0];
n2 += array2[i + 1];
if (i > 0) {
path.rLineTo(array2[i + 0], array2[i + 1]);
final float n13 = n5;
n12 = n6;
n10 = n4;
n11 = n13;
break;
}
path.rMoveTo(array2[i + 0], array2[i + 1]);
final float n14 = n2;
final float n15 = n;
n10 = n4;
n12 = n2;
n11 = n;
n2 = n14;
n = n15;
break;
}
case 'M': {
final float n16 = array2[i + 0];
final float n17 = array2[i + 1];
if (i > 0) {
path.lineTo(array2[i + 0], array2[i + 1]);
final float n18 = n16;
final float n19 = n5;
n12 = n6;
n10 = n4;
n11 = n19;
n2 = n17;
n = n18;
break;
}
path.moveTo(array2[i + 0], array2[i + 1]);
final float n20 = n17;
final float n21 = n16;
n10 = n4;
n12 = n17;
n11 = n16;
n2 = n20;
n = n21;
break;
}
case 'l': {
path.rLineTo(array2[i + 0], array2[i + 1]);
final float n22 = array2[i + 0];
final float n23 = array2[i + 1] + n2;
n += n22;
final float n24 = n5;
n12 = n6;
n10 = n4;
n11 = n24;
n2 = n23;
break;
}
case 'L': {
path.lineTo(array2[i + 0], array2[i + 1]);
n = array2[i + 0];
n2 = array2[i + 1];
final float n25 = n5;
n12 = n6;
n10 = n4;
n11 = n25;
break;
}
case 'h': {
path.rLineTo(array2[i + 0], 0.0f);
final float n26 = n + array2[i + 0];
final float n27 = n5;
n12 = n6;
n10 = n4;
n11 = n27;
n = n26;
break;
}
case 'H': {
path.lineTo(array2[i + 0], n2);
n = array2[i + 0];
final float n28 = n5;
n12 = n6;
n10 = n4;
n11 = n28;
break;
}
case 'v': {
path.rLineTo(0.0f, array2[i + 0]);
final float n29 = array2[i + 0];
final float n30 = n5;
n2 += n29;
n12 = n6;
n10 = n4;
n11 = n30;
break;
}
case 'V': {
path.lineTo(n, array2[i + 0]);
final float n31 = array2[i + 0];
final float n32 = n5;
n12 = n6;
n10 = n4;
n11 = n32;
n2 = n31;
break;
}
case 'c': {
path.rCubicTo(array2[i + 0], array2[i + 1], array2[i + 2], array2[i + 3], array2[i + 4], array2[i + 5]);
final float n33 = array2[i + 2];
final float n34 = array2[i + 3];
final float n35 = array2[i + 4];
final float n36 = array2[i + 5];
n3 = n + n33;
final float n37 = n36 + n2;
n += n35;
n11 = n5;
final float n38 = n34 + n2;
n12 = n6;
n10 = n38;
n2 = n37;
break;
}
case 'C': {
path.cubicTo(array2[i + 0], array2[i + 1], array2[i + 2], array2[i + 3], array2[i + 4], array2[i + 5]);
n = array2[i + 4];
n2 = array2[i + 5];
n3 = array2[i + 2];
final float n39 = array2[i + 3];
n11 = n5;
n12 = n6;
n10 = n39;
break;
}
case 's': {
float n41;
float n42;
if (c3 == 'c' || c3 == 's' || c3 == 'C' || c3 == 'S') {
final float n40 = n - n3;
n41 = n2 - n4;
n42 = n40;
}
else {
n41 = 0.0f;
n42 = 0.0f;
}
path.rCubicTo(n42, n41, array2[i + 0], array2[i + 1], array2[i + 2], array2[i + 3]);
final float n43 = array2[i + 0];
final float n44 = array2[i + 1];
final float n45 = array2[i + 2];
final float n46 = array2[i + 3];
n3 = n + n43;
final float n47 = n46 + n2;
n += n45;
n11 = n5;
final float n48 = n44 + n2;
n12 = n6;
n10 = n48;
n2 = n47;
break;
}
case 'S': {
float n50;
if (c3 == 'c' || c3 == 's' || c3 == 'C' || c3 == 'S') {
final float n49 = 2.0f * n - n3;
n2 = 2.0f * n2 - n4;
n50 = n49;
}
else {
n50 = n;
}
path.cubicTo(n50, n2, array2[i + 0], array2[i + 1], array2[i + 2], array2[i + 3]);
n3 = array2[i + 0];
final float n51 = array2[i + 1];
n = array2[i + 2];
n2 = array2[i + 3];
n11 = n5;
n12 = n6;
n10 = n51;
break;
}
case 'q': {
path.rQuadTo(array2[i + 0], array2[i + 1], array2[i + 2], array2[i + 3]);
final float n52 = array2[i + 0];
final float n53 = array2[i + 1];
final float n54 = array2[i + 2];
final float n55 = array2[i + 3];
n3 = n + n52;
final float n56 = n55 + n2;
n += n54;
n11 = n5;
final float n57 = n53 + n2;
n12 = n6;
n10 = n57;
n2 = n56;
break;
}
case 'Q': {
path.quadTo(array2[i + 0], array2[i + 1], array2[i + 2], array2[i + 3]);
n3 = array2[i + 0];
final float n58 = array2[i + 1];
n = array2[i + 2];
n2 = array2[i + 3];
n11 = n5;
n12 = n6;
n10 = n58;
break;
}
case 't': {
float n59;
float n60;
if (c3 == 'q' || c3 == 't' || c3 == 'Q' || c3 == 'T') {
n59 = n - n3;
n60 = n2 - n4;
}
else {
n60 = 0.0f;
n59 = 0.0f;
}
path.rQuadTo(n59, n60, array2[i + 0], array2[i + 1]);
final float n61 = array2[i + 0];
final float n62 = array2[i + 1];
final float n63 = n + n59;
final float n64 = n62 + n2;
n += n61;
final float n65 = n5;
final float n66 = n60 + n2;
n12 = n6;
n10 = n66;
n11 = n65;
n3 = n63;
n2 = n64;
break;
}
case 'T': {
float n67 = 0.0f;
float n68 = 0.0f;
Label_1864: {
if (c3 != 'q' && c3 != 't' && c3 != 'Q') {
n67 = n2;
n68 = n;
if (c3 != 'T') {
break Label_1864;
}
}
n68 = 2.0f * n - n3;
n67 = 2.0f * n2 - n4;
}
path.quadTo(n68, n67, array2[i + 0], array2[i + 1]);
n = array2[i + 0];
n2 = array2[i + 1];
n3 = n68;
n11 = n5;
n12 = n6;
n10 = n67;
break;
}
case 'a': {
drawArc(path, n, n2, array2[i + 5] + n, array2[i + 6] + n2, array2[i + 0], array2[i + 1], array2[i + 2], array2[i + 3] != 0.0f, array2[i + 4] != 0.0f);
n += array2[i + 5];
final float n69 = array2[i + 6] + n2;
n11 = n5;
n3 = n;
n2 = n69;
n12 = n6;
n10 = n69;
break;
}
case 'A': {
drawArc(path, n, n2, array2[i + 5], array2[i + 6], array2[i + 0], array2[i + 1], array2[i + 2], array2[i + 3] != 0.0f, array2[i + 4] != 0.0f);
n = array2[i + 5];
final float n70 = array2[i + 6];
n11 = n5;
n3 = n;
n2 = n70;
n12 = n6;
n10 = n70;
break;
}
}
}
array[0] = n;
array[1] = n2;
array[2] = n3;
array[3] = n4;
array[4] = n5;
array[5] = n6;
}
private static void arcToBezier(final Path path, final double n, final double n2, final double n3, final double n4, double n5, double n6, double cos, double n7, double sin) {
final int n8 = (int)Math.ceil(Math.abs(4.0 * sin / 3.141592653589793));
final double cos2 = Math.cos(cos);
final double sin2 = Math.sin(cos);
cos = Math.cos(n7);
final double sin3 = Math.sin(n7);
final double n9 = -n3;
final double n10 = -n3;
final double n11 = sin / n8;
int i = 0;
final double n12 = sin3 * (n10 * sin2) + cos * (n4 * cos2);
final double n13 = n9 * cos2 * sin3 - n4 * sin2 * cos;
sin = n7;
n7 = n6;
cos = n5;
n6 = n13;
n5 = n12;
while (i < n8) {
final double n14 = sin + n11;
final double sin4 = Math.sin(n14);
final double cos3 = Math.cos(n14);
final double n15 = n3 * cos2 * cos3 + n - n4 * sin2 * sin4;
final double n16 = n4 * cos2 * sin4 + (n3 * sin2 * cos3 + n2);
final double n17 = -n3 * cos2 * sin4 - n4 * sin2 * cos3;
final double n18 = cos3 * (n4 * cos2) + sin4 * (-n3 * sin2);
final double tan = Math.tan((n14 - sin) / 2.0);
sin = Math.sin(n14 - sin);
sin = (Math.sqrt(tan * (3.0 * tan) + 4.0) - 1.0) * sin / 3.0;
path.rCubicTo((float)(n6 * sin + cos) - (float)cos, (float)(n7 + n5 * sin) - (float)n7, (float)(n15 - sin * n17) - (float)cos, (float)(n16 - sin * n18) - (float)n7, (float)n15 - (float)cos, (float)n16 - (float)n7);
++i;
n6 = n17;
sin = n14;
n7 = n16;
cos = n15;
n5 = n18;
}
}
private static void drawArc(final Path path, final float n, final float n2, final float n3, final float n4, final float n5, final float n6, final float n7, final boolean b, final boolean b2) {
final double radians = Math.toRadians(n7);
final double cos = Math.cos(radians);
final double sin = Math.sin(radians);
final double n8 = (n * cos + n2 * sin) / n5;
final double n9 = (-n * sin + n2 * cos) / n6;
final double n10 = (n3 * cos + n4 * sin) / n5;
final double n11 = (-n3 * sin + n4 * cos) / n6;
final double n12 = n8 - n10;
final double n13 = n9 - n11;
final double n14 = (n8 + n10) / 2.0;
final double n15 = (n9 + n11) / 2.0;
final double n16 = n12 * n12 + n13 * n13;
if (n16 == 0.0) {
Log.w("PathParser", " Points are coincident");
return;
}
final double n17 = 1.0 / n16 - 0.25;
if (n17 < 0.0) {
Log.w("PathParser", "Points are too far apart " + n16);
final float n18 = (float)(Math.sqrt(n16) / 1.99999);
drawArc(path, n, n2, n3, n4, n5 * n18, n6 * n18, n7, b, b2);
return;
}
final double sqrt = Math.sqrt(n17);
final double n19 = n12 * sqrt;
final double n20 = n13 * sqrt;
double n21;
double n22;
if (b == b2) {
n21 = n14 - n20;
n22 = n19 + n15;
}
else {
n21 = n20 + n14;
n22 = n15 - n19;
}
final double atan2 = Math.atan2(n9 - n22, n8 - n21);
final double n23 = Math.atan2(n11 - n22, n10 - n21) - atan2;
final boolean b3 = n23 >= 0.0;
double n24 = n23;
if (b2 != b3) {
if (n23 > 0.0) {
n24 = n23 - 6.283185307179586;
}
else {
n24 = n23 + 6.283185307179586;
}
}
final double n25 = n5 * n21;
final double n26 = n22 * n6;
arcToBezier(path, n25 * cos - n26 * sin, n25 * sin + n26 * cos, n5, n6, n, n2, radians, atan2, n24);
}
public static void nodesToPath(final PathParser$PathDataNode[] array, final Path path) {
final float[] array2 = new float[6];
char type = 'm';
for (int i = 0; i < array.length; ++i) {
addCommand(path, array2, type, array[i].type, array[i].params);
type = array[i].type;
}
}
}
| true |
90246eb4f941a60f1f02105e35b9090d7990d87c | Java | pedrollcopatti/homeAloneMarket | /src/visao/NovoPedidoView.java | UTF-8 | 15,061 | 2.109375 | 2 | [] | no_license | /*
* 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 visao;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import modelo.Boleto;
import modelo.Compra;
import modelo.Endereco;
import modelo.MetodoPagamento;
import modelo.Telefone;
import modelo.Produto;
import modelo.Email;
/**
*
* @author pedro
*/
public class NovoPedidoView extends javax.swing.JFrame {
private HomeAloneView homeAloneView;
private ArrayList<Produto> produtosCompra;
/**
* Creates new form NovoPedidoView
*/
public NovoPedidoView(HomeAloneView homeAloneView) {
this.homeAloneView = homeAloneView;
initComponents();
homeAloneView.getTelefones().forEach(telefone -> {cbTelefone.addItem(telefone);});
homeAloneView.getEnderecos().forEach(endereco -> {cbEndereco.addItem(endereco);});
homeAloneView.getCartoes().forEach(cartao -> {cbPagamento.addItem(cartao);});
homeAloneView.getEmails().forEach(email -> {cbEmail.addItem(email);});
Boleto boleto = new Boleto("file.pdf", "", "", "");
cbPagamento.addItem(boleto);
atualizaComboProdutos();
homeAloneView.setVisible(false);
this.produtosCompra = new ArrayList<Produto>();
}
/**
* 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() {
jLabel7 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
tfDataPrevisao = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
cbProduto = new javax.swing.JComboBox<>();
jLabel4 = new javax.swing.JLabel();
cbPagamento = new javax.swing.JComboBox<>();
jScrollPane2 = new javax.swing.JScrollPane();
taProdutosLista = new javax.swing.JTextArea();
jlVoltar = new javax.swing.JLabel();
btLimparProduto = new javax.swing.JButton();
jlAdicionaProduto = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
cbTelefone = new javax.swing.JComboBox<>();
btSalvar = new javax.swing.JButton();
btNovoProduto = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
cbEndereco = new javax.swing.JComboBox<>();
cbEmail = new javax.swing.JComboBox<>();
jLabel9 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel7.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("Novo Pedido");
getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 20, -1, 40));
jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Data da Previsão:");
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 150, -1, 20));
tfDataPrevisao.setBackground(new java.awt.Color(255, 255, 255));
tfDataPrevisao.setForeground(new java.awt.Color(0, 0, 0));
tfDataPrevisao.setHorizontalAlignment(javax.swing.JTextField.CENTER);
tfDataPrevisao.setText("dd/mm/yyyy");
tfDataPrevisao.setToolTipText("");
tfDataPrevisao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tfDataPrevisaoActionPerformed(evt);
}
});
getContentPane().add(tfDataPrevisao, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 150, 90, -1));
jLabel8.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("Lista de produtos:");
getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 250, -1, -1));
jLabel3.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Email:");
getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 60, -1, 40));
jLabel6.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("Selecione os Produtos");
getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 190, -1, -1));
cbProduto.setBackground(new java.awt.Color(255, 255, 255));
cbProduto.setForeground(new java.awt.Color(0, 0, 0));
cbProduto.setToolTipText("");
getContentPane().add(cbProduto, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 210, 460, 30));
jLabel4.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Método Pagamento:");
getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 110, -1, -1));
cbPagamento.setBackground(new java.awt.Color(255, 255, 255));
cbPagamento.setForeground(new java.awt.Color(0, 0, 0));
cbPagamento.setToolTipText("");
getContentPane().add(cbPagamento, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 110, 120, -1));
taProdutosLista.setBackground(new java.awt.Color(255, 255, 255));
taProdutosLista.setColumns(20);
taProdutosLista.setForeground(new java.awt.Color(0, 0, 0));
taProdutosLista.setRows(5);
taProdutosLista.setToolTipText("");
jScrollPane2.setViewportView(taProdutosLista);
getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 280, 340, 150));
jlVoltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/voltar.png"))); // NOI18N
jlVoltar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jlVoltarMouseClicked(evt);
}
});
getContentPane().add(jlVoltar, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 20, -1, 40));
btLimparProduto.setBackground(new java.awt.Color(95, 46, 234));
btLimparProduto.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
btLimparProduto.setForeground(new java.awt.Color(255, 255, 255));
btLimparProduto.setText("Limpar Lista");
btLimparProduto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btLimparProdutoActionPerformed(evt);
}
});
getContentPane().add(btLimparProduto, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 330, 150, 30));
jlAdicionaProduto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/add.png"))); // NOI18N
jlAdicionaProduto.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jlAdicionaProdutoMouseClicked(evt);
}
});
getContentPane().add(jlAdicionaProduto, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 210, -1, -1));
jLabel10.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("Telefone:");
getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 110, -1, -1));
cbTelefone.setBackground(new java.awt.Color(255, 255, 255));
cbTelefone.setForeground(new java.awt.Color(0, 0, 0));
cbTelefone.setToolTipText("");
getContentPane().add(cbTelefone, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 110, 130, -1));
btSalvar.setBackground(new java.awt.Color(95, 46, 234));
btSalvar.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
btSalvar.setForeground(new java.awt.Color(255, 255, 255));
btSalvar.setText("Concluir");
btSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btSalvarActionPerformed(evt);
}
});
getContentPane().add(btSalvar, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 450, 510, 40));
btNovoProduto.setBackground(new java.awt.Color(95, 46, 234));
btNovoProduto.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
btNovoProduto.setForeground(new java.awt.Color(255, 255, 255));
btNovoProduto.setText("Novo Produto");
btNovoProduto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btNovoProdutoActionPerformed(evt);
}
});
getContentPane().add(btNovoProduto, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 280, 150, 30));
jLabel5.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Endereço:");
getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 70, -1, -1));
cbEndereco.setBackground(new java.awt.Color(255, 255, 255));
cbEndereco.setForeground(new java.awt.Color(0, 0, 0));
cbEndereco.setToolTipText("");
getContentPane().add(cbEndereco, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 70, 130, -1));
cbEmail.setBackground(new java.awt.Color(255, 255, 255));
cbEmail.setForeground(new java.awt.Color(0, 0, 0));
cbEmail.setToolTipText("");
getContentPane().add(cbEmail, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 70, 120, -1));
jLabel9.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/background.png"))); // NOI18N
getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 600, 510));
pack();
}// </editor-fold>//GEN-END:initComponents
private void tfDataPrevisaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfDataPrevisaoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_tfDataPrevisaoActionPerformed
private void jlVoltarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jlVoltarMouseClicked
this.dispose();
this.homeAloneView.setVisible(true);
}//GEN-LAST:event_jlVoltarMouseClicked
private void btLimparProdutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLimparProdutoActionPerformed
taProdutosLista.setText("");
this.produtosCompra.clear();
}//GEN-LAST:event_btLimparProdutoActionPerformed
private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
ArrayList<Compra> compras = homeAloneView.getCompras();
String newTelefone = ((cbTelefone.getSelectedItem() == null) ? "" : cbTelefone.getSelectedItem().toString()),
newEndereco = ((cbEndereco.getSelectedItem() == null) ? "" : cbEndereco.getSelectedItem().toString()),
newEmail = ((cbEmail.getSelectedItem() == null) ? "" : cbEmail.getSelectedItem().toString()),
newPagamento = ((cbPagamento.getSelectedItem() == null) ? "" : cbPagamento.getSelectedItem().toString());
Compra compra = new Compra(tfDataPrevisao.getText(),
newTelefone,
newEndereco,
newEmail,
newPagamento);
compra.adicionaProduto(this.produtosCompra);
compras.add(compra);
this.setVisible(false);
homeAloneView.setVisible(true);
}//GEN-LAST:event_btSalvarActionPerformed
private void btNovoProdutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoProdutoActionPerformed
CadastrarProdutoView cadastrarProdutoView = new CadastrarProdutoView(this, this.homeAloneView);
cadastrarProdutoView.setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_btNovoProdutoActionPerformed
private void jlAdicionaProdutoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jlAdicionaProdutoMouseClicked
Produto produto = (Produto) cbProduto.getSelectedItem();
if (produto == null){
JOptionPane.showMessageDialog(null, "Nenhum produto selecionado!");
} else {
String listaProduto = taProdutosLista.getText();
listaProduto = listaProduto + produto.imprimeProduto() + System.lineSeparator();
taProdutosLista.setText(listaProduto);
this.produtosCompra.add(produto);
}
}//GEN-LAST:event_jlAdicionaProdutoMouseClicked
/**
* @param args the command line arguments
*/
public void atualizaComboProdutos(){
cbProduto.removeAllItems();
homeAloneView.getProdutos().forEach(produto -> cbProduto.addItem(produto));
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btLimparProduto;
private javax.swing.JButton btNovoProduto;
private javax.swing.JButton btSalvar;
private javax.swing.JComboBox<Email> cbEmail;
private javax.swing.JComboBox<Endereco> cbEndereco;
private javax.swing.JComboBox<MetodoPagamento> cbPagamento;
private javax.swing.JComboBox<Produto> cbProduto;
private javax.swing.JComboBox<Telefone> cbTelefone;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JLabel jlAdicionaProduto;
private javax.swing.JLabel jlVoltar;
private javax.swing.JTextArea taProdutosLista;
private javax.swing.JTextField tfDataPrevisao;
// End of variables declaration//GEN-END:variables
}
| true |
91f25805a8c5229258f4a5c1b92e4a4ffaf76086 | Java | j388923r/witrackurop | /WiTrack/app/src/main/java/util/PersonPath.java | UTF-8 | 1,707 | 2.890625 | 3 | [] | no_license | package util;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import java.util.ArrayList;
import java.util.List;
/**
* Created by j388923r on 9/30/2015.
*/
public class PersonPath {
Path path;
Room currentRoom;
public int color;
List<Point> convexHull;
public PersonPath() {
this.path = new Path();
color = Color.BLUE;
convexHull = new ArrayList<Point>();
}
public PersonPath(int color) {
this.path = new Path();
this.color = color;
convexHull = new ArrayList<Point>();
}
public PersonPath(int x, int y) {
this.path = new Path();
this.path.moveTo(x, y);
color = Color.BLUE;
convexHull = new ArrayList<Point>();
}
public PersonPath(int x, int y, int color) {
this.path = new Path();
this.path.moveTo(x, y);
this.color = color;
convexHull = new ArrayList<Point>();
}
public void addPoint(int x, int y) {
if (this.path.isEmpty())
path.moveTo(x, y);
else
path.lineTo(x, y);
if(convexHull.size() < 3) {
convexHull.add(new Point(x, y));
} else {
Point pPoint = convexHull.get(convexHull.size() - 1);
Point ppPoint = convexHull.get(convexHull.size() - 2);
}
}
public Path getPath() {
return path;
}
public RectF getBounds() {
RectF rect = new RectF();
path.computeBounds(rect, true);
return rect;
}
public List<Point> getConvexHull() {
return convexHull;
}
}
| true |
ba1b2b22c2fbe9154c465964b80217408ffdae46 | Java | princek628/welcome | /app/src/main/java/g4eis/ontern/g4project/Accounts.java | UTF-8 | 5,805 | 1.90625 | 2 | [] | no_license | package g4eis.ontern.g4project;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.famoussoft.libs.JSON.JSONArray;
import com.famoussoft.libs.JSON.JSONException;
import com.famoussoft.libs.JSON.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Accounts extends AppCompatActivity{
protected String qry="";
public int id;
JSONArray message=null;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs";
JSONArray jarray=new JSONArray();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accounts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//editSearch = (SearchView) findViewById(R.id.search);
//editSearch.setOnQueryTextListener(this);
//Toast.makeText(Accounts.this, oauth2, Toast.LENGTH_LONG).show();
downloadData();
loadList();
}
private void loadList() {
// TODO Auto-generated method stub
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.accounts_form);
mainLayout.removeAllViews();
//int total=Integer.parseInt(data.getString("total").toString());
//this.total=total;
message=jarray;
for (int i=0; i<jarray.length(); i++) {
JSONObject jobj=new JSONObject(jarray.getJSONObject(i).toString());
String name = jobj.getString("name").toString();
id = jobj.getInt("id");
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.VERTICAL);
ll.setPadding(10, 10, 10, 10);
final LinearLayout sll = new LinearLayout(this);
sll.setId(id);
sll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
sll.setPadding(15, 15, 5, 15);
sll.setOrientation(LinearLayout.VERTICAL);
//sll.setBackgroundColor(Color.WHITE);
TextView tvTitle = new TextView(this);
tvTitle.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tvTitle.setText(Html.fromHtml("<big><b><h3><i>"+"</i></b>"+""+name+"</h3></big>"));
tvTitle.setTextColor(Color.BLACK);
tvTitle.setClickable(true);
tvTitle.setGravity(Gravity.CENTER);
tvTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Toast.makeText(Accounts.this,"Clicked "+sll.getId(),Toast.LENGTH_LONG).show();
accountDetails(sll.getId());
}
});
sll.addView(tvTitle);
ll.addView(sll);
mainLayout.addView(ll);
}
}
private void downloadData()
{
JSONObject data = new JSONObject();
try {
data.put("id", "1");
data.put("name", "Johnson and Johnson");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject data1 = new JSONObject();
try {
data1.put("id", "2");
data1.put("name", "Motorola");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject data2 = new JSONObject();
try {
data2.put("id", "3");
data2.put("name", "JP Morgan Chase & Co");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject data3 = new JSONObject();
try {
data3.put("id", "4");
data3.put("name", "J.C. Penney Company");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject data4 = new JSONObject();
try {
data4.put("id", "5");
data4.put("name", "John Bean Technologies Corporation");
} catch (JSONException e) {
e.printStackTrace();
}
jarray.put(data);
jarray.put(data1);
jarray.put(data2);
jarray.put(data3);
jarray.put(data4);
}
private void accountDetails(final int id){
Intent chatIntent=new Intent(Accounts.this,AccDetails.class);
String id1=Integer.toString(id);
chatIntent.putExtra("accid",id1);
startActivity(chatIntent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true |
441f7f088e52f1c34eafa439ca9145e0b465b051 | Java | adligo/i_util_tests.adligo.org | /src/org/adligo/i/util_tests/shared/mocks/MockTextFormatterFactory.java | UTF-8 | 677 | 1.921875 | 2 | [
"Apache-2.0"
] | permissive | package org.adligo.i.util_tests.shared.mocks;
import org.adligo.i.util.shared.I_Factory;
import org.adligo.i.util.shared.TextFormatter;
import org.adligo.i.util_tests.shared.MockTextFormatter;
public class MockTextFormatterFactory extends TextFormatter implements I_Factory {
public MockTextFormatterFactory(boolean initNull) throws Exception {
TextFormatter.setDelegate(null);
}
public MockTextFormatterFactory() throws Exception {
TextFormatter.setDelegate(new MockTextFormatter());
}
public static void uninit() {
TextFormatter.delegate = null;
}
@Override
public Object createNew(Object p) {
// TODO Auto-generated method stub
return null;
}
}
| true |
0bff5a2ac5bd177f58ddc170421fe45497c4dc04 | Java | xuejianjun0321/Test | /src/main/java/com/手撕算法/牛客网/字符串/公共子串计算.java | UTF-8 | 1,543 | 4.34375 | 4 | [] | no_license | package com.手撕算法.牛客网.字符串;
import java.util.Scanner;
/**
* 描述
* 给定两个只包含小写字母的字符串,计算两个字符串的最大公共子串的长度。
*
* 注:子串的定义指一个字符串删掉其部分前缀和后缀(也可以不删)后形成的字符串。
* 数据范围:字符串长度:1\le s\le 150\1≤s≤150
* 进阶:时间复杂度:O(n^3)\O(n
* 3
* ) ,空间复杂度:O(n)\O(n)
* 输入描述:
* 输入两个只包含小写字母的字符串
*
* 输出描述:
* 输出一个整数,代表最大公共子串的长度
*/
public class 公共子串计算 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ss1 = in.nextLine();
String ss2 = in.nextLine();
String s1 = ss1.length()<ss2.length() ? ss1:ss2; // 短的字符串
String s2 = ss1.length()<ss2.length() ? ss2:ss1; // 长的字符串
int n = 0;
for(int i=0;i<s1.length();i++){ // 头指针从第一位开始递增
for(int j=s1.length();j>i;j--){ // 尾指针从最后一位开始缩减
if(s2.contains(s1.substring(i,j))){ // 第一次发现合集的长度一定是最大的
n = j-i>n ? j-i:n; // 取每一次比较的最大值
continue; // 已经是最大的,无需再进行后续的操作
}
}
}
System.out.println(n);
}
} | true |
fa004ae601bcacfff60497d89745cca01692df64 | Java | Algure/LeetCode-Ex | /MainPack/MergeSort.java | UTF-8 | 1,050 | 3.359375 | 3 | [] | no_license | class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int dex=m+n-1;
int d1=m-1;
int d2=n-1;
int ref=0;
int[] res=new int[m+n];
while(dex>=0){
if((d1>=0&& d2>=0&& nums1[d1]>nums2[d2])||d2<0){
nums1[dex]=nums1[d1];
d1--;
}else {
// System.out.println(String.format("dex %d d2 %d d1 %d",dex,d2,d1));
nums1[dex]=nums2[d2];
d2--;
}
dex--;
}
}
}
/*Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Constraints:
-10^9 <= nums1[i], nums2[i] <= 10^9
nums1.length == m + n
nums2.length == n*/
| true |
6c8dcb058131ce0735a070b95b70a76593e04e42 | Java | NTRsolutions/KippinProduction | /app/src/main/java/com/kippinretail/kippingallerypreview/KippinCloudGalleryActivity.java | UTF-8 | 6,452 | 1.734375 | 2 | [] | no_license | package com.kippinretail.kippingallerypreview;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.kippinretail.Adapter.AdapterCloudGalleryImages;
import com.kippinretail.ApplicationuUlity.CommonUtility;
import com.kippinretail.CommonDialog.MessageDialog;
import com.kippinretail.Modal.kippinggallery.KippinCloudgallery;
import com.kippinretail.NonKippinGiftCardListActivity;
import com.kippinretail.R;
import com.kippinretail.SuperActivity;
import com.kippinretail.UserDashBoardActivity;
import com.kippinretail.loadingindicator.LoadingBox;
import com.kippinretail.retrofit.RestClient;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* Created by agnihotri on 07/11/17.
*/
public class KippinCloudGalleryActivity extends SuperActivity {
GridView gridView;
TextView tvTopbarTitle;
EditText txtSearch;
AdapterCloudGalleryImages adapterCloudImages;
List<KippinCloudgallery> kippinCloudgalleries;
ArrayList<KippinCloudgallery> cloudgalleries;
RelativeLayout lalayout_ivBack, layout_ivHome;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_cloud_images);
initialiseUI();
cloudgalleries=new ArrayList<>();
cloudgalleries.clear();
NonKippinGiftCardListActivity.kippinGallery=false;
}
@Override
protected void onResume() {
super.onResume();
if(NonKippinGiftCardListActivity.kippinGallery){
finish();
overridePendingTransition(R.anim.animation_from_left, R.anim.animation_to_right);
}
}
public void initialiseUI() {
gridView = (GridView) findViewById(R.id.gvImages);
tvTopbarTitle = (TextView) findViewById(R.id.tvTopbarTitle);
txtSearch = (EditText) findViewById(R.id.txtSearch);
lalayout_ivBack = (RelativeLayout) findViewById(R.id.lalayout_ivBack);
layout_ivHome = (RelativeLayout) findViewById(R.id.layout_ivHome);
// Capture Text in EditText
txtSearch.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = txtSearch.getText().toString().toLowerCase(Locale.getDefault());
filter(text);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
lalayout_ivBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
overridePendingTransition(R.anim.animation_from_left, R.anim.animation_to_right);
}
});
layout_ivHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CommonUtility.moveToTarget(KippinCloudGalleryActivity.this, UserDashBoardActivity.class);
// reSetToNonKippinList();
}
});
fetchListOfKippinGallery();
}
private void fetchListOfKippinGallery() {
LoadingBox.showLoadingDialog(KippinCloudGalleryActivity.this, "Loading...");
RestClient.getApiServiceForPojo().cloudgalleryImages(new Callback<JsonElement>() {
@Override
public void success(JsonElement jsonElement, Response response) {
LoadingBox.dismissLoadingDialog();
Log.e("JsonElement:", "" + jsonElement);
Type type = new TypeToken<List<KippinCloudgallery>>() {
}.getType();
kippinCloudgalleries = new Gson().fromJson(jsonElement.toString(), type);
if (kippinCloudgalleries.size() == 0) {
gridView.setVisibility(View.GONE);
} else {
cloudgalleries.addAll(kippinCloudgalleries);
adapterCloudImages = new AdapterCloudGalleryImages(KippinCloudGalleryActivity.this, kippinCloudgalleries);
gridView.setAdapter(adapterCloudImages);
gridView.setVisibility(View.VISIBLE);
adapterCloudImages.notifyDataSetChanged();
}
}
@Override
public void failure(RetrofitError error) {
Log.e(error.getUrl(), error.getMessage());
LoadingBox.dismissLoadingDialog();
MessageDialog.showDialog(KippinCloudGalleryActivity.this, CommonUtility.TIME_OUT_MESSAGE, false);
}
});
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
Log.e("charText:",""+charText);
kippinCloudgalleries.clear();
if (charText.length() == 0) {
kippinCloudgalleries.addAll(cloudgalleries);
}
else
{
for (KippinCloudgallery wp : cloudgalleries)
{
Log.e("WP:::",""+wp.getTemplateName());
if (wp.getTemplateName().toLowerCase(Locale.getDefault()).contains(charText))
{
kippinCloudgalleries.add(wp);
}
}
}
Log.e("cloudImages:",""+kippinCloudgalleries.size());
adapterCloudImages = new AdapterCloudGalleryImages(KippinCloudGalleryActivity.this, kippinCloudgalleries);
gridView.setAdapter(adapterCloudImages);
gridView.setVisibility(View.VISIBLE);
adapterCloudImages.notifyDataSetChanged();
}
}
| true |
bb994116ea903f9e34cf5a14348b19fc6c31f533 | Java | dragibus-4if/dragibus-devoo | /OptiFret/test/test/RegularGraphTest.java | UTF-8 | 4,122 | 2.703125 | 3 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package test;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import model.Client;
import model.Delivery;
import model.RoadNetwork;
import model.RoadNode;
import model.RoadSection;
import model.TimeSlot;
import tsp.RegularGraph;
public class RegularGraphTest extends TestCase {
public void testLoadRoadFromNetwork() {
// Création des infos nécessaires à un RegularGraph
int nbVertices = 100000;
int max = 1000000;
int min = 0;
int[][] cost = null;
ArrayList<ArrayList<Integer>> succ = new ArrayList<>();
Map<Integer, RoadNode> index2Node = new TreeMap<>();
// On crée un RegularGraph "à la main" (HandMade)
RegularGraph graphHM = new RegularGraph(nbVertices, max, min, cost, succ,
index2Node, new ArrayList<Delivery>());
// Test du RegularGraph généré à partir d'un RoadNetwork nul
try {
RegularGraph.loadFromRoadNetwork(null, null);
fail("Génération d'un RegularGraph à partir d'un RoadNetwork nul");
} catch (NullPointerException e) {
}
// Test du RegularGraph créé avec un root nul (RoadNetwork)
RoadNetwork netNR = new RoadNetwork();
RegularGraph graphZero = new RegularGraph(0, 0, 0, new int[0][0],
new ArrayList<ArrayList<Integer>>(),
new TreeMap<Integer, RoadNode>(),
new ArrayList<Delivery>());
RegularGraph graphGZero = RegularGraph.loadFromRoadNetwork(netNR, new ArrayList<Delivery>());
assertEquals(graphZero.getNbVertices(), graphGZero.getNbVertices());
assertEquals(graphZero.getMaxArcCost(), graphGZero.getMaxArcCost());
assertEquals(graphZero.getMinArcCost(), graphGZero.getMinArcCost());
assertEquals(graphZero.getCost().length, graphGZero.getCost().length);
// Test de deux nodes pointant l'un vers l'autre : cas de base
RoadNetwork netCB = new RoadNetwork();
RoadNode node1 = new RoadNode(0);
RoadNode node2 = new RoadNode(1);
node1.addNeighbor(new RoadSection(node1, node2, 1, 88));
node2.addNeighbor(new RoadSection(node2, node1, 1, 14));
netCB.setRoot(node1);
List<Delivery> obj = new ArrayList<>();
Date date = new Date();
obj.add(new Delivery(new Long(0), new Long(0), new TimeSlot(date, new Long(0)), new Client()));
obj.add(new Delivery(new Long(1), new Long(1), new TimeSlot(date, new Long(0)), new Client()));
// Création du graph "à la main" de ce cas
int[][] costCB = new int[2][2];
costCB[0][0] = 0;
costCB[0][1] = 88;
costCB[1][0] = 14;
costCB[1][1] = 0;
ArrayList<ArrayList<Integer>> succCB
= new ArrayList<>();
ArrayList<Integer> e1 = new ArrayList<>();
e1.add(1);
ArrayList<Integer> e2 = new ArrayList<>();
e2.add(0);
succCB.add(e1);
succCB.add(e2);
Map<Integer, RoadNode> treeCB = new TreeMap<>();
treeCB.put(0, node1);
treeCB.put(1, node2);
RegularGraph graphCB = new RegularGraph(2, 88, 14, costCB, succCB,
treeCB, obj);
RegularGraph graphGCB = RegularGraph.loadFromRoadNetwork(netCB, obj);
assertEquals(graphCB.getNbVertices(), graphGCB.getNbVertices());
assertEquals(graphCB.getMaxArcCost(), graphGCB.getMaxArcCost());
assertEquals(graphCB.getCost()[0][0], graphGCB.getCost()[0][0]);
assertEquals(graphCB.getCost()[0][1], graphGCB.getCost()[0][1]);
assertEquals(graphCB.getCost()[1][0], graphGCB.getCost()[1][0]);
assertEquals(graphCB.getCost()[1][1], graphGCB.getCost()[1][1]);
for(int i = 0 ; i < 2 ; i++)
for(int j = 0 ; j < graphCB.getSucc(j).length ; j++)
assertEquals(graphCB.getSucc(i)[j], graphGCB.getSucc(i)[j]);
}
}
| true |
40ec27c51d359dfb6f3d9834ee3a1566bec647f9 | Java | ankitadey/SeleniumProjects | /FordAssured/src/Data/ValuationConstraints.java | UTF-8 | 212 | 1.796875 | 2 | [] | no_license | package Data;
public class ValuationConstraints {
public static final String Errors[]= {"Please select make year","Please select make","Please select model","Please select variant","Please select city"};
}
| true |
4b858c1282da4a717f8239a74520a09e32d779ae | Java | rohitkr0807/CodingBlock | /Class/ArraysDemo.java | UTF-8 | 220 | 2.25 | 2 | [] | no_license | package Class;
public class ArraysDemo {
public static void main(String[] args) {
}
public static void swap(int arr[], int other[]){
int temp[]= arr;
arr=other;
other=temp;
}
}
| true |
fd2de1405c53babc43c9f230a1624f64ee6d40ad | Java | syrajgara/algos | /algos/src/main/java/com/shabs/datastructures/graph/MSTPrims.java | UTF-8 | 2,549 | 3.640625 | 4 | [] | no_license | package com.shabs.datastructures.graph;
import java.util.Comparator;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.PriorityQueue;
/**
* MST - connect all nodes in a graph, to form a tree with minimum edge weight
* <p>
* MSTPrims - Greedy
* - grow single tree
* - pick lowest weight edge from already seen edges (priority queue)
*
* https://stackoverflow.com/questions/14144279/difference-between-prims-and-dijkstras-algorithms
*
* <p>
* - start from one node (source node)
* - pick edge connected to it, but lowest weight
* - now pick edge connected to either on of these nodes, pick lowest weight
* - continue, till all nodes covered
*/
public class MSTPrims {
private int findMinWeight(GraphNode<Integer> rootNode) {
PriorityQueue<GraphEdge<Integer>> edgePQ =
new PriorityQueue<>(Comparator.comparingInt(o -> o.weight));
checkAndAddToPQ(rootNode, edgePQ);
int minWeight = 0;
while (!edgePQ.isEmpty()) {
GraphEdge<Integer> currentEdge = edgePQ.remove();
if (currentEdge.fromNode.visited && currentEdge.toNode.visited) {
continue; // we dont need this edge
}
// we are going to use this edge
currentEdge.print();
minWeight += currentEdge.weight;
checkAndAddToPQ(currentEdge.fromNode, edgePQ);
checkAndAddToPQ(currentEdge.toNode, edgePQ);
}
return minWeight;
}
private void checkAndAddToPQ(GraphNode<Integer> node, PriorityQueue<GraphEdge<Integer>> edgePQ) {
if (!node.visited) {
node.visited = true;
for (GraphEdge<Integer> ge : node.edges) {
edgePQ.add(ge);
}
}
}
@Test
public void test() {
GraphNode<Integer> gn1 = new GraphNode(1);
GraphNode<Integer> gn2 = new GraphNode(2);
GraphNode<Integer> gn3 = new GraphNode(3);
GraphNode<Integer> gn4 = new GraphNode(4);
GraphNode<Integer> gn5 = new GraphNode(5);
GraphNode<Integer> gn6 = new GraphNode(6);
GraphNode<Integer> gn7 = new GraphNode(7);
GraphNode<Integer> gn8 = new GraphNode(8);
GraphNode<Integer> gn9 = new GraphNode(9);
gn1.addNode(gn2, 4);
gn1.addNode(gn3, 8);
gn2.addNode(gn4, 8);
gn3.addNode(gn5, 7);
gn3.addNode(gn6, 1);
gn4.addNode(gn5, 2);
gn4.addNode(gn7, 7);
gn4.addNode(gn8, 4);
gn5.addNode(gn6, 6);
gn6.addNode(gn8, 2);
gn7.addNode(gn8, 14);
gn7.addNode(gn9, 9);
gn8.addNode(gn9, 10);
int expected = 37;
int actual = findMinWeight(gn1);
Assert.assertEquals(actual, expected);
}
} | true |
ea0cc1d2d2f72300b0a952205ddc962e3900f901 | Java | markcditzel/java_team_project | /javablog/src/main/java/models/Article.java | UTF-8 | 3,282 | 2.6875 | 3 | [] | no_license | package models;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "articles")
public class Article {
private int id;
private String title;
private String imageLink;
private String textContent;
private Author author;
private List<Section> sections;
private Date lastUpdated;
private int numberOfViews;
public Article(String title, String textContent, Author author) {
this.title = title;
this.textContent = textContent;
this.author = author;
this.sections = new ArrayList<>();
this.numberOfViews = 0;
this.imageLink = "";
}
public Article() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "image_link")
public String getImageLink() {
return imageLink;
}
public void setImageLink(String imageLink) {
this.imageLink = imageLink;
}
@Type(type = "text")
@Column(name = "text_content")
public String getTextContent() {
return textContent;
}
public void setTextContent(String textContent) {
this.textContent = textContent;
}
@ManyToOne
@JoinColumn( name = "author_id", nullable = false)
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@ManyToMany( fetch = FetchType.EAGER)
@JoinTable(
name = "articles_sections",
joinColumns = { @JoinColumn(name = "article_id", updatable = false)},
inverseJoinColumns = { @JoinColumn(name = "section_id", updatable = false) }
)
public List<Section> getSections() {
return sections;
}
public void setSections(List<Section> sections) {
this.sections = sections;
}
public void addSectionToArticle(Section section){
this.sections.add(section);
}
@Temporal(TemporalType.DATE)
@Column(name = "last_updated")
public Date getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public void updateArticleDate(){
Date currentDateTime = new Date();
this.lastUpdated = currentDateTime;
}
@Transient
public List<Integer> getSectionIds(){
List<Integer> sectionIds = new ArrayList<>();
for(Section section : sections){
sectionIds.add(section.getId());
}
return sectionIds;
}
public void clearArticleSections(){
this.sections.clear();
}
@Column(name = "number_of_views")
public int getNumberOfViews() {
return numberOfViews;
}
public void setNumberOfViews(int numberOfViews) {
this.numberOfViews = numberOfViews;
}
public void addView(){
this.numberOfViews++;
}
@Transient
public String getReducedTextContent(int numberOfCharacters){
int textContentLength = this.textContent.length();
if (textContentLength < numberOfCharacters)
{
numberOfCharacters = textContentLength;
}
String reducedContent = this.textContent.substring(0, numberOfCharacters) + "...";
return reducedContent;
}
}
| true |
59aa4f11befe255162f7f685a8048facb00d17c1 | Java | zxizx23/Java_Fundamental | /src/java_20190731/Calendar2.java | UTF-8 | 2,036 | 4 | 4 | [] | no_license | package java_20190731;
import java.util.Calendar;
//java docs comment
/**
Calendar 클래스는 연도별, 월별, 요일을 구할 수 있는 클래스 입니다.
*/
public class Calendar2 {
/**
매개변수에 연도로 호출하면 해당 연도의 월별 달력을 출력하는 기능입니다.
*/
public void print(int year) {
for(int i=1;i<=12;i++) {
print(year,i);
}
}
/**
매개변수에 연도와 월로 호출하면 해당 연도의 월 달력을 출력하는 기능입니다.
*/
public void print(int year, int month) {
Calendar c = Calendar.getInstance();
c.set(year,month-1,1);
System.out.println("일\t월\t화\t수\t목\t금\t토");
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
//들여쓰기 기능
for(int i=1;i<dayOfWeek;i++) {
System.out.print("\t");
}
for(int i=1;i<=c.getActualMaximum(Calendar.DATE);i++) {
System.out.print(i + "\t");
if(dayOfWeek % 7 == 0) {
System.out.println();
}
dayOfWeek++;
}
System.out.println();
System.out.println();
}
/**
매개변수에 연,월,일로 호출하면 요일을 출력하는 기능입니다.
*/
public void print(int year,int month, int day) {
Calendar c = Calendar.getInstance();
c.set(year,month-1,day);
int dayofWeek = c.get(Calendar.DAY_OF_WEEK);
String message = null;
if(dayofWeek == Calendar.SUNDAY) {
message = "일요일";
}else if(dayofWeek == Calendar.MONDAY) {
message = "월요일";
}else if(dayofWeek == Calendar.TUESDAY) {
message = "화요일";
}else if(dayofWeek == Calendar.WEDNESDAY) {
message = "수요일";
}else if(dayofWeek == Calendar.THURSDAY) {
message = "목요일";
}else if(dayofWeek == Calendar.FRIDAY) {
message = "금요일";
}else if(dayofWeek == Calendar.SATURDAY) {
message = "토요일";
}
System.out.println(year + "년 " + month +"월 " + day + "일은 " + message + "입니다");
}
}
| true |
64f34fb1510874259d1955365334199266029559 | Java | tkachenkoanastazi/test | /parser/src/main/java/main/Parser.java | UTF-8 | 3,903 | 3.0625 | 3 | [] | no_license | package main;
import org.jetbrains.annotations.NotNull;
public class Parser {
protected char[][]exprParser(@NotNull String expr)
{
char[][] superExpression=new char[2][expr.length()];
int a =0;
for(int i=0; i<expr.length();i++)
{
if(expr.charAt(i)=='*')
{
superExpression[0][a]='.';
} else {
if (expr.charAt(i)=='*' || expr.charAt(i)=='+') {
throw new UnsupportedOperationException("Неверное построенное регулярное выражение.");
} else{
superExpression[0][a] = expr.charAt(i);
}
}
if(i+1<expr.length()){
if (expr.charAt(i+1) == '*' || expr.charAt(i+1)=='+')
{
if(expr.charAt(i+1)=='*'){
superExpression[1][a]=0;
i++;
} else{
superExpression[1][a]=1;
i++;
}
} else {
superExpression[1][a]=2;
}
}
a++;
}
return superExpression;
}
protected int finder (char[][] expr, char[] str){
boolean isMatch=false;
boolean canReturn=false;
String result="";
int i_expr=0;
int i_str=0;
int startOfMathc=-1;
while (i_expr<expr.length) {
if (i_str < str.length) {
if ((expr[0][i_expr] == '.') || (expr[0][i_expr] == str[i_str])) {
switch (expr[1][i_expr]) {
case 0: {
if (i_expr == 0) {
canReturn = false;
} else
canReturn = true;
startOfMathc = i_str;
break;
}
case 1: {
canReturn = true;
startOfMathc = i_str;
i_str++;
break;
}
case 2: {
canReturn = false;
startOfMathc = i_str;
i_str++;
break;
}
}
i_expr++;
isMatch = true;
result += str[i_str];
} else {
if (canReturn) {
if ((expr[0][i_expr - 1] == '.') || (expr[0][i_expr - 1] == str[i_str])) {
if ((expr[1][i_expr - 1] == 1) || (expr[1][i_expr - 1] == 0)) {
startOfMathc = i_str;
i_str++;
}
isMatch = true;
result += str[i_str];
}
}else {
isMatch = false;
i_str++;
if (!result.isEmpty()) {
i_str = startOfMathc;
i_expr = 0;
}
}
}
} else {
if(!isMatch){
result="";
startOfMathc=-1;
}
break;
}
}
return startOfMathc;
}
int parse(String expression, String str){
char[][] myExpression;
int result;
char[] charString;
charString=str.toCharArray();
myExpression=exprParser(expression);
result=finder(myExpression,charString);
return result;
}
} | true |
728d230791f9b0747ad1b21a3ed34040ba0298f6 | Java | hudongxing/AndroidLearn | /VioletTANK/app/src/main/java/com/example/violet/violettank/ui/music/MusicPlayerFragment.java | UTF-8 | 6,142 | 1.921875 | 2 | [] | no_license | package com.example.violet.violettank.ui.music;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatSeekBar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.violet.violettank.R;
import com.example.violet.violettank.RxBus;
import com.example.violet.violettank.data.model.PlayList;
import com.example.violet.violettank.data.model.Song;
import com.example.violet.violettank.data.source.AppRepository;
import com.example.violet.violettank.data.source.PreferenceManager;
import com.example.violet.violettank.event.PlaySongEvent;
import com.example.violet.violettank.player.IPlayback;
import com.example.violet.violettank.player.PlayMode;
import com.example.violet.violettank.player.PlaybackService;
import com.example.violet.violettank.ui.base.BaseFragment;
import com.example.violet.violettank.ui.widget.ShadowImageView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
/**
* Created by violet.
*
* @ author VioLet.
* @ email 286716191@qq.com
* @ date 2017/11/8.
*/
public class MusicPlayerFragment extends BaseFragment implements MusicPlayerContract.View {
@BindView(R.id.image_view_album)
ShadowImageView imageViewAlbum;
@BindView(R.id.text_view_name)
TextView textViewName;
@BindView(R.id.text_view_artist)
TextView textViewArtist;
@BindView(R.id.text_view_progress)
TextView textViewProgress;
@BindView(R.id.seek_bar)
AppCompatSeekBar seekBar;
@BindView(R.id.text_view_duration)
TextView textViewDuration;
@BindView(R.id.layout_progress)
LinearLayout layoutProgress;
@BindView(R.id.button_play_mode_toggle)
AppCompatImageView buttonPlayModeToggle;
@BindView(R.id.button_play_last)
AppCompatImageView buttonPlayLast;
@BindView(R.id.button_play_toggle)
AppCompatImageView buttonPlayToggle;
@BindView(R.id.button_play_next)
AppCompatImageView buttonPlayNext;
@BindView(R.id.button_favorite_toggle)
AppCompatImageView buttonFavoriteToggle;
@BindView(R.id.layout_play_controls)
LinearLayout layoutPlayControls;
Unbinder unbinder;
private Handler mHandler = new Handler();
private IPlayback mPlayer;
private PlaybackService mServer;
private MusicPlayerPresenter mPresenter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_music, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mPresenter = new MusicPlayerPresenter(getActivity(), AppRepository.getInstance(), this);
mPresenter.subscribe();
}
// RXBus Events
@Override
protected Subscription subscribeEvents() {
return RxBus.getInstance().toObservable()
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(new Action1<Object>() {
@Override
public void call(Object o) {
if (o instanceof PlaySongEvent) {
onPlaySongEvent((PlaySongEvent) o);
}
// else if (o instanceof PlayListNowEvent) {
// onPlayListNowEvent((PlayListNowEvent) o);
// }
}
})
.subscribe(RxBus.defaultSubscriber());
}
@OnClick(R.id.button_play_toggle)
public void onPlayToggleAction(View view) {
if (mPlayer == null) return;
if (mServer.isPlaying()) {
mServer.pause();
} else {
mServer.play();
}
}
private void onPlaySongEvent(PlaySongEvent songEvent){
Song song = songEvent.song;
playSong(song);
}
private void playSong(Song song){
PlayList playList = new PlayList(song);
playSong(playList, 0);
}
private void playSong(PlayList playList,int playIndex){
if (playList == null) return;
playList.setPlayMode(PreferenceManager.lastPlayMode(getContext()));
}
@Override
public void handleError(Throwable error) {
}
@Override
public void onPlaybackServiceBound(PlaybackService service) {
mServer = service;
// mPlayer.registerCallback(this);
}
@Override
public void onPlaybackServiceUnbound() {
}
@Override
public void onSongSetAsFavorite(@NonNull Song song) {
}
@Override
public void onSongUpdated(@Nullable Song song) {
}
@Override
public void updatePlayMode(PlayMode playMode) {
if (playMode == null) {
playMode = PlayMode.getDefault();
}
switch (playMode) {
case LIST:
buttonPlayModeToggle.setImageResource(R.drawable.ic_play_mode_list);
break;
case LOOP:
buttonPlayModeToggle.setImageResource(R.drawable.ic_play_mode_loop);
break;
case SHUFFLE:
buttonPlayModeToggle.setImageResource(R.drawable.ic_play_mode_shuffle);
break;
case SINGLE:
buttonPlayModeToggle.setImageResource(R.drawable.ic_play_mode_single);
break;
}
}
@Override
public void updatePlayToggle(boolean play) {
}
@Override
public void updateFavoriteToggle(boolean favorite) {
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
}
| true |
a06e7af22056507881498d23d08871bf4bb14667 | Java | vasskob/Test-Rotation | /app/src/main/java/com/example/vasskob/testrotation/data/entity/maper/ProductEntityDataMapper.java | UTF-8 | 839 | 2.53125 | 3 | [] | no_license | package com.example.vasskob.testrotation.data.entity.maper;
import com.example.vasskob.testrotation.data.entity.ProductEntity;
import com.example.vasskob.testrotation.domain.model.Product;
import io.reactivex.functions.Function;
public class ProductEntityDataMapper implements Function<ProductEntity, Product> {
@Override
public Product apply(ProductEntity productEntity) throws Exception {
Product product = new Product();
product.setId(productEntity.getId());
product.setName(productEntity.getName());
product.setImageUrl(productEntity.getImageUrl());
product.setPriceInCents(productEntity.getPriceInCents());
product.setPrimaryCategory(productEntity.getPrimaryCategory());
product.setInventoryCount(productEntity.getInventoryCount());
return product;
}
}
| true |
6c03d447d488cd32da4aaef88b1bf4c0270501a1 | Java | ivandiassantos/prova-cadastro-clientes | /src/main/java/br/com/cadastroclientes/repository/TelefoneRepository.java | UTF-8 | 294 | 1.671875 | 2 | [] | no_license | package br.com.cadastroclientes.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import br.com.cadastroclientes.model.Telefone;
@Repository
public interface TelefoneRepository extends CrudRepository<Telefone, Long>{
}
| true |
671c60f96f19475159768d166d6681ec6f8c7a4e | Java | junnikokuki/RobotApplication | /alpha2ctrl/src/main/java/com/ubtechinc/alpha2ctrlapp/ui/adapter/shop/SearchActionAdpter.java | UTF-8 | 7,113 | 1.773438 | 2 | [] | no_license | package com.ubtechinc.alpha2ctrlapp.ui.adapter.shop;
import android.content.Context;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.orhanobut.logger.Logger;
import com.ubtechinc.alpha2ctrlapp.R;
import com.ubtechinc.alpha2ctrlapp.base.Alpha2Application;
import com.ubtechinc.alpha2ctrlapp.base.IDataCallback;
import com.ubtechinc.alpha2ctrlapp.entity.business.robot.NewActionInfo;
import com.ubtechinc.alpha2ctrlapp.service.RobotManagerService;
import com.ubtechinc.alpha2ctrlapp.ui.activity.main.MainPageActivity;
import com.ubtechinc.alpha2ctrlapp.ui.fragment.shop.SearchFragment;
import com.ubtechinc.alpha2ctrlapp.widget.dialog.CommonDiaglog;
import com.ubtechinc.alpha2ctrlapp.widget.dialog.CommonDiaglog.OnNegsitiveClick;
import com.ubtechinc.alpha2ctrlapp.widget.dialog.CommonDiaglog.OnPositiveClick;
import com.ubtechinc.alpha2ctrlapp.widget.dialog.LoadingDialog;
import java.util.List;
/**
* [动作列表适配器]
*
* @author zengdengyi
* @version 1.0
* @date 2014-9-27
**/
public class SearchActionAdpter extends BaseAdapter implements OnItemClickListener, OnItemLongClickListener, OnPositiveClick, OnNegsitiveClick {
private Context context;
private List<NewActionInfo> actionList;
private LayoutInflater inflater;
public int clicktemp = -1;
private long mlLastClickTime = SystemClock.uptimeMillis();
/**
* 动作名称
**/
private String mPlayActionFileName = "";
private MainPageActivity activity;
private CommonDiaglog deleDialog;
private SearchFragment frag;
IDataCallback<String> callback;
public String getmPlayActionFileName() {
return mPlayActionFileName;
}
public void setmPlayActionFileName(String mPlayActionFileName) {
this.mPlayActionFileName = mPlayActionFileName;
}
public SearchActionAdpter(Context context, SearchFragment frag, List<NewActionInfo> actionList, IDataCallback<String> callback) {
this.context = context;
this.frag = frag;
this.actionList = actionList;
activity = (MainPageActivity) context;
inflater = LayoutInflater.from(context);
deleDialog = new CommonDiaglog(activity, false);
deleDialog.setNegsitiveClick(this);
deleDialog.setPositiveClick(this);
this.callback = callback;
deleDialog.setMessase(context.getString(R.string.local_action_uninstall_action_tips));
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return actionList.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return actionList.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public void onNotifyDataSetChanged(List<NewActionInfo> actionList) {
this.actionList = actionList;
clicktemp = -1;
this.notifyDataSetChanged();
}
public void onClear() {
this.actionList.clear();
clicktemp = -1;
this.notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
ViewHolder viewHolder = null;
if (viewHolder == null) {
viewHolder = new ViewHolder();
convertView = inflater.inflate(R.layout.search_item,
null, false);
viewHolder.alphaName = (TextView) convertView
.findViewById(R.id.alphaName);
viewHolder.lvbackground = (LinearLayout) convertView
.findViewById(R.id.lvbackground);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (clicktemp == position) {
viewHolder.alphaName.setTextColor(context.getResources().getColor(R.color.red));
;
} else {
viewHolder.alphaName.setTextColor(context.getResources().getColor(R.color.black2));
}
viewHolder.alphaName.setText(actionList.get(position).getActionName());
return convertView;
}
class ViewHolder {
TextView alphaName;
LinearLayout lvbackground;
}
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
// TODO Auto-generated method stub
clicktemp = position;
notifyDataSetChanged();
if (RobotManagerService.getInstance().isConnectedRobot()) {
Logger.i( "onItemClick = " + position);
boolean bTimeOut = Math.abs(SystemClock.uptimeMillis()
- mlLastClickTime) > 250 ? true : false;
mlLastClickTime = SystemClock.uptimeMillis();
if (bTimeOut) {// 防止频繁发送命令
setmPlayActionFileName(actionList.get(position).getActionId());
activity.onPlayAction(actionList.get(position).getActionId(), actionList.get(position).getActionName());
Alpha2Application.getInstance().setCurrentPlayFileName(actionList.get(position).getActionName());
}
}
}
/**
* 提取英文的首字母,非英文字母用#代替。
*
* @param str
* @return
*/
private String getAlpha(String str) {
String sortStr = str.trim().substring(0, 1).toUpperCase();
// 正则表达式,判断首字母是否是英文字母
if (sortStr.matches("[A-Z]")) {
return sortStr;
} else {
return "#";
}
}
@Override
public void OnNegsitiveClick() {
// TODO Auto-generated method stub
}
@Override
public void OnPositiveClick() {
// TODO Auto-generated method stub
if (clicktemp != -1) {
if (RobotManagerService.getInstance().isConnectedRobot()) {
if (!TextUtils.isEmpty(Alpha2Application.getInstance().getCurrentPlayFileName()) && Alpha2Application.getInstance().getCurrentPlayFileName().equals(actionList.get(clicktemp).getActionName())) {
activity.onStopAction();
Alpha2Application.getInstance().setCurrentPlayFileName("");
}
LoadingDialog.getInstance(context).show();
callback.onCallback(actionList.get(clicktemp).getActionId());
}
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
clicktemp = position;
deleDialog.show();
return true;
}
}
| true |
aeb9e16b109a8225f2664fa7a57b7ff4cae7b56b | Java | AmarvirSingh/Contact_AmarvirSingh_783273 | /app/src/main/java/com/example/contact_amarvirsingh_783273/HelperClass.java | UTF-8 | 4,360 | 2.5 | 2 | [] | no_license | package com.example.contact_amarvirsingh_783273;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class HelperClass extends SQLiteOpenHelper {
private final String tableName = "phoneBook";
private final String fName = "f_name";
private final String lName = "l_name";
private final String Email = "email";
private final String Phone = "phone";
private final String Address = "address";
private final String Id = "id";
public HelperClass(@Nullable Context context) {
super(context, "Contact_Database", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + fName + " TEXT NOT NULL , " + lName + " TEXT NOT NULL," + Email + " TEXT NOT NULL," + Phone + " TEXT NOT NULL," + Address + " TEXT NOT NULL," + Id + " INTEGER NOT NULL CONSTRAINT contact_pk PRIMARY KEY AUTOINCREMENT);";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long insertContact(String first, String last, String add, String number, String mail) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(fName, first);
cv.put(lName, last);
cv.put(Email, mail);
cv.put(Phone, number);
cv.put(Address, add);
long result = db.insert(tableName, null, cv);
return result;
}
public long deleteContact(int id) {
SQLiteDatabase db = getWritableDatabase();
long res = db.delete(tableName, Id + " = ?", new String[]{String.valueOf(id)});
return res;
}
public ArrayList<ContactModelClass> getAllContacts() {
SQLiteDatabase data = getReadableDatabase();
ArrayList<ContactModelClass> allContact = new ArrayList<>();
Cursor cursor = null;
cursor = data.rawQuery("SELECT * FROM " + tableName, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String fName = cursor.getString(0);
String lName = cursor.getString(1);
String Email = cursor.getString(2);
String Phone = cursor.getString(3);
String Address = cursor.getString(4);
int Id = cursor.getInt(5);
ContactModelClass model = new ContactModelClass(Id, fName, lName, Address, Email, Phone);
allContact.add(model);
}
}
cursor.close();
return allContact;
}
public ArrayList<ContactModelClass> getOneContact(int id) {
SQLiteDatabase data = getReadableDatabase();
ArrayList<ContactModelClass> contact = new ArrayList<>();
Cursor cursor = null;
ContactModelClass model = new ContactModelClass();
cursor = data.rawQuery("SELECT * FROM " + tableName + " WHERE " + Id + " = ? ;", new String[]{String.valueOf(id)});
if (cursor != null) {
while (cursor.moveToNext()) {
String fName = cursor.getString(0);
String lName = cursor.getString(1);
String Email = cursor.getString(2);
String Phone = cursor.getString(3);
String Address = cursor.getString(4);
int Id = cursor.getInt(5);
model = new ContactModelClass(Id, fName, lName, Address, Email, Phone);
contact.add(model);
}
}
cursor.close();
return contact;
}
public long updateData(int ID, String Fname, String Lname, String email, String phone, String address) {
SQLiteDatabase database = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(fName, Fname);
values.put(lName, Lname);
values.put(Email, email);
values.put(Phone, phone);
values.put(Address, address);
long result = database.update(tableName, values, Id + " = ? ", new String[]{String.valueOf(ID)});
return result;
}
}
| true |
0db1f92eb4076d9f6d4ff1a5ef879484c06b2ca8 | Java | Moswag/ConcertFinder | /app/src/main/java/cytex/co/zw/concertfinder/fragments/LoginFragment.java | UTF-8 | 4,310 | 2.234375 | 2 | [] | no_license | package cytex.co.zw.concertfinder.fragments;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import cytex.co.zw.concertfinder.NavMain;
import cytex.co.zw.concertfinder.R;
import cytex.co.zw.concertfinder.utils.MessageToast;
/**
* A simple {@link Fragment} subclass.
*/
public class LoginFragment extends Fragment {
EditText email,password;
Button btnLogin;
private FirebaseAuth auth;
private ProgressDialog progressDialog;
public LoginFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_login, container, false);
email=view.findViewById(R.id.email);
password=view.findViewById(R.id.password);
btnLogin=view.findViewById(R.id.btnLogin);
progressDialog=new ProgressDialog(getActivity());
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
MessageToast.show(getActivity(),"Welcome back");
startActivity(new Intent(getActivity(), NavMain.class));
}
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkTexts()){
//do it
}
else{
progressDialog.setTitle("Authenticating user");
progressDialog.show();
String temail=email.getText().toString().trim();
String tpassword=password.getText().toString().trim();
//authenticate user
auth.signInWithEmailAndPassword(temail, tpassword)
.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressDialog.dismiss();
if (!task.isSuccessful()) {
MessageToast.show(getActivity(),"Authentiction failed, please try differently");
//startActivity(new Intent(LoginActivity.this,NavMain.class));
} else {
MessageToast.show(getActivity(),"Welcome to Concert Finder App");
Intent intent = new Intent(getActivity(), NavMain.class);
startActivity(intent);
}
}
});
}
}
});
return view;
}
private boolean checkTexts(){
if(TextUtils.isEmpty(email.getText().toString())){
email.setFocusable(true);
email.setError("Email is required");
return true;
}
else if(TextUtils.isEmpty(password.getText().toString())){
password.setFocusable(true);
password.setError("Password is required");
return true;
}
else{
return false;
}
}
}
| true |
5dcfdf0a032f087576a179058a523796308d3b9a | Java | shmilychan/goods-crud | /goods-service/src/main/java/cn/czl/goods/service/IGoodsService.java | UTF-8 | 1,520 | 2.40625 | 2 | [] | no_license | package cn.czl.goods.service;
import java.util.Map;
import java.util.Set;
import cn.czl.goods.vo.Goods;
public interface IGoodsService {
/**
* 批量删除商品信息,逻辑删除
* @param gids 商品ID的集合
* @return 删除成功返回true,失败返回false
*/
public boolean delete(Set<Long> gids);
/**
* 更新商品信息
* @param gid 要修改的商品编号
* @return 成功返回true,失败返回false
*/
public boolean edit(Goods vo);
/**
* 进行商品信息更新前的查询操作
* @param gid 要修改的商品编号
* @return 包括如下内容:<br>
* 1.key = allItems, value = 所有的一级分类信息
* 2.key = allSubitems , value = 所有的二级分类信息
* 3.key = goods, value = 商品数据<br>
*/
public Map<String, Object> editPre(Long gid);
/**
* 进行所有商品信息的列出操作
* @param currentPage 当前页
* @param lineSize 每页显示行数
* @param column 数据列
* @param keyWord 关键字
* @return 返回商品信息的Map集合
*/
public Map<String, Object> list(long currentPage,int lineSize,String column,String keyWord);
/**
* 增加商品信息
* @param vo 商品信息vo对象
* @return 成功返回true
*/
public boolean add(Goods vo);
/**
* 实现商品商品信息增加前的查询
* @return 包括如下内容:<br>
* 1.key = allItems , value = 所有的一级菜单<br>
*
*/
public Map<String, Object> addPre();
}
| true |
584899ea714e940261d19156b7d281c7bb44d0c1 | Java | navdeep-G/code-cracking | /src/code/ngill/arraysandstrings/DupeChars.java | UTF-8 | 963 | 3.734375 | 4 | [] | no_license | package code.ngill.arraysandstrings;
public class DupeChars {
public static void removeDuplicateChars(char[] string) {
for (int i = 0; i < string.length - 1; i++) {
if(string[i] == ' ') {
continue;
}
for (int j = i + 1; j < string.length; j++) {
if(string[i] == string[j]) {
string[j] = ' ';
}
}
}
for (int i = 1; i < string.length - 1; i++) {
if(string[i] == ' ') {
string[i] = string[i+1];
string[i+1] = ' ';
}
}
System.out.println(string);
}
public static void removeDuplicateCharacters(char[] string) {
int tail = 1;
for (int i = 1; i < string.length; ++i) {
int j;
for (j = 0; j < tail; ++j) {
if(string[i] == string[j]) break;
}
if(j == tail) {
string[tail] = string[i];
++tail;
}
}
string[tail] = 0;
System.out.println(string);
}
public static void main(String[] args) {
char[] str = "aaaa".toCharArray();
removeDuplicateCharacters(str);
}
}
| true |
72d4ea5f202764297e3bf6cb081d350b703ce23a | Java | flyfoxwhu/applications | /service/src/main/java/com/applications/service/lock/DistributeHandlerTest.java | UTF-8 | 601 | 2.34375 | 2 | [] | no_license | package com.applications.service.lock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author hukaisheng
* @date 2017/4/5.
*/
@Component
public class DistributeHandlerTest {
@Autowired
private static DistributedLockHandler distributedLockHandler;
public static void main(String[] args) {
Lock lock = new Lock("lockk", "sssssssss");
if (distributedLockHandler.tryLock(lock)) {
System.out.print("test 1234456");
distributedLockHandler.releaseLock(lock);
}
}
}
| true |
abe3aa9d319f7a1e9cf7d7fc7ab6a0e5002240fb | Java | medalibettaieb/moduleArchitectureJee | /tn.esprit.moduleArchitectureJee.calculetteClient/appClientModule/tn/esprit/moduleArchitectureJee/calculetteClient/tests/TestAdd.java | UTF-8 | 850 | 2.25 | 2 | [] | no_license | package tn.esprit.moduleArchitectureJee.calculetteClient.tests;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import tn.esprit.moduleArchitectureJee.calculette.services.interfaces.CalculetteServicesRemote;
public class TestAdd {
/**
* @param args
*/
public static void main(String[] args) {
Context context;
try {
context = new InitialContext();
CalculetteServicesRemote calculetteServicesRemote = (CalculetteServicesRemote) context
.lookup("tn.esprit.moduleArchitectureJee.calculette/CalculetteServices!tn.esprit.moduleArchitectureJee.calculette.services.interfaces.CalculetteServicesRemote");
int a = 1;
int b = 0;
calculetteServicesRemote.add(a, b);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true |
93b6672171e4a914b884dcc3c09fee66e1620735 | Java | httvc/WidgetDemo | /app/src/main/java/com/httvc/widgetdemo/ScalableImageView.java | UTF-8 | 9,682 | 2.546875 | 3 | [] | no_license | package com.httvc.widgetdemo;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.OverScroller;
import androidx.core.view.GestureDetectorCompat;
//双向滑动的
public class ScalableImageView extends View {
private static final float IMAGE_WIDTH=Utils.dp2px(300);
private static final float OVER_SCALE_FACTOR=1.5f;
Bitmap bitmap;
Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
float offsetX;
float offsetY;
float originalOffsetX;
float originalOffsetY;
float smallScale;
float bigScale;
boolean big;//判断当前是否是大图
float currentScale;//从0到1f的值
ObjectAnimator scaleAnimator;
GestureDetectorCompat detector;
HenGestureListener gestureListener=new HenGestureListener();
HenFlingRunner henFlingRunner=new HenFlingRunner();
ScaleGestureDetector scaleDetector;//手指缩放 ScaleGestureDetectorCompat不是其兼容类
HenScaleListener henScaleListener=new HenScaleListener();
OverScroller scroller;
public ScalableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
bitmap=Utils.getPicture(getResources(),(int) IMAGE_WIDTH);
/* detector=new GestureDetectorCompat(context,this);
detector.setOnDoubleTapListener(this);//双击*/
detector=new GestureDetectorCompat(context,gestureListener);
scroller=new OverScroller(context);
scaleDetector=new ScaleGestureDetector(context,henScaleListener);
//双击第二种写法 简单写法
/* detector=new GestureDetectorCompat(context,new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onDoubleTap(MotionEvent e) {
return super.onDoubleTap(e);
}
});*/
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
originalOffsetX =((float) getWidth()-bitmap.getWidth())/2;
originalOffsetY =((float) getHeight()-bitmap.getHeight())/2;
if ((float)bitmap.getWidth()/bitmap.getHeight()>(float) getWidth()/getHeight()) {
smallScale=(float) getWidth()/bitmap.getWidth();
bigScale=(float) getHeight()/bitmap.getHeight()*OVER_SCALE_FACTOR;
}else {
smallScale=(float) getHeight()/bitmap.getHeight();
bigScale=(float) getWidth()/bitmap.getWidth()*OVER_SCALE_FACTOR;
}
currentScale=smallScale;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getActionMasked()==MotionEvent.ACTION_UP){
performClick();
}
boolean result=scaleDetector.onTouchEvent(event);
if (!scaleDetector.isInProgress()){//isInProgress 检测是不是双指缩放
result=detector.onTouchEvent(event);
}
return result;
}
@Override
public boolean performClick() {
return super.performClick();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float scaleFraction=(currentScale-smallScale)/(bigScale-smallScale);
canvas.translate(offsetX*scaleFraction,offsetY*scaleFraction);
// float scale=smallScale+(bigScale-smallScale)*scaleFraction ;
canvas.scale(currentScale,currentScale,getWidth()/2f,getHeight()/2f);
canvas.drawBitmap(bitmap, originalOffsetX, originalOffsetY,paint);
}
public float getCurrentScale() {
return currentScale;
}
public void setCurrentScale(float currentScale) {
this.currentScale = currentScale;
invalidate();
}
class HenGestureListener extends GestureDetector.SimpleOnGestureListener{
/**
* 收到ACTION_DOWN之后调用
* @param e
* @return
*/
@Override
public boolean onDown(MotionEvent e) {
return true;//必须返回true后面的才能收到
}
/**
* 预按下
* @param e
*/
@Override
public void onShowPress(MotionEvent e) {
}
//每次单下抬起(单击)
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
//手指按下移动
//
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (big){
offsetX-=distanceX;
offsetX=Math.min(offsetX,(bitmap.getWidth()*bigScale-getWidth())/2);
offsetX=Math.max(offsetX,-(bitmap.getWidth()*bigScale-getWidth())/2);
offsetY-=distanceY;
offsetY=Math.min(offsetY,(bitmap.getHeight()*bigScale-getHeight())/2);
offsetY=Math.max(offsetY,-(bitmap.getHeight()*bigScale-getHeight())/2);
invalidate();
}
return false;
}
//长按
@Override
public void onLongPress(MotionEvent e) {
}
//手指快速滑动(滑动的时候手指抬起了)
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (big){
scroller.fling((int)offsetX,(int)offsetY,(int)velocityX,(int)velocityY,
(int)-(bitmap.getWidth()*bigScale-getWidth())/2,
(int)(bitmap.getWidth()*bigScale-getWidth())/2,
(int)-(bitmap.getHeight()*bigScale-getWidth())/2,
(int)(bitmap.getHeight()*bigScale-getHeight())/2);
/* for (int i = 10; i <100 ; i+=10) {
postDelayed(new Runnable() {
@Override
public void run() {
refresh();
}
},i);
}*/
//作用是让 postOnAnimation里面的代码在下一帧到来的时候去主线程执行
// postOnAnimation(ScalableImageView.this);
postOnAnimation(henFlingRunner);
//立即去主线程执行
//post(this);
}
return false;
}
//单击确认(确认想单击还是想双击)用于做双击的监听
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
//双击 300ms 点击四次 这个方法触发两次
@Override
public boolean onDoubleTap(MotionEvent e) {
big=!big;
if (big){
offsetX=(e.getX()-getWidth()/2f)-(e.getX()-getWidth()/2f)*bigScale/smallScale;
offsetY=(e.getX()-getHeight()/2f)-(e.getX()-getHeight()/2f)*bigScale/smallScale;
getScaleAnimator().start();
}else {
getScaleAnimator().reverse();
}
return false;
}
//当手指双击抬起,再按下会触发不太起触发,抬起后消失
@Override
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
}
private ObjectAnimator getScaleAnimator(){
if (scaleAnimator==null){
scaleAnimator=ObjectAnimator.ofFloat(this,"currentScale",0);
/*scaleAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
offsetX=0;
offsetY=0;
}
});*/
}
scaleAnimator.setFloatValues(smallScale,bigScale);
return scaleAnimator;
}
private void postOnAnimation(ScalableImageView scalableImageView) {
if (scroller.computeScrollOffset()){//这个动画是否还在执行中,动画执行完返回false
offsetX=scroller.getCurrX();
offsetY=scroller.getCurrY();
invalidate();
postOnAnimation(this);
//兼容
// ViewCompat.postOnAnimation(this,this);
}
}
class HenFlingRunner implements Runnable{
@Override
public void run() {
if (scroller.computeScrollOffset()){//这个动画是否还在执行中,动画执行完返回false
offsetX=scroller.getCurrX();
offsetY=scroller.getCurrY();
invalidate();
postOnAnimation(this);
//兼容
// ViewCompat.postOnAnimation(this,this);
}
}
}
class HenScaleListener implements ScaleGestureDetector.OnScaleGestureListener {
float initialScale;
//在scale过程中
@Override
public boolean onScale(ScaleGestureDetector detector) {//detector里有倍数和焦点,焦点是两个手指的中心
detector.getFocusX();//焦点
detector.getFocusY();
currentScale =initialScale*detector.getScaleFactor();//缩放倍数从1到0
invalidate();
return false;
}
//在scale之前
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
initialScale=currentScale;
return true;
}
//在scale之后
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
}
}
}
| true |
c4b477ae7250b4aa732c335dd493e8b0f1013cb9 | Java | zhclub/study | /study-spring/src/test/java/com/zhouhao/study/spring/ioc/TestBeanTest.java | UTF-8 | 481 | 1.890625 | 2 | [] | no_license | package com.zhouhao.study.spring.ioc;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
class TestBeanTest {
@Test
public void test() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
TestBean testBean = applicationContext.getBean(TestBean.class);
testBean.hello();
}
} | true |
e418b0e41bae2e2361b803c065cb71da5ad5400e | Java | alldatacenter/alldata | /dts/airbyte/airbyte-config/init/src/main/java/io/airbyte/config/init/DefinitionsProvider.java | UTF-8 | 703 | 1.648438 | 2 | [
"MIT",
"Elastic-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | /*
* Copyright (c) 2023 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.config.init;
import io.airbyte.config.StandardDestinationDefinition;
import io.airbyte.config.StandardSourceDefinition;
import io.airbyte.config.persistence.ConfigNotFoundException;
import java.util.List;
import java.util.UUID;
public interface DefinitionsProvider {
StandardSourceDefinition getSourceDefinition(final UUID definitionId) throws ConfigNotFoundException;
List<StandardSourceDefinition> getSourceDefinitions();
StandardDestinationDefinition getDestinationDefinition(final UUID definitionId) throws ConfigNotFoundException;
List<StandardDestinationDefinition> getDestinationDefinitions();
}
| true |
a0e2fbd608a3c5520045dea3d2c400f57c989d9e | Java | anuragkumarak95/lang | /src/org/practice/lang/tokenizer/Token.java | UTF-8 | 521 | 3.078125 | 3 | [] | no_license | package org.practice.lang.tokenizer;
/**
* Created by Anurag on 14-02-2016.
* <p/>
* This class contains the standard token model in LANG (having a token string and its Token BuiltInType.).
*/
public class Token {
private String token;
private TokenType type;
public Token(String token, TokenType type) {
this.token = token;
this.type = type;
}
//getters.
public String getToken() {
return token;
}
public TokenType getType() {
return type;
}
}
| true |
14d09e120523d910a7150338b5ee5e34db0719d0 | Java | mdsd-team-1/photos-metamodeling | /Photos-EMF-Project/src/PhotosMetaModel/impl/AutowiredImpl.java | UTF-8 | 770 | 1.828125 | 2 | [
"MIT"
] | permissive | /**
*/
package PhotosMetaModel.impl;
import PhotosMetaModel.Autowired;
import PhotosMetaModel.PhotosMetaModelPackage;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Autowired</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class AutowiredImpl extends MinimalEObjectImpl.Container implements Autowired {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected AutowiredImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return PhotosMetaModelPackage.Literals.AUTOWIRED;
}
} //AutowiredImpl
| true |