text
stringlengths 10
2.72M
|
|---|
package appModules;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import Utility.ExcelUtils;
import pageObjects.Signup_Objects;
public class SignUp {
static WebDriver driver;
@BeforeTest
public void launch()
{
driver=new FirefoxDriver();
driver.get("https://www.samsung.com/us/support/account");
driver.manage().window().maximize();
}
@Test
public void signup() throws Exception
{
driver.switchTo().frame("support_iframe");
Signup_Objects.btn_Signup(driver).click();
Utility.ExcelUtils.setExcelFile(Utility.Constant.Path_TestData+Utility.Constant.File_TestData, "Sheet2");
for(int i=1;i<3;i++)
{
//String spassword=ExcelUtils.getCellData(i, 2);
Signup_Objects.txtbx_FirstName(driver).sendKeys(ExcelUtils.getStringCellData(i, 0));
Thread.sleep(3000);
Signup_Objects.txtbx_LastName(driver).sendKeys(ExcelUtils.getStringCellData(i, 1));
Thread.sleep(3000);
double zip=ExcelUtils.getNumericCellData(i, 2);
Signup_Objects.txtbx_Zipcode(driver).sendKeys(String.valueOf(zip));
Thread.sleep(3000);
double phone=ExcelUtils.getNumericCellData(i, 3);
Signup_Objects.txtbx_Phonenumber(driver).sendKeys(String.valueOf(phone));
Thread.sleep(3000);
Signup_Objects.txtbx_Email(driver).sendKeys(ExcelUtils.getStringCellData(i, 4));
Thread.sleep(3000);
Signup_Objects.txtbx_ConfEmail(driver).sendKeys(Signup_Objects.txtbx_Email(driver).getAttribute("value"));
Thread.sleep(3000);
Signup_Objects.txtbx_Password(driver).sendKeys(ExcelUtils.getStringCellData(i, 6));
Thread.sleep(3000);
Signup_Objects.txtbx_ConfPassword(driver).sendKeys(Signup_Objects.txtbx_Password(driver).getAttribute("value"));
Signup_Objects.dropdown_Month(driver).selectByVisibleText("3");
Thread.sleep(3000);
Signup_Objects.dropdown_Day(driver).selectByValue("23");
Thread.sleep(3000);
Signup_Objects.dropdown_Year(driver).selectByValue("1990");
Thread.sleep(3000);
Signup_Objects.btn_Submit(driver).click();
Thread.sleep(3000);
}
}
}
|
package com.example.labs.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class OpeningPage extends AppCompatActivity {
private ImageButton anxious, sad, tired, happy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opening_page);
anxious = (ImageButton) findViewById(R.id.imageButton5);
sad = (ImageButton) findViewById(R.id.imageButton8);
tired = (ImageButton) findViewById(R.id.imageButton7);
happy = (ImageButton) findViewById(R.id.imageButton9);
happy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openActivity2();
}
});
}
public void openActivity2() {
Intent intent = new Intent(this, activity_lpp2901_2.class);
startActivity(intent);
}
}
|
package com.lesports.albatross.entity.community;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by jiangjianxiong on 16/6/1.
*/
public class CommunityEntity extends MultiItemEntity {
@SerializedName("content")
@Expose
private ContentEntity content;
@SerializedName("content_id")
@Expose
private int content_id;
@SerializedName("content_type")
@Expose
private String content_type;
@SerializedName("time")
@Expose
private String time;
public ContentEntity getContent() {
return content;
}
public void setContent(ContentEntity content) {
this.content = content;
}
public int getContent_id() {
return content_id;
}
public void setContent_id(int content_id) {
this.content_id = content_id;
}
public String getContent_type() {
return content_type;
}
public void setContent_type(String content_type) {
this.content_type = content_type;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
|
package com.zackstrife.hugo.capezzone;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private DessinView dessin;
private Button Btnred,Btnblue,Btnblack,Btnyel,Btnrand,Btnclear;
private TextView size;
private EditText weight;
private String color;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dessin= (DessinView)findViewById(R.id.DessinView);
Btnblack= (Button)findViewById(R.id.BtnBlack);
Btnblue= (Button)findViewById(R.id.BtnBlue);
Btnred= (Button)findViewById(R.id.BtnRed);
Btnyel=(Button)findViewById(R.id.BtnYel);
Btnrand=(Button)findViewById(R.id.BtnRand);
Btnclear=(Button)findViewById(R.id.BtnClear);
weight= (EditText)findViewById(R.id.editText);
Btnblue.setOnClickListener(new setcolorblue());
Btnred.setOnClickListener(new setcolorred());
Btnblack.setOnClickListener(new setcolorblack());
Btnyel.setOnClickListener(new setcoloryellow());
Btnrand.setOnClickListener(new setcolorrandom());
Btnclear.setOnClickListener(new clear());
weight.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
dessin.setStroke(Integer.parseInt(weight.getText().toString()));
Toast.makeText(MainActivity.this, "Stroke width changed", Toast.LENGTH_SHORT).show();
}
});
}
private class setcolorblue implements View.OnClickListener {
@Override
public void onClick(View v) {
dessin.setPaintColor(Color.BLUE);
}
}
private class setcolorred implements View.OnClickListener {
@Override
public void onClick(View v) {
dessin.setPaintColor(Color.RED);
}
}
private class setcolorblack implements View.OnClickListener {
@Override
public void onClick(View v) {
dessin.setPaintColor(Color.BLACK);
}
}
private class setcoloryellow implements View.OnClickListener {
@Override
public void onClick(View v) {
dessin.setPaintColor(Color.YELLOW);
}
}
private class setcolorrandom implements View.OnClickListener {
@Override
public void onClick(View v) {
Random color = new Random();
dessin.setPaintColor(Color.rgb(color.nextInt(256), color.nextInt(256), color.nextInt(256)));
}
}
private class clear implements View.OnClickListener {
@Override
public void onClick(View v) {
dessin.path.reset();
dessin.invalidate();
}
}
}
|
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/**
* Created by jorge on 04/05/2018.
*/
class MainTests {
private static WebDriver webDriver;
private static final String BASE_URL = "https://192.168.56.101:5000";
//private static final String BASE_URL="https://192.168.164.129:5000";
@BeforeAll
static void init() {
try {
System.setProperty("webdriver.gecko.driver", new File("../../res/geckodriver.exe").getCanonicalPath());
System.setProperty("webdriver.chrome.driver", new File("../../res/chromedriver.exe").getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
webDriver = new FirefoxDriver();
assertTrue(login());
}
private static boolean login() {
webDriver.get(BASE_URL);
webDriver.findElement(By.cssSelector("a[href=\"#login-modal\"]:not(#signUpButton)")).click();
webDriver.findElement(By.id("email")).sendKeys("teacher@gmail.com");
webDriver.findElement(By.id("password")).sendKeys("pass");
webDriver.findElement(By.id("log-in-btn")).click();
WebDriverWait wait = new WebDriverWait(webDriver, 10);
wait.until((ExpectedCondition<Boolean>) webDriver -> {
System.out.print(webDriver.getCurrentUrl());
if (webDriver.getCurrentUrl().equals(BASE_URL))
try {
return webDriver.findElement(By.cssSelector("login-modal app-error-message")) != null;
} catch (ElementNotFoundException e) {
return false;
}
else return true;
});
return !webDriver.getCurrentUrl().equals(BASE_URL);
}
@Test
public void testLogin() {
//assertEquals(true, login());
}
@Test
public void changePasswordCorrectly() {
WebElement settingsBtn = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.id("settings-button")));
settingsBtn.click();
assertEquals(BASE_URL + "/#/settings", webDriver.getCurrentUrl());
webDriver.findElement((By.cssSelector("[href=\"#password-modal\"]"))).click();
webDriver.findElement(By.id("inputCurrentPassword")).sendKeys("pass");
webDriver.findElement(By.id("inputNewPassword")).sendKeys("pass2");
webDriver.findElement(By.id("inputNewPassword2")).sendKeys("pass23");
webDriver.findElement(By.cssSelector("button.modal-footer-button")).click();
String status = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#password-modal app-error-message"))).getAttribute("ng-reflect-custom-class");
assertEquals("correct", status);
}
@Test
public void changePasswordIncorrectly() {
WebElement settingsBtn = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.id("settings-button")));
settingsBtn.click();
assertEquals(BASE_URL + "/#/settings", webDriver.getCurrentUrl());
webDriver.findElement((By.cssSelector("[href=\"#password-modal\"]"))).click();
webDriver.findElement(By.id("inputCurrentPassword")).sendKeys("pass");
webDriver.findElement(By.id("inputNewPassword")).sendKeys("pass2");
webDriver.findElement(By.id("inputNewPassword2")).sendKeys("pass23");
webDriver.findElement(By.cssSelector("button.modal-footer-button")).click();
String status = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#password-modal app-error-message"))).getAttribute("ng-reflect-custom-class");
assertNotEquals("correct", status);
}
@Test
public void showCourses() {
WebElement element = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.id("course-list")));
assertNotEquals(0, element.findElements(By.className("course-list-item")).size());
}
@Test
public void navigateCalendar() {
String[] months = {
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"october",
"november",
"december"
};
List<String> monthsList = Arrays.asList(months);
WebElement element = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.className("calendar-title")));
String calendarTitle = element.getText().toLowerCase();
String[] dateParts = calendarTitle.split(" ");
int currentMonthIndex = monthsList.indexOf(dateParts[0].toLowerCase());
String previousMonth = currentMonthIndex == 0 ? monthsList.get(11) : monthsList.get(currentMonthIndex - 1);
String previousYear = currentMonthIndex == 0 ? (Integer.parseInt(dateParts[1]) - 1 + "") : dateParts[1];
WebElement calendarIconGroup = webDriver.findElement(By.className("calendar-icon-group"));
List<WebElement> calendarIcons = calendarIconGroup.findElements(By.className("material-icons"));
calendarIcons.get(0).click();
assertEquals(previousMonth + " " + previousYear, webDriver.findElement(By.className("calendar-title")).getText().toLowerCase());
calendarIcons.get(1).click();
assertEquals(calendarTitle, webDriver.findElement(By.className("calendar-title")).getText().toLowerCase());
}
private WebElement getBusyDayEvents() {
new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.className("cal-cell-row")));
List<WebElement> calendarRows = webDriver.findElements(By.className("cal-cell-row"));
for (WebElement row :
calendarRows) {
try {
WebElement busyDayElement = row.findElement(By.className("cal-day-badge"));
busyDayElement.click();
return new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.className("cal-open-day-events")));
} catch (NoSuchElementException ignored) {
}
}
return null;
}
@Test
public void calendarToday() {
}
@Test
public void calendarGoEvent() {
WebElement events = getBusyDayEvents();
assertNotNull(events);
events.findElement(By.className("calendar-event-icon")).click();
assertTrue(webDriver.getCurrentUrl().matches(BASE_URL + "/#/courses/\\d/\\d"));
}
public void clickCourse(){
showCourses(); //WaitCoursesToShow
webDriver.findElement(By.id("course-list")).findElement(By.className("course-list-item")).click();
assertTrue(webDriver.getCurrentUrl().matches(BASE_URL + "/#/courses/\\d/\\d"));
}
@Test
public void showForumTopics() {
clickCourse();
WebElement tab = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.id("forum-tab-icon")));
tab.click();
WebElement tabContainer = webDriver.findElement(By.id("md-tab-content-0-2"));
assertNotEquals(0, tabContainer.findElements(By.className("entry-title")).size());
}
@Test
public void createForumTopic() {
// todo não foi possível implementar porque o popup de criação de tópico não fica visível
}
@Test
public void showFiles(){
clickCourse();
WebElement tab = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.id("files-tab-icon")));
tab.click();
WebElement tabContainer = webDriver.findElement(By.id("md-tab-content-0-3"));
try{
assertNotNull(tabContainer.findElements(By.tagName("app-file-group")));
}catch (ElementNotFoundException ignored){
}
}
@Test
public void EditFile(){
showFiles();
WebElement editBtn = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".material-icons.add-element-icon.right")));
editBtn.click();
WebElement firstFile = webDriver.findElement(By.className("drag-bag-editable")).findElements(By.tagName("div")).get(0);
String fileName = firstFile.findElement(By.className("file-name-div")).getText();
WebElement editFileBtn = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.className("edit-file-name-icon")));
editFileBtn.click();
WebElement fileNameInput = webDriver.findElement(By.id("input-file-title"));
assertEquals(fileName, fileNameInput.getAttribute("value"));
fileNameInput.sendKeys("2");
webDriver.findElement(By.id("put-modal-btn")).click();
firstFile = webDriver.findElement(By.className("drag-bag-editable")).findElements(By.tagName("div")).get(0);
assertEquals(fileName + "2", firstFile.findElement(By.className("file-name-div")).getText());
}
@Test
public void deleteFile(){
showFiles();
WebElement editBtn = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".material-icons.add-element-icon.right")));
// todo
}
@Test
public void showUsers(){
clickCourse();
WebElement tab = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.id("attenders-tab-icon")));
tab.click();
WebElement tabContainer = webDriver.findElement(By.id("md-tab-content-0-4"));
assertNotEquals(0, tabContainer.findElements(By.className("user-attender-row")).size());
}
@Test
public void deleteUser(){
showUsers();
WebElement editBtn = new WebDriverWait(webDriver, 10)
.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".material-icons.add-element-icon.right")));
editBtn.click();
WebElement tabContainer = webDriver.findElement(By.id("md-tab-content-0-4"));
int previousUsersCount = tabContainer.findElements(By.className("user-attender-row")).size();
webDriver.findElement(By.className("del-attender-icon")).click();
assertEquals(previousUsersCount - 1, tabContainer.findElements(By.className("user-attender-row")).size());
}
}
|
package com.intricatech.topwatch;
import android.text.SpannableString;
/**
* Created by Bolgbolg on 17/05/2017.
*/
public interface NewSplitListener {
void onNewSplitCreated(SpannableString timeSS, SpannableString distanceSS);
}
|
package ir.ceit.search.nlp.stemming.global.utils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* @author htaghizadeh
*/
public class TrieImpl<T> implements TrieInterface<T> {
private TrieNode<T> rootNode = new TrieNode<T>();
@Override
public void add(String key, T value) {
addNode(rootNode, key, 0, value);
}
@Override
public T find(String key) {
return findKey(rootNode, key);
}
@Override
public List<T> search(String prefix) {
List<T> list = new ArrayList<T>();
char[] ch = prefix.toCharArray();
TrieNode<T> node = rootNode;
for (int i = 0; i < ch.length; i++) {
node = node.getChildren().get(ch[i]);
if (node == null) {
break;
}
}
if (node != null) {
getValuesFromNode(node, list);
}
return list;
}
@Override
public boolean contains(String key) {
return hasKey(rootNode, key);
}
@Override
public Set<String> getAllKeys() {
Set<String> keySet = new HashSet<String>();
getKeysFromNode(rootNode, "", keySet);
return keySet;
}
@Override
public int size() {
return getAllKeys().size();
}
private void getValuesFromNode(TrieNode<T> currNode, List<T> valueList) {
if (currNode.isTerminal()) {
valueList.add(currNode.getNodeValue());
}
Map<Character, TrieNode<T>> children = currNode.getChildren();
Iterator childIter = children.keySet().iterator();
while (childIter.hasNext()) {
Character ch = (Character)childIter.next();
TrieNode<T> nextNode = children.get(ch);
getValuesFromNode(nextNode, valueList);
}
}
private void getKeysFromNode(TrieNode<T> currNode, String key, Set keySet) {
if (currNode.isTerminal()) {
keySet.add(key);
}
Map<Character, TrieNode<T>> children = currNode.getChildren();
Iterator childIter = children.keySet().iterator();
while (childIter.hasNext()) {
Character ch = (Character)childIter.next();
TrieNode<T> nextNode = children.get(ch);
String s = key + nextNode.getNodeKey();
getKeysFromNode(nextNode, s, keySet);
}
}
private T findKey(TrieNode<T> currNode, String key) {
Character c = key.charAt(0);
if (currNode.getChildren().containsKey(c)) {
TrieNode<T> nextNode = currNode.getChildren().get(c);
if (key.length() == 1) {
if (nextNode.isTerminal()) {
return nextNode.getNodeValue();
}
} else {
return findKey(nextNode, key.substring(1));
}
}
return null;
}
private boolean hasKey(TrieNode<T> currNode, String key) {
Character c = key.charAt(0);
if (currNode.getChildren().containsKey(c)) {
TrieNode<T> nextNode = currNode.getChildren().get(c);
if (key.length() == 1) {
if (nextNode.isTerminal()) {
return true;
}
} else {
return hasKey(nextNode, key.substring(1));
}
}
return false;
}
private void addNode(TrieNode<T> currNode, String key, int pos, T value) {
Character c = key.charAt(pos);
TrieNode<T> nextNode = currNode.getChildren().get(c);
if (nextNode == null) {
nextNode = new TrieNode<T>();
nextNode.setNodeKey(c);
if (pos < key.length() - 1) {
addNode(nextNode, key, pos + 1, value);
} else {
nextNode.setNodeValue(value);
nextNode.setTerminal(true);
}
currNode.getChildren().put(c, nextNode);
} else {
if (pos < key.length() - 1) {
addNode(nextNode, key, pos + 1, value);
} else {
nextNode.setNodeValue(value);
nextNode.setTerminal(true);
}
}
}
}
|
package com.sinotech.settle.utils;
//import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Excel工具类
* @author ZTF
* @date 2017年5月24日 下午3:47:38
*/
public class PoiExcelUtils {
/** 数字格式化 */
private static NumberFormat format = NumberFormat.getInstance();
/** 日志 */
private static final Logger LOGGER = LoggerFactory.getLogger(PoiExcelUtils.class);
/** 列默认宽度 */
private static final int DEFAUL_COLUMN_WIDTH = 4000;
/**
* 是否是2003的excel,返回true是2003
* @param filePath
* @return
*/
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
/**
* 是否是2007的excel,返回true是2007
* @param filePath
* @return
*/
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
/**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
public static boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
return false;
}
return true;
}
/**
* 1.创建 workbook
* @return {@link HSSFWorkbook}
* @author ZTF
*/
private HSSFWorkbook getHSSFWorkbook() {
LOGGER.info("【创建 workbook】");
return new HSSFWorkbook();
}
/**
* 2.创建 sheet
* @param hssfWorkbook {@link HSSFWorkbook}
* @param sheetName sheet 名称
* @return {@link HSSFSheet}
*/
private HSSFSheet getHSSFSheet(HSSFWorkbook hssfWorkbook, String sheetName) {
LOGGER.info("【创建 sheet】sheetName : " + sheetName);
return hssfWorkbook.createSheet(sheetName);
}
/**
* 3.写入表头信息
* @param hssfWorkbook {@link HSSFWorkbook}
* @param hssfSheet {@link HSSFSheet}
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值
* </p>
* @param title 标题
*/
private void writeHeader(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet, String[] headers,
String title) {
LOGGER.info("【写入表头信息】");
// 头信息处理
String[] newHeaders = headersHandler(headers);
// 初始化标题和表头单元格样式
HSSFCellStyle titleCellStyle = createTitleCellStyle(hssfWorkbook);
// 标题栏
HSSFRow titleRow = hssfSheet.createRow(0);
titleRow.setHeight((short) 500);
HSSFCell titleCell = titleRow.createCell(0);
// 设置标题文本
titleCell.setCellValue(new HSSFRichTextString(title));
// 设置单元格样式
titleCell.setCellStyle(titleCellStyle);
// 处理单元格合并,四个参数分别是:起始行,终止行,起始行,终止列
hssfSheet.addMergedRegion(new CellRangeAddress(0, 0, (short) 0,
(short) (newHeaders.length - 1)));
// 设置合并后的单元格的样式
titleRow.createCell(newHeaders.length - 1).setCellStyle(titleCellStyle);
// 表头
HSSFRow headRow = hssfSheet.createRow(1);
headRow.setHeight((short) 500);
HSSFCell headCell = null;
String[] headInfo = null;
// 处理excel表头
for (int i = 0, len = newHeaders.length; i < len; i++) {
headInfo = newHeaders[i].split("@");
headCell = headRow.createCell(i);
headCell.setCellValue(headInfo[0]);
headCell.setCellStyle(titleCellStyle);
// 设置列宽度
setColumnWidth(i, headInfo, hssfSheet);
}
}
/**
* 写入表头信息
* @param hssfWorkbook {@link HSSFWorkbook}
* @param hssfSheet {@link HSSFSheet}
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值
* </p>
* @param startIndex 起始行索引
*/
private void writeHeader(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet, String[] headers,
int startIndex) {
LOGGER.info("【写入表头信息】");
HSSFCellStyle headerCellStyle = createTitleCellStyle(hssfWorkbook);
// 表头
HSSFRow headRow = hssfSheet.createRow(startIndex);
headRow.setHeight((short) 500);
HSSFCell headCell = null;
String[] headInfo = null;
// 处理excel表头
for (int i = 0, len = headers.length; i < len; i++) {
headInfo = headers[i].split("@");
headCell = headRow.createCell(i);
headCell.setCellValue(headInfo[0]);
headCell.setCellStyle(headerCellStyle);
// 设置列宽度
setColumnWidth(i, headInfo, hssfSheet);
}
}
/**
* 写入表头信息
* 多行表头
* @param hssfWorkbook {@link HSSFWorkbook}
* @param hssfSheet {@link HSSFSheet}
* @param headers 列标题,数组形式,{{表头一},{表头2}}
* <p>
* head#1,2,1,1:和平表头#开始行,结束行,开始列,结束列
* 如要合并(@head#1,2,1,1) 必须放置 字符串最后,'列标题1@beanFieldName1@columnWidth ’ 为必须
* 如{{"列标题1@beanFieldName1@columnWidth@head#1,2,1,1","列标题2@colspan@rowspan@columnWidth","列标题3@colspan@rowspan@columnWidth"},
* {"列标题1@colspan@rowspan@columnWidth@head#2,3,4,5","列标题2@colspan@rowspan@columnWidth","列标题3@colspan@rowspan@columnWidth"}}
* </p>
* 表头长度必须一致,合并处可用""代替
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值
* </p>
* @param startIndex 起始行索引
*/
private void writeMultiHeader(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet, String[][] headers,String title,
int startIndex) {
LOGGER.info("【写入表头信息】");
// 头信息处理
String[] newHeaders = headersHandler(headers[headers.length-1]);
HSSFCellStyle headerCellStyle = createTitleCellStyle(hssfWorkbook);
// 初始化标题和表头单元格样式
HSSFCellStyle titleCellStyle = createTitleCellStyle(hssfWorkbook);
// 标题栏
HSSFRow titleRow = hssfSheet.createRow(0);
titleRow.setHeight((short) 500);
HSSFCell titleCell = titleRow.createCell(0);
// 设置标题文本
titleCell.setCellValue(new HSSFRichTextString(title));
// 设置单元格样式
titleCell.setCellStyle(titleCellStyle);
// 处理单元格合并,四个参数分别是:起始行,终止行,起始行,终止列
hssfSheet.addMergedRegion(new CellRangeAddress(0, 0, (short) 0,
(short) (newHeaders.length - 1)));
// 设置合并后的单元格的样式
titleRow.createCell(newHeaders.length - 1).setCellStyle(titleCellStyle);
// String[] header = {};
List<String[]> multiparam = new ArrayList<>();
// Map<Integer,String[]> msp = new HashMap<Integer, String[]>();
String[] header = {};
String[] colspan = {};
for (int j = 0, len = headers.length; j < len;j++ ) {
header = headers[j];
HSSFRow headRow = hssfSheet.createRow(startIndex++);
headRow.setHeight((short) 500);
HSSFCell headCell = null;
String[] headInfo = null;
for (int i = 0, _len = header.length; i < _len; i++) {
headInfo = header[i].split("@");
if(j==0 && header[i].indexOf("head#") !=-1){
String hade = headInfo[headInfo.length-1];
colspan = hade.replace("head#","").split(",");
multiparam.add(colspan);
}
headCell = headRow.createCell(i);
headCell.setCellValue(headInfo[0]);
headCell.setCellStyle(headerCellStyle);
// 设置列宽度
setColumnWidth(i, headInfo, hssfSheet);
}
}
for (String[] string : multiparam) {
CellRangeAddress cra =new CellRangeAddress(Integer.parseInt(string[0]),
Integer.parseInt(string[1]),
Integer.parseInt(string[2]),
Integer.parseInt(string[3])); // 起始行, 终止行, 起始列, 终止列
hssfSheet.addMergedRegion(cra);
}
}
/**
* 头信息校验和处理
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值
* </p>
* @return 校验后的头信息
*/
private String[] headersHandler(String[] headers) {
List<String> newHeaders = new ArrayList<String>();
for (String string : headers) {
if (StringUtils.isNotBlank(string)) {
newHeaders.add(string);
}
}
int size = newHeaders.size();
return newHeaders.toArray(new String[size]);
}
/**
* 4.写入内容部分(默认从第三行开始写入)
*
* @param hssfWorkbook {@link HSSFWorkbook}
* @param hssfSheet {@link HSSFSheet}
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值
* </p>
* @param dataList 要导出的数据集合
* @throws Exception
*/
private void writeContentRowspan(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet, String[] headers,
List<?> dataList) throws Exception {
writeContentRowspan(hssfWorkbook, hssfSheet, headers, dataList, 2);
}
/**
* 4.写入内容部分(默认从第三行开始写入),可合并列
*
* @param hssfWorkbook {@link HSSFWorkbook}
* @param hssfSheet {@link HSSFSheet}
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值
* </p>
* @param dataList 要导出的数据集合
* @throws Exception
*/
private void writeContent(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet, String[] headers,
List<?> dataList) throws Exception {
writeContent(hssfWorkbook, hssfSheet, headers, dataList, 2);
}
/**
* 4.写入内容部分
*
* @param hssfWorkbook {@link HSSFWorkbook}
* @param hssfSheet {@link HSSFSheet}
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值
* </p>
* @param dataList 要导出的数据集合
* @param startIndex 起始行的索引
* @throws Exception
*/
private void writeContent(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet, String[] headers,
List<?> dataList, int startIndex) throws Exception {
LOGGER.info("【写入Excel内容部分】");
// 2015-8-13 增加,当没有数据的时候,把原来抛异常的方式修改成返回一个只有头信息,没有数据的空Excel
if (CollectionUtils.isEmpty(dataList)) {
LOGGER.warn("【没有内容数据】");
return;
}
HSSFRow row = null;
HSSFCell cell = null;
// 单元格的值
Object cellValue = null;
// 数据写入行索引
int rownum = startIndex;
// 单元格样式
HSSFCellStyle cellStyle = createContentCellStyle(hssfWorkbook);
// 遍历集合,处理数据
for (int j = 0, size = dataList.size(); j < size; j++) {
row = hssfSheet.createRow(rownum);
for (int i = 0, len = headers.length; i < len; i++) {
cell = row.createCell(i);
cellValue = ReflectUtils.getValueOfGetIncludeObjectFeild(dataList.get(j),
headers[i].split("@")[1]);
if(headers[i].indexOf("@format") != -1 && null != cellValue ){
cellValue = DateUtil.getDateTimeFormat((Date)(cellValue));
}
cellValueHandler(cell, cellValue);
cell.setCellStyle(cellStyle);
}
rownum++;
}
}
/**
* 4.写入内容部分,和并行,值相同时合并,以第一列合并为主,
*
* @param hssfWorkbook {@link HSSFWorkbook}
* @param hssfSheet {@link HSSFSheet}
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值
* </p>
* @param dataList 要导出的数据集合
* @param startIndex 起始行的索引
* @throws Exception
*/
private void writeContentRowspan(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet, String[] headers,
List<?> dataList, int startIndex) throws Exception {
LOGGER.info("【写入Excel内容部分】");
// 2015-8-13 增加,当没有数据的时候,把原来抛异常的方式修改成返回一个只有头信息,没有数据的空Excel
if (CollectionUtils.isEmpty(dataList)) {
LOGGER.warn("【没有内容数据】");
return;
}
HSSFRow row = null;
HSSFCell cell = null;
// 单元格的值
Object cellValue = null;
// 数据写入行索引
int rownum = startIndex;
// 单元格样式
HSSFCellStyle cellStyle = createContentCellStyle(hssfWorkbook);
// 遍历集合,处理数据
//需要合并的列
Map<Integer,int[]> rowspans = new HashMap<Integer, int[]>();
Map<Integer,Object> values = new HashMap<Integer,Object>();
boolean fals = false;
for (int j = 0, size = dataList.size(); j < size; j++) {
row = hssfSheet.createRow(rownum);
fals = false;
for (int i = 0, len = headers.length; i < len; i++) {
cell = row.createCell(i);
cellValue = ReflectUtils.getValueOfGetIncludeObjectFeild(dataList.get(j),
headers[i].split("@")[1]);
if(headers[i].indexOf("@format") != -1 && null != cellValue ){
cellValue = DateUtil.getDateTimeFormat((Date)(cellValue));
}
if(headers[i].indexOf("@colspan")!=-1){
if(j == 0){
values.put(i, cellValue);
rowspans.put(i, new int[]{rownum,rownum,i,i});//开始行,结束行,开始列,结束列
}
if(!cellValue.equals(values.get(i) ) || fals){
if(i == 0){
fals = true;
}
//合并数据
if(rowspans.get(i)[0] < rowspans.get(i)[1]){
CellRangeAddress cra =new CellRangeAddress(rowspans.get(i)[0],rowspans.get(i)[1], rowspans.get(i)[2], rowspans.get(i)[3]); // 起始行, 终止行, 起始列, 终止列
hssfSheet.addMergedRegion(cra);
}
values.put(i, cellValue);
rowspans .put(i, new int[]{rownum,rownum,i,i});//开始行,结束行,开始列,结束列
}else{
rowspans.get(i)[1] = rownum;
fals = false;
}
}
cellValueHandler(cell, cellValue);
cell.setCellStyle(cellStyle);
}
rownum++;
}
int [] index = new int[4];
for (Map.Entry<Integer, int[]> entry : rowspans.entrySet()) {
index = entry.getValue();
if(index[0] < index[1]){
CellRangeAddress cra =new CellRangeAddress(index[0],index[1],index[2],index[3]); // 起始行, 终止行, 起始列, 终止列
hssfSheet.addMergedRegion(cra);
}
}
}
/**
* 设置列宽度
* @param i 列的索引号
* @param headInfo 表头信息,其中包含了用户需要设置的列宽
*/
private void setColumnWidth(int i, String[] headInfo, HSSFSheet hssfSheet) {
if (headInfo.length < 3) {
// 用户没有设置列宽,使用默认宽度
hssfSheet.setColumnWidth(i, DEFAUL_COLUMN_WIDTH);
return;
}
if (StringUtils.isBlank(headInfo[2])) {
// 使用默认宽度
hssfSheet.setColumnWidth(i, DEFAUL_COLUMN_WIDTH);
return;
}
// 使用用户设置的列宽进行设置
hssfSheet.setColumnWidth(i, Integer.parseInt(headInfo[2]));
}
/**
* 单元格写值处理器
* @param {{@link HSSFCell}
* @param cellValue 单元格值
*/
private void cellValueHandler(HSSFCell cell, Object cellValue) {
// 2015-8-13 修改,判断cellValue是否为空,否则在cellValue.toString()会出现空指针异常
if (cellValue == null) {
cell.setCellValue("");
return;
}
if (cellValue instanceof String) {
cell.setCellValue((String) cellValue);
} else if (cellValue instanceof Boolean) {
cell.setCellValue((Boolean) cellValue);
} else if (cellValue instanceof Calendar) {
cell.setCellValue((Calendar) cellValue);
} else if (cellValue instanceof Double) {
cell.setCellValue((Double) cellValue);
} else if (cellValue instanceof Integer || cellValue instanceof Long
|| cellValue instanceof Short || cellValue instanceof Float) {
cell.setCellValue((Double.parseDouble(cellValue.toString())));
} else if (cellValue instanceof HSSFRichTextString) {
cell.setCellValue((HSSFRichTextString) cellValue);
}
cell.setCellValue(cellValue.toString());
}
/**
* 创建标题和表头单元格样式
* @param hssfWorkbook {@link HSSFWorkbook}
* @return {@link HSSFCellStyle}
*/
@SuppressWarnings("deprecation")
private HSSFCellStyle createTitleCellStyle(HSSFWorkbook hssfWorkbook) {
LOGGER.info("【创建标题和表头单元格样式】");
// 单元格的样式
HSSFCellStyle cellStyle = hssfWorkbook.createCellStyle();
// 设置字体样式,改为变粗
HSSFFont font = hssfWorkbook.createFont();
font.setFontHeightInPoints((short) 13);
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(font);
// 单元格垂直居中
cellStyle.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
// 设置通用的单元格属性
setCommonCellStyle(cellStyle);
return cellStyle;
}
/**
* 创建内容单元格样式
* @param hssfWorkbook {@link HSSFWorkbook}
* @return {@link HSSFCellStyle}
*/
@SuppressWarnings("deprecation")
private HSSFCellStyle createContentCellStyle(HSSFWorkbook hssfWorkbook) {
LOGGER.info("【创建内容单元格样式】");
// 单元格的样式
HSSFCellStyle cellStyle = hssfWorkbook.createCellStyle();
// 设置字体样式,改为不变粗
HSSFFont font = hssfWorkbook.createFont();
font.setFontHeightInPoints((short) 11);
cellStyle.setFont(font);
// 设置单元格自动换行
cellStyle.setWrapText(true);
// 单元格垂直居中
cellStyle.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
//水平居中
// cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 设置通用的单元格属性
setCommonCellStyle(cellStyle);
return cellStyle;
}
/**
* 设置通用的单元格属性
* @param cellStyle 要设置属性的单元格
*/
@SuppressWarnings("deprecation")
private void setCommonCellStyle(HSSFCellStyle cellStyle) {
// 居中
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
// 设置边框
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
}
/**
* 将生成的Excel输出到指定目录
* @param hssfWorkbook {@link HSSFWorkbook}
* @param filePath 文件输出目录,包括文件名(.xls)
*/
private void write2FilePath(HSSFWorkbook hssfWorkbook, String filePath) {
LOGGER.info("【将生成的Excel输出到指定目录】filePath :" + filePath);
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream(filePath);
hssfWorkbook.write(fileOut);
} catch (Exception e) {
LOGGER.error("【将生成的Excel输出到指定目录失败】", e);
throw new RuntimeException("将生成的Excel输出到指定目录失败");
} finally {
IOUtils.closeQuietly(fileOut);
}
}
/**
* 生成Excel,存放到指定目录
* @param sheetName sheet名称
* @param title 标题
* @param filePath 要导出的Excel存放的文件路径
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值,默认4000
* </p>
* @param dataList 要导出数据的集合
* @throws Exception
*/
public static void createExcel2FilePath(String sheetName, String title, String filePath,
String[] headers, List<?> dataList) throws Exception {
if (org.apache.commons.lang3.ArrayUtils.isEmpty(headers)) {
LOGGER.warn("【表头为空】");
throw new RuntimeException("表头不能为空");
}
LOGGER.info("【生成Excel,并存放到指定文件夹目录下】sheetName : " + sheetName + " , title : " + title
+ " , filePath : " + filePath + " , headers : " + Arrays.toString(headers));
PoiExcelUtils poiExcelUtil = new PoiExcelUtils();
// 1.创建 Workbook
HSSFWorkbook hssfWorkbook = poiExcelUtil.getHSSFWorkbook();
// 2.创建 Sheet
HSSFSheet hssfSheet = poiExcelUtil.getHSSFSheet(hssfWorkbook, sheetName);
// 3.写入 head
poiExcelUtil.writeHeader(hssfWorkbook, hssfSheet, headers, title);
// 4.写入内容
poiExcelUtil.writeContent(hssfWorkbook, hssfSheet, headers, dataList);
// 5.保存文件到filePath中
poiExcelUtil.write2FilePath(hssfWorkbook, filePath);
}
/**
* 生成Excel,存放到指定目录
* @param sheetName sheet名称
* @param title 标题
* @param filePath 要导出的Excel存放的文件路径
* @param mainDataFields 主表数据需要展示的字段集合
* <p>
* 如{"字段1@beanFieldName1","字段2@beanFieldName2",字段3@beanFieldName3"}
* </p>
* @param mainData 主表数据
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值,默认4000
* </p>
* @param detailDataList 要导出数据的集合
* @param needExportDate 是否需要显示“导出日期”
* @throws Exception
*/
public static void createExcel2FilePath(String sheetName, String title, String filePath,
String[] mainDataFields, Object mainData,
String[] headers, List<?> detailDataList,
final boolean needExportDate) throws Exception {
if (ArrayUtils.isEmpty(headers)) {
LOGGER.warn("【参数headers为空】");
throw new IllegalArgumentException("headers");
}
if (ArrayUtils.isEmpty(mainDataFields)) {
LOGGER.warn("【参数mainDataFields】");
throw new IllegalArgumentException("mainDataFields");
}
if (mainData == null) {
LOGGER.warn("【参数mainData】");
throw new IllegalArgumentException("mainData");
}
LOGGER.info("【生成Excel,并存放到指定文件夹目录下】sheetName : " + sheetName + " , title : " + title
+ " , filePath : " + filePath + " , headers : " + Arrays.toString(headers));
PoiExcelUtils poiExcelUtil = new PoiExcelUtils();
// 1.创建 Workbook
HSSFWorkbook hssfWorkbook = poiExcelUtil.getHSSFWorkbook();
// 2.创建 Sheet
HSSFSheet hssfSheet = poiExcelUtil.getHSSFSheet(hssfWorkbook, sheetName);
// 3.写标题
headers = poiExcelUtil.writeTitle(hssfWorkbook, hssfSheet, headers, title);
// 4.写主表(mainData)数据
int usedRows = poiExcelUtil.writeMainData(hssfWorkbook, hssfSheet, headers.length,
mainDataFields, mainData, 1, needExportDate);
// 5.写入 head 这里默认将title写入到了第一行,所以header的起始行索引为usedRows + 1
poiExcelUtil.writeHeader(hssfWorkbook, hssfSheet, headers, usedRows + 1);
// 6.写从表(detailDataList)内容
poiExcelUtil.writeContent(hssfWorkbook, hssfSheet, headers, detailDataList, usedRows + 2);
// 7.保存文件到filePath中
poiExcelUtil.write2FilePath(hssfWorkbook, filePath);
}
/**
* 写标题
* @param hssfWorkbook {@link HSSFWorkbook}
* @param hssfSheet {@link HSSFSheet}
* @param headers 表头
* @param title 标题
* @return 去除无效表头后的新表头集合
*/
private String[] writeTitle(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet, String[] headers,
String title) {
return writeTitle(hssfWorkbook, hssfSheet, headers, title, 0);
}
/**
* 写标题
* @param hssfWorkbook {@link HSSFWorkbook}
* @param hssfSheet {@link HSSFSheet}
* @param headers 表头
* @param title 标题
* @param titleRowIndex 标题行的索引
* @return 去除无效表头后的新表头集合
*/
private String[] writeTitle(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet, String[] headers,
String title, int titleRowIndex) {
// 头信息处理
String[] newHeaders = headersHandler(headers);
// 初始化标题和表头单元格样式
HSSFCellStyle titleCellStyle = createTitleCellStyle(hssfWorkbook);
// 标题栏
HSSFRow titleRow = hssfSheet.createRow(titleRowIndex);
titleRow.setHeight((short) 500);
HSSFCell titleCell = titleRow.createCell(0);
// 设置标题文本
titleCell.setCellValue(new HSSFRichTextString(title));
// 设置单元格样式
titleCell.setCellStyle(titleCellStyle);
// 处理单元格合并,四个参数分别是:起始行,终止行,起始列,终止列
hssfSheet.addMergedRegion(new CellRangeAddress(titleRowIndex, titleRowIndex, (short) 0,
(short) (newHeaders.length - 1)));
// 设置合并后的单元格的样式
titleRow.createCell(newHeaders.length - 1).setCellStyle(titleCellStyle);
return newHeaders;
}
/**
* 写主表(mainData)数据
* @param hssfWorkbook {@link HSSFWorkbook}
* @param hssfSheet {@link HSSFSheet}
* @param columnSize 列数
* @param mainDataFields 主表数据需要展示的字段集合
* @param mainData 主表数据对象
* @param startIndex 起始行索引
* @param needExportDate 是否需要输出“导出日期”
* @return 主表数据使用了多少行
* @throws Exception
*/
private int writeMainData(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet, int columnSize,
String[] mainDataFields, Object mainData, int startIndex,
boolean needExportDate) throws Exception {
// LOGGER.info("【写主表(mainData)数据】columnSize = {} , mainDataFields = {} , mainData = {}",
// columnSize, Arrays.toString(mainDataFields), mainData);
// 1.计算主表数据需要写多少行,每行写多少个单元格,每行写多少个字段
int fieldsSize = mainDataFields.length;
// 导出日期是否需要独立一行显示
boolean exportDateSingleRow = fieldsSize * 2 % columnSize == 0;
// 主表属性需要的行数
int needRows = exportDateSingleRow ? fieldsSize * 2 / columnSize : fieldsSize * 2
/ columnSize + 1;
if (needExportDate && exportDateSingleRow) {
needRows += 1;
}
// 主表属性显示时,每行显示的主表属性量
int filedSizeInOneRow = fieldsSize * 2 < columnSize ? fieldsSize : columnSize / 2;
// 列数是否为偶数
final boolean isEvenColumn = columnSize % 2 == 0;
// // 每个字段需要2个单元格进行展示 --> fieldName : value
// int fieldsSize = mainDataFields.length;
// int needCellSize = needExportDate ? (fieldsSize + 1) * 2 : fieldsSize * 2;
// // 转换列数为偶数
// final boolean isEvenColumn = columnSize % 2 == 0;
// int availableColumns = isEvenColumn ? columnSize : columnSize - 1;
// // 计算写主表数据需要多少行
// int needRows = needCellSize % availableColumns == 0 ? needCellSize / availableColumns
// : needCellSize / availableColumns + 1;
// // 每行显示的字段数
// int fieldsSizeAddExportDateCell = needExportDate ? fieldsSize + 1 : fieldsSize;
// int filedSizeInOneRow = fieldsSizeAddExportDateCell % needRows == 0 ? fieldsSizeAddExportDateCell
// / needRows
// : fieldsSizeAddExportDateCell / needRows + 1;
// 2.开始写主表数据
HSSFRow row = null;
HSSFCell cell4FiledName = null;
HSSFCell cell4Value = null;
// 数据写入行索引
int rownum = startIndex;
// 单元格样式
HSSFCellStyle cellStyle = createContentCellStyle(hssfWorkbook);
// 每一行的单元格的索引
int cellIndex = 0;
// 主表字段的数组索引
int fieldIndex = 0;
for (int i = 0; i < needRows; i++) {
row = hssfSheet.createRow(rownum);
for (int j = 0; j < filedSizeInOneRow; j++) {
if (fieldIndex == fieldsSize) {
break;
}
// 取出对应索引的主表字段,然后切割成字符串数组
String[] fieldsArray = mainDataFields[fieldIndex].split("@");
fieldIndex++;
// 每个字段对应的单元格的索引
cellIndex = j * 2;
// 字段描述的单元格
cell4FiledName = row.createCell(cellIndex);
cellValueHandler(cell4FiledName, fieldsArray[0]);
cell4FiledName.setCellStyle(cellStyle);
// 字段值的单元格
cell4Value = row.createCell(cellIndex + 1);
cellValueHandler(cell4Value,
ReflectUtils.getValueOfGetIncludeObjectFeild(mainData, fieldsArray[1]));
cell4Value.setCellStyle(cellStyle);
// 如果当前行还可以继续写数据,则将导出日期写在该行
if (fieldIndex == fieldsSize && needExportDate && filedSizeInOneRow != j + 1) {
writeExportDate(hssfWorkbook, row, cellIndex + 2);
needExportDate = false;
hssfSheet.addMergedRegion(new CellRangeAddress(rownum, rownum,
(short) cellIndex + 3, (short) (columnSize - 1)));
// 设置合并后的单元格的样式
setMergedCellStyle(row, cellIndex + 3, columnSize - 1, cellStyle);
}
// 如果最后一个有值的单元格后还有空白单元格,将他们合并
if ((j == filedSizeInOneRow - 1 && !isEvenColumn) || fieldIndex == fieldsSize) {
int startCellIndex = needExportDate ? (short) cellIndex + 1
: (short) cellIndex + 3;
// 处理单元格合并,四个参数分别是:起始行,终止行,起始列,终止列
hssfSheet.addMergedRegion(new CellRangeAddress(rownum, rownum, startCellIndex,
(short) (columnSize - 1)));
// 设置合并后的单元格的样式
setMergedCellStyle(row, startCellIndex, columnSize - 1, cellStyle);
}
}
// 导出日期独自占用一行
if (needExportDate && fieldIndex == fieldsSize) {
int exportDateRowNum = rownum + 1;
row = hssfSheet.createRow(exportDateRowNum);
writeExportDate(hssfWorkbook, row, 0);
hssfSheet.addMergedRegion(new CellRangeAddress(exportDateRowNum, exportDateRowNum,
1, (short) (columnSize - 1)));
// 设置合并后的单元格的样式
setMergedCellStyle(row, 1, columnSize - 1, cellStyle);
// 生成一次导出日期之后,改变标识
needExportDate = false;
break;
}
rownum++;
}
return needRows;
}
/**
* 设置合并后的单元格的样式
* @param row {@link HSSFRow}
* @param beginCellIdnex 合并开始的单元格
* @param endCellIndex 合并结束的单元格
* @param cellStyle {@link HSSFCellStyle}
*/
private void setMergedCellStyle(HSSFRow row, int beginCellIdnex, int endCellIndex,
HSSFCellStyle cellStyle) {
for (int i = beginCellIdnex + 1; i <= endCellIndex; i++) {
row.createCell(i).setCellStyle(cellStyle);
}
}
/**
* 写入导出日期
* @param row {@link HSSFRow}
* @param cellIndex 列索引
*/
private void writeExportDate(HSSFWorkbook hssfWorkbook, HSSFRow row, int cellIndex) {
// 单元格样式
HSSFCellStyle cellStyle = createContentCellStyle(hssfWorkbook);
// 导出日期
HSSFCell cell4ExortDate = row.createCell(cellIndex);
cellValueHandler(cell4ExortDate, "导出日期");
cell4ExortDate.setCellStyle(cellStyle);
// 导出日期的值
HSSFCell cell4ExportDateValue = row.createCell(cellIndex + 1);
// cellValueHandler(cell4ExportDateValue,
// ProDateUtil.getCurrentDate(ProDateUtil.DATE_TIME_FORMAT));
cell4ExportDateValue.setCellStyle(cellStyle);
}
/**
* 生成Excel的WorkBook,用于导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值,默认4000
* </p>
* @param dataList 要导出数据的集合
* @throws Exception
*/
public static HSSFWorkbook createExcel2Export(String sheetName, String title, String[] headers,
List<?> dataList) throws Exception {
if (ArrayUtils.isEmpty(headers)) {
LOGGER.warn("【表头为空】");
throw new RuntimeException("表头不能为空");
}
LOGGER.info("【生成Excel的WorkBook,用于导出Excel】sheetName : " + sheetName + " , title : " + title
+ " , headers : " + Arrays.toString(headers));
PoiExcelUtils poiExcelUtil = new PoiExcelUtils();
// 1.创建 Workbook
HSSFWorkbook hssfWorkbook = poiExcelUtil.getHSSFWorkbook();
// 2.创建 Sheet
HSSFSheet hssfSheet = poiExcelUtil.getHSSFSheet(hssfWorkbook, sheetName);
// 3.写入 head
poiExcelUtil.writeHeader(hssfWorkbook, hssfSheet, headers, title);
// 4.写入内容
poiExcelUtil.writeContent(hssfWorkbook, hssfSheet, headers, dataList);
return hssfWorkbook;
}
/**
* 生成Excel的WorkBook,用于导出Excel
* 多表头
* @param sheetName sheet名称
* @param title 标题
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值,默认4000
* </p>
* @param dataList 要导出数据的集合
* @throws Exception
*/
public static HSSFWorkbook createExcelMultiExport(String sheetName, String title, String[][] headers,
List<?> dataList,List<int[]> list) throws Exception {
if (ArrayUtils.isEmpty(headers)) {
LOGGER.warn("【表头为空】");
throw new RuntimeException("表头不能为空");
}
LOGGER.info("【生成Excel的WorkBook,用于导出Excel】sheetName : " + sheetName + " , title : " + title
+ " , headers : " + Arrays.toString(headers));
PoiExcelUtils poiExcelUtil = new PoiExcelUtils();
// 1.创建 Workbook
HSSFWorkbook hssfWorkbook = poiExcelUtil.getHSSFWorkbook();
// 2.创建 Sheet
HSSFSheet hssfSheet = poiExcelUtil.getHSSFSheet(hssfWorkbook, sheetName);
// 3.写入 head
poiExcelUtil.writeMultiHeader(hssfWorkbook, hssfSheet, headers, title,1);
// 4.写入内容
poiExcelUtil.writeContent(hssfWorkbook, hssfSheet, headers[headers.length-1], dataList,3);
//加入合并合计行
if(null != list && list.size()>= 1){
for (int[] str : list) {
CellRangeAddress cra =new CellRangeAddress(str[0],
str[1],
str[2],
str[3]); // 起始行, 终止行, 起始列, 终止列
hssfSheet.addMergedRegion(cra);
}
}
return hssfWorkbook;
}
/**
* 生成Excel的WorkBook,用于导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值,默认4000
* </p>
* @param dataList 要导出数据的集合
* @throws Exception
*/
public static HSSFWorkbook createExcel2ExportRowspan (String sheetName, String title, String[] headers,
List<?> dataList) throws Exception {
if (ArrayUtils.isEmpty(headers)) {
LOGGER.warn("【表头为空】");
throw new RuntimeException("表头不能为空");
}
LOGGER.info("【生成Excel的WorkBook,用于导出Excel】sheetName : " + sheetName + " , title : " + title
+ " , headers : " + Arrays.toString(headers));
PoiExcelUtils poiExcelUtil = new PoiExcelUtils();
// 1.创建 Workbook
HSSFWorkbook hssfWorkbook = poiExcelUtil.getHSSFWorkbook();
// 2.创建 Sheet
HSSFSheet hssfSheet = poiExcelUtil.getHSSFSheet(hssfWorkbook, sheetName);
// 3.写入 head
poiExcelUtil.writeHeader(hssfWorkbook, hssfSheet, headers, title);
// 4.写入内容
poiExcelUtil.writeContentRowspan(hssfWorkbook, hssfSheet, headers, dataList);
return hssfWorkbook;
}
/**
* 生成Excel的WorkBook,用于导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param mainDataFields 主表数据需要展示的字段集合
* <p>
* 如{"字段1@beanFieldName1","字段2@beanFieldName2",字段3@beanFieldName3"}
* </p>
* @param mainData 主表数据
* @param headers 列标题,数组形式
* <p>
* 如{"列标题1@beanFieldName1@columnWidth","列标题2@beanFieldName2@columnWidth","列标题3@beanFieldName3@columnWidth"}
* </p>
* <p>
* 其中参数@columnWidth可选,columnWidth为整型数值,默认4000
* </p>
* @param detailDataList 要导出数据的集合
* @param needExportDate 是否需要“导出日期”
* @return {@link HSSFWorkbook}
* @throws Exception
*/
public static HSSFWorkbook createExcel2Export(String sheetName, String title,
String[] mainDataFields, Object mainData,
String[] headers, List<?> detailDataList,
boolean needExportDate) throws Exception {
if (ArrayUtils.isEmpty(headers)) {
LOGGER.warn("【参数headers为空】");
throw new IllegalArgumentException("headers");
}
if (ArrayUtils.isEmpty(mainDataFields)) {
LOGGER.warn("【参数mainDataFields】");
throw new IllegalArgumentException("mainDataFields");
}
if (mainData == null) {
LOGGER.warn("【参数mainData】");
throw new IllegalArgumentException("mainData");
}
LOGGER.info("【生成Excel,用于导出】sheetName : " + sheetName + " , title : " + title
+ " , headers : " + Arrays.toString(headers) + " , mainDataFields = "
+ Arrays.toString(mainDataFields));
PoiExcelUtils poiExcelUtil = new PoiExcelUtils();
// 1.创建 Workbook
HSSFWorkbook hssfWorkbook = poiExcelUtil.getHSSFWorkbook();
// 2.创建 Sheet
HSSFSheet hssfSheet = poiExcelUtil.getHSSFSheet(hssfWorkbook, sheetName);
// 3.写标题
headers = poiExcelUtil.writeTitle(hssfWorkbook, hssfSheet, headers, title);
// 4.写主表(mainData)数据
int usedRows = poiExcelUtil.writeMainData(hssfWorkbook, hssfSheet, headers.length,
mainDataFields, mainData, 1, needExportDate);
// 5.写入 head 这里默认将title写入到了第一行,然后需要header和主表详情间隔一行
poiExcelUtil.writeHeader(hssfWorkbook, hssfSheet, headers, usedRows + 2);
// 6.写从表(detailDataList)内容
poiExcelUtil.writeContent(hssfWorkbook, hssfSheet, headers, detailDataList, usedRows + 3);
return hssfWorkbook;
}
/**
* 根据文件路径读取excel文件,默认读取第0个sheet
* @param excelPath excel的路径
* @param skipRows 需要跳过的行数
* @param columnCount 列数量
* @return List<String[]> 集合中每一个元素是一个数组,按单元格索引存储每个单元格的值,一个元素可以封装成一个需要的java bean
* @throws Exception
*/
public static List<String[]> readExcel(String excelPath, int skipRows, int columnCount)
throws Exception {
return readExcel(excelPath, skipRows, columnCount, 0, null);
}
/**
* 根据文件路径读取excel文件的指定sheet
* @param excelPath excel的路径
* @param skipRows 需要跳过的行数
* @param columnCount 列数量
* @param sheetNo 要读取的sheet的索引,从0开始
* @return List<String[]> 集合中每一个元素是一个数组,按单元格索引存储每个单元格的值,一个元素可以封装成一个需要的java bean
* @throws Exception
*/
public static List<String[]> readExcel(String excelPath, int skipRows, int columnCount,
int sheetNo) throws Exception {
return readExcel(excelPath, skipRows, columnCount, sheetNo, null);
}
/**
* 根据文件路径读取excel文件的指定sheet,并封装空值单位各的坐标,默认读取第0个sheet
* @param excelPath excel的路径
* @param skipRows 需要跳过的行数
* @param columnCount 列数量
* @param noneCellValuePositionList 存储空值的单元格的坐标,每个坐标以x-y的形式拼接,如2-5表示第二行第五列
* @return List<String[]> 集合中每一个元素是一个数组,按单元格索引存储每个单元格的值,一个元素可以封装成一个需要的java bean
* @throws Exception
*/
public static List<String[]> readExcel(String excelPath, int skipRows, int columnCount,
List<String> noneCellValuePositionList) throws Exception {
return readExcel(excelPath, skipRows, columnCount, 0, noneCellValuePositionList);
}
/**
* 根据文件路径读取excel文件的指定sheet,并封装空值单位各的坐标,默认读取第0个sheet
* @param excelPath excel的路径
* @param skipRows 需要跳过的行数
* @param columnCount 列数量
* @param columnNumberForSkipValueValidateSet 不需要做空值验证的列的索引集合
* @param noneCellValuePositionList 存储空值的单元格的坐标,每个坐标以x-y的形式拼接,如2-5表示第二行第五列
* @return List<String[]> 集合中每一个元素是一个数组,按单元格索引存储每个单元格的值,一个元素可以封装成一个需要的java bean
* @throws Exception
*/
public static List<String[]> readExcel(String excelPath, int skipRows, int columnCount,
Set<Integer> columnNumberForSkipValueValidateSet,
List<String> noneCellValuePositionList) throws Exception {
return readExcel(excelPath, skipRows, columnCount, 0, columnNumberForSkipValueValidateSet,
noneCellValuePositionList);
}
/**
* 根据文件路径读取excel文件的指定sheet,并封装空值单位各的坐标
* @param excelPath excel的路径
* @param skipRows 需要跳过的行数
* @param columnCount 列数量
* @param sheetNo 要读取的sheet的索引,从0开始
* @param noneCellValuePositionList 存储空值的单元格的坐标,每个坐标以x-y的形式拼接,如2-5表示第二行第五列
* @return List<String[]> 集合中每一个元素是一个数组,按单元格索引存储每个单元格的值,一个元素可以封装成一个需要的java bean
* @throws Exception
*/
public static List<String[]> readExcel(String excelPath, int skipRows, int columnCount,
int sheetNo, List<String> noneCellValuePositionList)
throws Exception {
return readExcel(excelPath, skipRows, columnCount, sheetNo, null, noneCellValuePositionList);
}
/**
* 根据文件路径读取excel文件的指定sheet,并封装空值单位各的坐标
* @param excelPath excel的路径
* @param skipRows 需要跳过的行数
* @param columnCount 列数量
* @param sheetNo 要读取的sheet的索引,从0开始
* @param columnNumberForSkipValueValidateSet 不需要做空值验证的列的索引集合
* @param noneCellValuePositionList 存储空值的单元格的坐标,每个坐标以x-y的形式拼接,如2-5表示第二行第五列
* @return List<String[]> 集合中每一个元素是一个数组,按单元格索引存储每个单元格的值,一个元素可以封装成一个需要的java bean
* @throws Exception
*/
public static List<String[]> readExcel(String excelPath, int skipRows, int columnCount,
int sheetNo,
Set<Integer> columnNumberForSkipValueValidateSet,
List<String> noneCellValuePositionList) throws Exception {
// LOGGER
// .info(
// "【读取Excel】excelPath = {} , skipRows = {} , columnCount = {} , columnNumberForSkipValueValidateSet = {}",
// excelPath, skipRows, columnCount, columnNumberForSkipValueValidateSet);
if (StringUtils.isBlank(excelPath)) {
LOGGER.warn("【参数excelPath为空】");
return new ArrayList<String[]>();
}
FileInputStream is = new FileInputStream(new File(excelPath));
POIFSFileSystem fs = new POIFSFileSystem(is);
HSSFWorkbook wb = new HSSFWorkbook(fs);
List<String[]> list = new ArrayList<String[]>();
HSSFSheet sheet = wb.getSheetAt(sheetNo);
// 得到总共的行数
int rowNum = sheet.getPhysicalNumberOfRows();
try {
for (int i = skipRows; i < rowNum; i++) {
String[] vals = new String[columnCount];
HSSFRow row = sheet.getRow(i);
if (null == row) {
continue;
}
for (int j = 0; j < columnCount; j++) {
HSSFCell cell = row.getCell(j);
String val = getStringCellValue(cell);
// 没有需要跳过校验的列索引
if (CollectionUtils.isEmpty(columnNumberForSkipValueValidateSet)) {
if (noneCellValuePositionList != null && StringUtils.isBlank(val)) {
// 封装空值单元格的坐标
noneCellValuePositionList.add((i + 1) + "-" + j);
}
} else {
// 如果需要校验空值的单元格、当前列索引不在需要跳过校验的索引集合中
if (noneCellValuePositionList != null && StringUtils.isBlank(val)
&& !columnNumberForSkipValueValidateSet.contains(j)) {
// 封装空值单元格的坐标
noneCellValuePositionList.add((i + 1) + "-" + j);
}
}
vals[j] = val;
}
list.add(vals);
}
} catch (Exception e) {
LOGGER.error("【Excel解析失败】", e);
throw new RuntimeException("Excel解析失败");
} finally {
is.close();
wb.close();
}
return list;
}
/**
* 获取单元格数据内容为字符串类型的数据
* @param cell Excel单元格{@link HSSFCell}
* @return 单元格数据内容(可能是布尔类型等,强制转换成String)
*/
@SuppressWarnings("deprecation")
private static String getStringCellValue(HSSFCell cell) {
if (cell == null) {
return "";
}
String strCell = "";
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
strCell = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
strCell = String.valueOf(format.format(cell.getNumericCellValue()))
.replace(",", "");
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
strCell = String.valueOf(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_BLANK:
strCell = "";
break;
default:
strCell = "";
break;
}
if (StringUtils.isBlank(strCell)) {
return "";
}
return strCell;
}
/**
*
* @param titleMap 表头map
* @param mfile 文件file
* @param sheetNumber 从第几行开始解析
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public static List getExcelToList(Map titleMap, MultipartFile mfile, int sheetNumber)
throws FileNotFoundException, IOException {
Workbook workbook = null;
InputStream is = null;
List<Map> result = new ArrayList<Map>();
// 获取工作薄workbook
try {
is = mfile.getInputStream();
// 2007
workbook = new XSSFWorkbook(is);
} catch (Exception ex) {
// 2003
workbook = new HSSFWorkbook(is);
}
// workbook = new HSSFWorkbook(new FileInputStream(path));
// 获得指定的sheet
Sheet sheet = workbook.getSheetAt(sheetNumber);
// HSSFSheet sheet = workbook.getSheetAt(sheetNumber);
Row row = null;
Row row1 = null;
Cell cell = null;
// 获得sheet总行数
int rowCount = sheet.getLastRowNum();
if (rowCount < 1) {
return result;
}
// 遍历行row
for (int rowIndex = 1; rowIndex <= rowCount; rowIndex++) {
Map exMap = new HashMap();
// 获得行对象
row = sheet.getRow(rowIndex);
row1 = sheet.getRow(0);
if (null != row) {
// 获得本行中单元格的个数
int cellCount = row.getLastCellNum();
// 遍历列cell
for (short cellIndex = 0; cellIndex < cellCount; cellIndex++) {
cell = row.getCell(cellIndex);
// 获得指定单元格中的数据
Object cellStr = getCellString(cell);
for (Object key : titleMap.keySet()) {
if (row1.getCell(cellIndex) != null
&& titleMap.get(key).equals(
row1.getCell(cellIndex).toString())) {
exMap.put(key, (cellStr == null
|| cellStr.equals("null") ? "" : cellStr
.toString().trim()));
break;
}
}
}
result.add(exMap);
}
}
//关闭流资源
FileUtil.closeStream(is);
return result;
}
/**
* 获得指定单元格中的数据
*
* @param cell
* @return
*/
private static Object getCellString(Cell cell) {
// TODO Auto-generated method stub
Object result = null;
if (cell != null) {
// 单元格类型:Numeric:0,String:1,Formula:2,Blank:3,Boolean:4,Error:5
int cellType = cell.getCellType();
switch (cellType) {
case HSSFCell.CELL_TYPE_STRING:
result = cell.getRichStringCellValue().getString();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
double d = cell.getNumericCellValue();
Date date = HSSFDateUtil.getJavaDate(d);
java.text.SimpleDateFormat form = new SimpleDateFormat(
"yyyy-MM-dd");
String datea = form.format(date);
result = datea;
} else {
// 取得当前Cell的数值
String ser = String.format("%20.2f", cell
.getNumericCellValue());
String ser2 = String.format("%20.0f", cell
.getNumericCellValue());
String fs = ser2.trim() + ".00";
if (fs.equals(ser.trim())) {
result = ser2.trim();
} else {
result = ser;
}
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
result = cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
result = null;
break;
case HSSFCell.CELL_TYPE_ERROR:
result = null;
break;
default:
System.out.println("枚举了所有类型");
break;
}
}
return result;
}
public static void main(String[] args) {
System.out.println(Objects.toString("sdf", null));;
}
}
|
package com.mariusreimer.tapjoy;
/**
* Created by marius on 01/03/17.
*/
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.tapjoy.TJEarnedCurrencyListener;
public class MyTJEarnedCurrencyListener implements TJEarnedCurrencyListener {
private final ReactContext reactContext;
MyTJEarnedCurrencyListener(ReactContext reactContext) {
this.reactContext = reactContext;
}
@Override
public void onEarnedCurrency(final String currencyName, final int amount) {
final WritableMap responseMap = Arguments.createMap();
responseMap.putString(TapjoyModule.EARNED_CURRENCY_NAME, currencyName);
responseMap.putInt(TapjoyModule.EARNED_CURRENCY_VALUE, amount);
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(TapjoyModule.Events.EVENT_PLACEMENT_EARNED_CURRENCY.toString(), responseMap);
}
}
|
package com.navarromugas.test;
import com.navarromugas.models.*;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
public class DiosTest {
private Dios dios;
private Mundo mundoCreadoPorDios;
private Gps gps;
@Before
public void setUp() {
gps = new Gps(3, 3);
dios_existe();
dios_creo_al_mundo();
}
private void dios_existe() {
this.dios = new Dios(gps);
}
private void dios_creo_al_mundo() {
mundoCreadoPorDios = dios.mundoCreado();
}
@Test
public void a_dios_le_podemos_dar_un_mundo_existente_para_que_juegue_con_el() {
Mundo mundo = new Mundo(new Gps(5, 5));
dios.darMundo(mundo);
assertThat(dios.mundoCreado().toString(), equalTo(mundo.toString()));
}
@Test
public void si_hay_una_sola_celula_viva_en_la_proxima_generacion_muere() {
Coordenada ubicacion = new Coordenada(2, 2);
mundoCreadoPorDios.revivirCelula(ubicacion);
dios.avanzarUnaGeneracion();
assertThat(mundoCreadoPorDios.isCelulaViva(ubicacion), equalTo(false));
}
@Test
public void una_celula_muerta_con_tres_vecinas_vivas_vive_por_reproduccion() {
mundoCreadoPorDios.revivirCelula(new Coordenada(0, 0));
mundoCreadoPorDios.revivirCelula(new Coordenada(0, 2));
mundoCreadoPorDios.revivirCelula(new Coordenada(1, 2));
dios.avanzarUnaGeneracion();
assertThat(mundoCreadoPorDios.isCelulaViva(new Coordenada(1, 1)), equalTo(true));
}
@Test
public void una_celula_muerta_con_tres_vecinas_vivas_en_un_mundo_toroidal_vive_por_reproduccion() {
mundoCreadoPorDios.revivirCelula(new Coordenada(gps.getParalelos() - 1, gps.getMeridianos() - 1));
mundoCreadoPorDios.revivirCelula(new Coordenada(1, 0));
mundoCreadoPorDios.revivirCelula(new Coordenada(0, 1));
dios.avanzarUnaGeneracion();
assertThat(mundoCreadoPorDios.isCelulaViva(new Coordenada(0, 0)), equalTo(true));
}
}
|
package com.legaoyi.platform.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.legaoyi.mq.MQMessageProducer;
import com.legaoyi.rabbitmq.RabbitmqDirectExchangeMessageProducer;
import com.legaoyi.rabbitmq.RabbitmqFanoutExchangeMessageProducer;
/**
* @author gaoshengbo
*/
@Configuration("rabbitmqConfiguration")
public class RabbitmqConfiguration {
@Value("${rabbitmq.common.down.message.exchange}")
private String downMessageExchange;
@Value("${rabbitmq.video.down.message.exchange}")
private String videoMessageDownExchange;
@Bean("commonDownMessageProducer")
public MQMessageProducer commonDownMessageProducer() {
RabbitmqDirectExchangeMessageProducer mqMessageProducer = new RabbitmqDirectExchangeMessageProducer(this.downMessageExchange);
return mqMessageProducer;
}
@Bean("videoMessageDownProducer")
public MQMessageProducer videoMessageDownProducer() {
RabbitmqFanoutExchangeMessageProducer mqMessageProducer = new RabbitmqFanoutExchangeMessageProducer(this.videoMessageDownExchange);
return mqMessageProducer;
}
}
|
package com.onlyu.reactiveprog.controllers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
@Slf4j
@AllArgsConstructor
public class FailureController {
@GetMapping("/access-denied.html")
public String accessDenied() {
return "access-denied";
}
}
|
package src;
public class Product {
int id;
String title;
int cost;
public Product(int id, String title, int cost) {
this.id=id;
this.title=title;
this.cost=cost;
}
public void printProd(){
System.out.println(title + "number " +id +" costs "+cost+" rub");
}
}
|
/*
* 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 main.java.spatialrelex.ling;
import edu.stanford.nlp.ling.IndexedWord;
import edu.stanford.nlp.semgraph.SemanticGraph;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import main.java.parsers.StanfordParser;
import main.java.spatialrelex.Main;
import main.java.spatialrelex.markup.Doc;
import main.java.spatialrelex.markup.SpatialElement;
import main.java.spatialrelex.markup.SpatialRelation;
/**
*
* @author Jenny D'Souza
*/
public class Features {
public String parseStringFeature = "";
private String concatenatedLemmaStr = "";
private String concatenatedWordStr = "";
private String lexicalPatternStr = "";
private List<String> wordsInBetween = new ArrayList<>();
private List<String> wordsOfSe3 = new ArrayList<>();
private List<String> dependencyPathsSe1Se3Se2 = new ArrayList<>();
private List<String> dependencyPathsSe1Se2 = new ArrayList<>();
private List<String> dependencyPathsSe3Se2 = new ArrayList<>();
private List<String> se3WordLinkedWithDependencyPathsSe3Se2 = new ArrayList<>();
//se1 WordNet synsets
//se2 WordNet synsets
//se1 WordNet hypernyms
//se2 WordNet hypernyms
//se1 srl
//se2 srl
//se3 srl
private List<String> sharedGeneralInquirerClasses = new ArrayList<>();
private List<String> sharedVerbNetClasses = new ArrayList<>();
private String orderOfElements = "";
//order as "r3-r2-r1"
private String distanceSe1Se2 = "";
private String distanceSe1Se3 = "";
private String distanceSe2Se3 = "";
private String binnedDistanceSe1Se2Se3 = "";
//se 1 Types
//se 2 Types
//se 3 Types
//se 1 Roles
//se 2 Roles
//se 3 Roles
public void setUniFV(Doc document, SpatialRelation sr) throws IOException {
int sentence = -1;
//add elements extracted in previous sieves here
//setting the map makes it easier to determine the order of the spatial elements in text
Map<Integer, SpatialElement> startOffsetSpatialElement = new TreeMap<>();
String[] roles = sr.rolesString.split("\\-");
if (sr.se1 != null) {
sr.se1.role = roles[0];
startOffsetSpatialElement.put(sr.se1.start, sr.se1);
sentence = document.startOffsetIndexedWord.get(sr.se1.start).sentIndex();
}
if (sr.se2 != null) {
sr.se2.role = sr.se1 == null ? roles[0] : roles[1];
startOffsetSpatialElement.put(sr.se2.start, sr.se2);
sentence = document.startOffsetIndexedWord.get(sr.se2.start).sentIndex();
}
if (sr.se3 != null) {
sr.se3.role = roles[roles.length-1];
startOffsetSpatialElement.put(sr.se3.start, sr.se3);
}
SemanticGraph graph = document.sentenceDependencyGraph.get(sentence);
Map<Integer, IndexedWord> startOffsetIndexedWord = document.startOffsetIndexedWord;
this.concatenatedLemmaStr = getConcatLemmaStr(sr.se1, sr.se2, sr.se3);
this.concatenatedWordStr = getConcatWordStr(sr.se1, sr.se2, sr.se3);
this.lexicalPatternStr = getLexicalPatternStr(startOffsetIndexedWord, startOffsetSpatialElement);
this.wordsInBetween = getWordsInBetween(startOffsetIndexedWord, startOffsetSpatialElement);
this.wordsOfSe3 = getWordsOfSpatialElement(sr.se3);
this.dependencyPathsSe1Se3Se2 = getDependencyPaths(sr.se1, sr.se3, sr.se2, startOffsetIndexedWord, graph);
this.dependencyPathsSe1Se2 = getDependencyPaths(sr.se1, sr.se2, startOffsetIndexedWord, graph);
this.dependencyPathsSe3Se2 = getDependencyPaths(sr.se3, sr.se2, startOffsetIndexedWord, graph);
this.se3WordLinkedWithDependencyPathsSe3Se2 = getWordLinkedDependencyPaths(sr.se3, sr.se2, startOffsetIndexedWord, graph);
this.sharedGeneralInquirerClasses = getSharedGeneralInquirerCategories(sr.se1, sr.se2);
this.sharedVerbNetClasses = getSharedVerbNetClasses(sr.se1, sr.se2);
this.orderOfElements = getOrderOfElementsInText(sr.se1, sr.se2, sr.se3, startOffsetSpatialElement);
this.distanceSe1Se2 = getDistanceBetweenSpatialElements(sr.se1, sr.se2);
this.distanceSe1Se3 = getDistanceBetweenSpatialElements(sr.se1, sr.se3);
this.distanceSe2Se3 = getDistanceBetweenSpatialElements(sr.se2, sr.se3);
this.binnedDistanceSe1Se2Se3 = getBinnedDistance(distanceSe1Se2, distanceSe1Se3, distanceSe2Se3);
//add elements extracted in preceding sieves
if (!sr.type.equals("LINK") && !sr.type.equals("MOVELINK") && !SpatialRelation.ORDERED_SIEVES.isEmpty()) {
List<String> precedingSieves = SpatialRelation.getPrecedingSieves(sr.type);
Map<String, List<String>> roleOtherElement = Main.train ? document.triggerMoverRoleOtherElements.get(document.filename+"-"+sr.se1.id+"-"+sr.se2.id) :
SpatialRelation.fileTriggerMoverRoleOtherElement.get(document.filename+"-"+sr.se1.id+"-"+sr.se2.id);
if (!precedingSieves.isEmpty() && roleOtherElement != null) {
for (String precedingSieve : precedingSieves) {
if (!roleOtherElement.containsKey(precedingSieve))
continue;
List<String> otherElements = roleOtherElement.get(precedingSieve);
for (String otherElement : otherElements) {
SpatialElement se = document.idSpatialElement.get(otherElement);
se = !se.role.toUpperCase().equals(precedingSieve) ? new SpatialElement(precedingSieve.toLowerCase(), se.start, se.end, se.startToken, se.endToken) : se;
startOffsetSpatialElement.put(se.start, se);
}
}
}
}
this.parseStringFeature = document.sentenceParseTree.get(sentence).getParseTreeFeature(startOffsetSpatialElement, document.sentenceTokenNumStartOffset.get(sentence), startOffsetIndexedWord);
}
/**
* Gets concatenated lemma strings of the spatial elements.
*
* @param se1 is spatial element posited in the first role of the relation triplet.
* @param se2 is spatial element posited in the second role of the relation triplet.
* @param se3 is spatial element posited in the third role of the relation triplet.
* @return String which is the concatenated lemma string of the spatial elements.
*/
public static String getConcatLemmaStr(SpatialElement se1, SpatialElement se2, SpatialElement se3) {
String concatLemmaStr = se1 == null ? "null" : se1.lemmaText;
concatLemmaStr += se2 == null ? "-null" : "-"+se2.lemmaText;
concatLemmaStr += se3 == null ? "-null" : "-"+se3.lemmaText;
return concatLemmaStr;
}
/**
* Get concatenated word strings of the spatial elements.
*
* @param se1 is spatial element posited in the first role of the relation triplet.
* @param se2 is spatial element posited in the second role of the relation triplet.
* @param se3 is spatial element posited in the third role of the relation triplet.
* @return String which is the concatenated word string of the spatial elements.
*/
public static String getConcatWordStr(SpatialElement se1, SpatialElement se2, SpatialElement se3) {
String concatWordStr = se1 == null ? "null" : se1.text;
concatWordStr += se2 == null ? "-null" : "-"+se2.text;
concatWordStr += se3 == null ? "-null" : "-"+se3.text;
return concatWordStr;
}
/**
* Gets lexical pattern containing spatial element roles and words in between.
*
* @param startOffsetIndexedWord is a map containing all tokens of the document
* to which the spatial element belongs.
* @param startOffsetSpatialElement is a sorted map linking the starting offset positions
* of the two or three spatial elements to the spatial elements.
* @return String which is the lexical pattern.
*/
public static String getLexicalPatternStr(Map<Integer, IndexedWord> startOffsetIndexedWord,
Map<Integer, SpatialElement> startOffsetSpatialElement) {
String lexicalPattern = "";
int start = -1;
int end = -1;
for (int startOffset : startOffsetSpatialElement.keySet()) {
SpatialElement se = startOffsetSpatialElement.get(startOffset);
if (start == -1)
start = se.end;
else if (end == -1) {
end = se.start;
String substring = "";
int i = start;
while (i < end) {
if (!startOffsetIndexedWord.containsKey(i)) {
i++;
continue;
}
IndexedWord iw = startOffsetIndexedWord.get(i);
substring += iw.value()+" ";
i++;
}
substring = substring.trim();
if (!substring.equals(""))
lexicalPattern += "_"+substring;
start = se.end;
end = -1;
}
lexicalPattern = lexicalPattern.equals("") ? se.role : lexicalPattern+"_"+se.role;
}
return lexicalPattern;
}
/**
* Gets a list containing all words in between the spatial elements.
*
* @param startOffsetIndexedWord is a map which links the starting offset positions
* of the tokens in the text to Stanford CoreNLP IndexedWord objects of the tokens.
* @param startOffsetSpatialElement is a sorted map linking the starting offset positions
* of the two or three spatial elements to the spatial element objects.
* @return list of words in between the spatial elements.
*/
public static List<String> getWordsInBetween(Map<Integer, IndexedWord> startOffsetIndexedWord, Map<Integer, SpatialElement> startOffsetSpatialElement) {
List<String> wordsInBetweenList = new ArrayList<>();
int start = -1;
int end = -1;
for (int startOffset : startOffsetSpatialElement.keySet()) {
SpatialElement se = startOffsetSpatialElement.get(startOffset);
if (start == -1)
start = se.end;
else if (end == -1) {
end = se.start;
for (int i = start; i < end; i++) {
if (!startOffsetIndexedWord.containsKey(i))
continue;
wordsInBetweenList = setList(wordsInBetweenList, startOffsetIndexedWord.get(i).value());
}
start = se.end;
end = -1;
}
}
return wordsInBetweenList;
}
/**
* Gets a list of all words of a spatial element.
*
* @param se the spatial element's words to return
* @return list of all words of the spatial element.
*/
public static List<String> getWordsOfSpatialElement(SpatialElement se) {
List<String> wordsOfSpatialElement = new ArrayList<>();
if (se == null)
return wordsOfSpatialElement;
String[] spatialElementWordsArr = se.text.split("\\s+");
for (String spatialElementWord : spatialElementWordsArr)
wordsOfSpatialElement = setList(wordsOfSpatialElement, spatialElementWord);
return wordsOfSpatialElement;
}
/**
* Get dependency paths between three spatial elements.
*
* @param firstSEOnPath is the first spatial element on the path.
* @param secondSEOnPath is the second spatial element on the path.
* @param thirdSEOnPath is the third spatial element on the path.
* @param startOffsetIndexedWord is a map which links the starting offset positions
* of the tokens in the text to Stanford CoreNLP IndexedWord objects of the tokens.
* @param graph is the dependency graph
* @return dependency paths between the three elements on the path.
*/
public static List<String> getDependencyPaths(SpatialElement firstSEOnPath, SpatialElement secondSEOnPath, SpatialElement thirdSEOnPath,
Map<Integer, IndexedWord> startOffsetIndexedWord, SemanticGraph graph) {
List<String> dependencyPaths = new ArrayList<>();
if (secondSEOnPath == null)
return dependencyPaths;
else if (thirdSEOnPath == null) {
int[] offsets1 = new int[2]; offsets1[0] = firstSEOnPath.start; offsets1[1] = firstSEOnPath.end;
int[] offsets2 = new int[2]; offsets2[0] = secondSEOnPath.start; offsets2[1] = secondSEOnPath.end;
dependencyPaths = StanfordParser.getDependencyPaths(offsets1, offsets2, startOffsetIndexedWord, graph);
}
else if (firstSEOnPath == null) {
int[] offsets1 = new int[2]; offsets1[0] = secondSEOnPath.start; offsets1[1] = secondSEOnPath.end;
int[] offsets2 = new int[2]; offsets2[0] = thirdSEOnPath.start; offsets2[1] = thirdSEOnPath.end;
dependencyPaths = StanfordParser.getDependencyPaths(offsets1, offsets2, startOffsetIndexedWord, graph);
}
else {
int[] offsets1 = new int[2]; offsets1[0] = firstSEOnPath.start; offsets1[1] = firstSEOnPath.end;
int[] offsets2 = new int[2]; offsets2[0] = secondSEOnPath.start; offsets2[1] = secondSEOnPath.end;
int[] offsets3 = new int[2]; offsets3[0] = thirdSEOnPath.start; offsets3[1] = thirdSEOnPath.end;
dependencyPaths = StanfordParser.getDependencyPaths(offsets1, offsets2, offsets3, startOffsetIndexedWord, graph);
}
return dependencyPaths;
}
/**
* Get dependency paths between two spatial elements.
*
* @param firstSEOnPath is the first spatial element.
* @param secondSEOnPath is the second spatial element.
* @param startOffsetIndexedWord is a map which links the starting offset positions
* of the tokens in the text to Stanford CoreNLP IndexedWord objects of the tokens.
* @param graph is the dependency graph.
* @return dependency paths between the two elements on the path.
*/
public static List<String> getDependencyPaths(SpatialElement firstSEOnPath, SpatialElement secondSEOnPath,
Map<Integer, IndexedWord> startOffsetIndexedWord, SemanticGraph graph) {
List<String> dependencyPaths = new ArrayList<>();
if (firstSEOnPath == null || secondSEOnPath == null)
return dependencyPaths;
int[] offsets1 = new int[2]; offsets1[0] = firstSEOnPath.start; offsets1[1] = firstSEOnPath.end;
int[] offsets2 = new int[2]; offsets2[0] = secondSEOnPath.start; offsets2[1] = secondSEOnPath.end;
dependencyPaths = StanfordParser.getDependencyPaths(offsets1, offsets2, startOffsetIndexedWord, graph);
return dependencyPaths;
}
/**
* Get dependency paths between two spatial elements with the first element's word linked to the paths.
*
* @param firstSEOnPath is the first spatial element.
* @param secondSEOnPath is the second spatial element
* @param startOffsetIndexedWord is a map which links the starting offset positions
* of the tokens in the text to Stanford CoreNLP IndexedWord objects of the tokens.
* @param graph is the dependency graph.
* @return dependency paths between two spatial elements with the first element's word linked to the paths.
*/
public static List<String> getWordLinkedDependencyPaths(SpatialElement firstSEOnPath, SpatialElement secondSEOnPath,
Map<Integer, IndexedWord> startOffsetIndexedWord, SemanticGraph graph) {
List<String> dependencyPaths = new ArrayList<>();
if (firstSEOnPath == null || secondSEOnPath == null)
return dependencyPaths;
int[] offsets1 = new int[2]; offsets1[0] = firstSEOnPath.start; offsets1[1] = firstSEOnPath.end;
int[] offsets2 = new int[2]; offsets2[0] = secondSEOnPath.start; offsets2[1] = secondSEOnPath.end;
Map<String, List<String>> wordLinkedDependencyPaths = StanfordParser.getWordLinkedDependencyPaths(offsets1, offsets2, true, startOffsetIndexedWord, graph);
for (String word : wordLinkedDependencyPaths.keySet()) {
List<String> paths = wordLinkedDependencyPaths.get(word);
for (String path : paths) {
if (dependencyPaths.contains(word+"-"+path))
continue;
dependencyPaths.add(word+"-"+path);
}
}
return dependencyPaths;
}
/**
* Get General Inquirer categories in common between the General Inquirer categories of two spatial elements.
*
* @param se1 is the first spatial element.
* @param se2 is the second spatial element.
* @return share General Inquirer categories between two spatial elements.
*/
public static List<String> getSharedGeneralInquirerCategories(SpatialElement se1, SpatialElement se2) {
List<String> sharedGeneralInquirerCategories = new ArrayList<>();
if (se1 == null || se2 == null || (se1.generalInquirerCategories.isEmpty() && se2.generalInquirerCategories.isEmpty()))
return sharedGeneralInquirerCategories;
sharedGeneralInquirerCategories.addAll(se1.generalInquirerCategories);
sharedGeneralInquirerCategories.retainAll(se2.generalInquirerCategories);
return sharedGeneralInquirerCategories;
}
/**
* Get verbnet classes in common between the verbnet classes of two spatial elements.
*
* @param se1 is the first spatial element.
* @param se2 is the second spatial element.
* @return shared verbnet classes between two spatial elements.
*/
public static List<String> getSharedVerbNetClasses(SpatialElement se1, SpatialElement se2) {
List<String> sharedVerbNetClasses = new ArrayList<>();
if (se1 == null || se2 == null || (se1.verbNetClasses.isEmpty() && se2.verbNetClasses.isEmpty()))
return sharedVerbNetClasses;
sharedVerbNetClasses.addAll(se1.verbNetClasses);
sharedVerbNetClasses.retainAll(se2.verbNetClasses);
return sharedVerbNetClasses;
}
/**
* Get order of spatial elements in text.
*
* @param se1 is the first participant in the relation.
* @param se2 is the second participant in the relation.
* @param se3 is the third participant in the relation.
* @param startOffsetSpatialElement is a sorted map linking the starting offset positions
* of the two or three spatial elements to the spatial element objects.
* @return String reflecting the order of the spatial elements.
*/
public static String getOrderOfElementsInText(SpatialElement se1, SpatialElement se2, SpatialElement se3,
Map<Integer, SpatialElement> startOffsetSpatialElement) {
String orderOfElements = "";
for (int startOffset : startOffsetSpatialElement.keySet()) {
SpatialElement se = startOffsetSpatialElement.get(startOffset);
String participant = se1 != null && se1.start == se.start ? "r1" :
se2 != null && se2.start == se.start ? "r2" : "r3";
orderOfElements = orderOfElements.equals("") ? participant : orderOfElements+"-"+participant;
}
return orderOfElements;
}
/**
* Gets the relative distance between two spatial elements.
*
* @param se1 is the first spatial element.
* @param se2 is the second spatial element.
* @return String the relative distance between the spatial elements.
*/
public static String getDistanceBetweenSpatialElements(SpatialElement se1, SpatialElement se2) {
if (se1 == null || se2 == null)
return "null";
String distance = se1.startToken < se2.startToken ?
Integer.toString(se2.startToken - se1.endToken) :
Integer.toString(se1.startToken - se2.endToken);
distance = se1.startToken < se2.startToken ? "-"+distance : distance;
return distance;
}
/**
* Gets concatenated string of binned distances between SE1, SE2, and SE3.
*
* @param se1Se2 relative distance between SE1 and SE2.
* @param se1Se3 relative distance between SE1 and SE3.
* @param se2Se3 relative distance between SE2 and SE3.
* @return String with binned distances.
*/
public static String getBinnedDistance(String se1Se2, String se1Se3, String se2Se3) {
String se1Se2Bound = se1Se2.equals("null") ? "null" : getBound(Integer.parseInt(se1Se2));
String se1Se3Bound = se1Se3.equals("null") ? "null" : getBound(Integer.parseInt(se1Se3));
String se2Se3Bound = se2Se3.equals("null") ? "null" : getBound(Integer.parseInt(se2Se3));
return se1Se2Bound+"_"+se1Se3Bound+"_"+se2Se3Bound;
}
/**
* Gets the binned upper bound of the value from bins of size 10.
*
* @param value to get binned bound for.
* @return String binned upper bound of the value from bins of size 10.
*/
public static String getBound(int value) {
String bound = "";
int temp_bound = -1;
int prev_temp_bound = -1;
for (int i = 1; i <= BIN_BOUNDS_MAP.size(); i++) {
temp_bound = BIN_BOUNDS_MAP.get(i);
if (i == 1) {
if (value <= temp_bound) {
bound = Integer.toString(temp_bound);
break;
}
}
else if (i == BIN_BOUNDS_MAP.size() && (value > temp_bound)) {
bound = ">80";
break;
}
else if (value > prev_temp_bound && value <= temp_bound) {
bound = Integer.toString(temp_bound);
break;
}
prev_temp_bound = temp_bound;
}
return bound;
}
/**
* Sets list with values.
*
* @param list to set.
* @param values to add to list.
* @return List with values added.
*/
public static List<String> setList (List<String> list, List<String> values) {
for (String value : values)
list = setList(list, value);
return list;
}
/**
* Sets list with value.
*
* @param list to set.
* @param value to add.
* @return List with value added.
*/
public static List<String> setList (List<String> list, String value) {
if (!list.contains(value))
list.add(value);
return list;
}
/**
* Sets universal features lists.
*
* @param sr is the spatial relation object with features to add to the features lists.
*/
public static void setUniFeatureLists(SpatialRelation sr) {
concatenatedLemmaStrs = setList(concatenatedLemmaStrs, sr.features.concatenatedLemmaStr);
concatenatedWordStrs = setList(concatenatedWordStrs, sr.features.concatenatedWordStr);
lexicalPatternStrs = setList(lexicalPatternStrs, sr.features.lexicalPatternStr);
inBetweenWords = setList(inBetweenWords, sr.features.wordsInBetween);
se3Words = setList(se3Words, sr.features.wordsOfSe3);
if (sr.se3 != null)
se3Phrases = setList(se3Phrases, sr.se3.text.toLowerCase().replaceAll("\\s+", " "));
se1Se3Se2DependencyPaths = setList(se1Se3Se2DependencyPaths, sr.features.dependencyPathsSe1Se3Se2);
se1Se2DependencyPaths = setList(se1Se2DependencyPaths, sr.features.dependencyPathsSe1Se2);
se3Se2DependencyPaths = setList(se3Se2DependencyPaths, sr.features.dependencyPathsSe3Se2);
se3WordLinkedWithSe3Se2DependencyPaths = setList(se3WordLinkedWithSe3Se2DependencyPaths, sr.features.se3WordLinkedWithDependencyPathsSe3Se2);
allSharedGeneralInquirerClasses = setList(allSharedGeneralInquirerClasses, sr.features.sharedGeneralInquirerClasses);
allSharedVerbNetClasses = setList(allSharedVerbNetClasses, sr.features.sharedVerbNetClasses);
ordersOfElements = setList(ordersOfElements, sr.features.orderOfElements);
distancesBetweenSpatialElements = setList(distancesBetweenSpatialElements, sr.features.distanceSe1Se2);
distancesBetweenSpatialElements = setList(distancesBetweenSpatialElements, sr.features.distanceSe1Se3);
distancesBetweenSpatialElements = setList(distancesBetweenSpatialElements, sr.features.distanceSe2Se3);
binnedDistances = setList(binnedDistances, sr.features.binnedDistanceSe1Se2Se3);
setUniFeaturesLists(sr.se1, true);
setUniFeaturesLists(sr.se2, true);
setUniFeaturesLists(sr.se3, false);
}
/**
* Sets spatial element specific universal feature lists.
*
* @param se is the spatial element.
* @param se1OrSe2 flag indicating whether it is the first or second spatial element.
*/
public static void setUniFeaturesLists(SpatialElement se, boolean se1OrSe2) {
if (se == null)
return;
if (se1OrSe2) {
allWordNetSynsets = setList(allWordNetSynsets, se.synsets);
allWordNetHypernyms = setList(allWordNetHypernyms, se.hypernyms);
}
allSRLs = setList(allSRLs, se.srls);
elementsTypes = setList(elementsTypes, se.type);
elementsRoles = setList(elementsRoles, se.roles);
}
/**
* clears all feature lists
*/
public static void clearFeatureLists() {
concatenatedLemmaStrs = new ArrayList<>();
concatenatedWordStrs = new ArrayList<>();
lexicalPatternStrs = new ArrayList<>();
inBetweenWords = new ArrayList<>();
se3Words = new ArrayList<>();
se3Phrases = new ArrayList<>();
se1Se3Se2DependencyPaths = new ArrayList<>();
se1Se2DependencyPaths = new ArrayList<>();
se3Se2DependencyPaths = new ArrayList<>();
se3WordLinkedWithSe3Se2DependencyPaths = new ArrayList<>();
allSharedGeneralInquirerClasses = new ArrayList<>();
allSharedVerbNetClasses = new ArrayList<>();
ordersOfElements = new ArrayList<>();
distancesBetweenSpatialElements = new ArrayList<>();
distancesBetweenSpatialElements = new ArrayList<>();
distancesBetweenSpatialElements = new ArrayList<>();
binnedDistances = new ArrayList<>();
allWordNetSynsets = new ArrayList<>();
allWordNetHypernyms = new ArrayList<>();
allSRLs = new ArrayList<>();
elementsTypes = new ArrayList<>();
elementsRoles = new ArrayList<>();
}
/**
* Sets universal features sizes.
*/
public static void setUniFeaturesSizes() {
endF1 = concatenatedLemmaStrs.size()+1; //concat lemma strings
endF2 = endF1+concatenatedWordStrs.size()+1; //concat word strings
endF3 = endF2+lexicalPatternStrs.size()+1; //lexical pattern
endF4 = endF3+inBetweenWords.size()+1; //words in between
endF5 = endF4+se3Words.size()+1; //SE3's words
endF6 = endF5+2+1; //SE2 seen as SE3 or either are absent
endF7 = endF6+se1Se3Se2DependencyPaths.size()+1; //dependency from SE1 to SE3 to SE2
endF8 = endF7+se1Se2DependencyPaths.size()+1; //dependency from SE1 to SE2
endF9 = endF8+se3Se2DependencyPaths.size()+1; //dependency from SE3 to SE2
endF10 = endF9+se3WordLinkedWithSe3Se2DependencyPaths.size()+1; //paths from SE3 to SE2 with SE3's string
endF11 = endF10+2+1; //about prep objects or absent
endF12 = endF11+allWordNetSynsets.size()+1; //wordnet synsets of SE1
endF13 = endF12+allWordNetSynsets.size()+1; //wordnet synsets of SE2
endF14 = endF13+allWordNetHypernyms.size()+1; //wordnet hypernyms of SE1
endF15 = endF14+allWordNetHypernyms.size()+1; //wordnet hypernyms of SE2
endF16 = endF15+allSRLs.size()+1; //srl of SE1
endF17 = endF16+allSRLs.size()+1; //srl of SE2
endF18 = endF17+allSRLs.size()+1; //srl of SE3
endF19 = endF18+allSharedGeneralInquirerClasses.size()+1; //GI categories shared by SE1 and SE2
endF20 = endF19+allSharedVerbNetClasses.size()+1; //VerbNet classes shared by SE1 and SE2
endF21 = endF20+ordersOfElements.size()+1; //order of participants
endF22 = endF21+2; //a specific order: yes or no
endF23 = endF22+distancesBetweenSpatialElements.size()+1; //distanceSe1Se2
endF24 = endF23+distancesBetweenSpatialElements.size()+1; //distanceSe1Se3
endF25 = endF24+distancesBetweenSpatialElements.size()+1; //distanceSe2Se3
endF26 = endF25+binnedDistances.size()+1; //binnedDistanceSe1Se2Se3
endF27 = endF26+elementsTypes.size()+1; //spatial element type of SE1
endF28 = endF27+elementsTypes.size()+1; //spatial element type of SE2
endF29 = endF28+elementsTypes.size()+1; //spatial element type of SE3
endF30 = endF29+elementsRoles.size()+1; //spatial element role of SE1
endF31 = endF30+elementsRoles.size()+1; //spatial element role of SE2
endF32 = endF31+elementsRoles.size()+1; //spatial element role of SE3
}
/**
* Gets an svm-style feature for a single elementFeature.
*
* @param begin index for a feature-type
* @param features list of values from training data of a specific feature type
* @param elementFeature
* @param end index for a feature-type
* @return String svm-style feature.
*/
public static String getFeature(int begin, List<String> features, String elementFeature, int end) {
return features.contains(elementFeature) ? Integer.toString(begin+features.indexOf(elementFeature)+1)+":1" : Integer.toString(end)+":1";
}
/**
* Gets svm-style features for a list of elementFeatures.
*
* @param begin index for a feature-type
* @param features list of values from training data of a specific feature type
* @param elementFeatures
* @param end index for a feature-type
* @return String svm-style features.
*/
public static String getFeature(int begin, List<String> features, List<String> elementFeatures, int end) {
List<Integer> elementFeatureIndexes = new ArrayList<>();
for (String elementFeature : elementFeatures) {
if (!features.contains(elementFeature)) {
if (!elementFeatureIndexes.contains(end))
elementFeatureIndexes.add(end);
continue;
}
int featureIndex = begin+features.indexOf(elementFeature)+1;
if (!elementFeatureIndexes.contains(featureIndex))
elementFeatureIndexes.add(featureIndex);
}
Collections.sort(elementFeatureIndexes);
String featureString = "";
for (int elementFeatureIndex : elementFeatureIndexes)
featureString += elementFeatureIndex+":1 ";
featureString = featureString.trim();
return featureString;
}
/**
* Gets svm-style feature string for a given relation instance.
*
* @param sr SpatialRelation object to generate features for.
* @return svm-style feature string.
*/
public String toString(SpatialRelation sr) {
return
"|BT| "+parseStringFeature+" |ET| "+
getFeature(0, concatenatedLemmaStrs, concatenatedLemmaStr, endF1) + " " +
getFeature(endF1, concatenatedWordStrs, concatenatedWordStr, endF2) + " " +
getFeature(endF2, lexicalPatternStrs, lexicalPatternStr, endF3) + " " +
getFeature(endF3, inBetweenWords, wordsInBetween, endF4) + " " +
getFeature(endF4, se3Words, wordsOfSe3, endF5) + " " +
(sr.se2 == null ? endF6+":1" : se3Phrases.contains(sr.se2.text.toLowerCase().replaceAll("\\s+", " ")) ? Integer.toString(endF5+1)+":1" : Integer.toString(endF5+2)+":1") + " " +
getFeature(endF6, se1Se3Se2DependencyPaths, dependencyPathsSe1Se3Se2, endF7) + " " +
getFeature(endF7, se1Se2DependencyPaths, dependencyPathsSe1Se2, endF8) + " " +
getFeature(endF8, se3Se2DependencyPaths, dependencyPathsSe3Se2, endF9) + " " +
getFeature(endF9, se3WordLinkedWithSe3Se2DependencyPaths, se3WordLinkedWithDependencyPathsSe3Se2, endF10) + " " +
//F11about prep objects + " " +
(sr.se1 == null ? endF12+":1" : getFeature(endF11, allWordNetSynsets, sr.se1.synsets, endF12)) + " " +
(sr.se2 == null ? endF13+":1" : getFeature(endF12, allWordNetSynsets, sr.se2.synsets, endF13)) + " " +
(sr.se1 == null ? endF14+":1" : getFeature(endF13, allWordNetHypernyms, sr.se1.hypernyms, endF14)) + " " +
(sr.se2 == null ? endF15+":1" : getFeature(endF14, allWordNetHypernyms, sr.se2.hypernyms, endF15)) + " " +
(sr.se1 == null ? endF16+":1" : getFeature(endF15, allSRLs, sr.se1.srls, endF16)) + " " +
(sr.se2 == null ? endF17+":1" : getFeature(endF16, allSRLs, sr.se2.srls, endF17)) + " " +
(sr.se3 == null ? endF18+":1" : getFeature(endF17, allSRLs, sr.se3.srls, endF18)) + " " +
getFeature(endF18, allSharedGeneralInquirerClasses, sharedGeneralInquirerClasses, endF19) + " " +
getFeature(endF19, allSharedVerbNetClasses, sharedVerbNetClasses, endF20) + " " +
getFeature(endF20, ordersOfElements, orderOfElements, endF21) + " " +
(orderOfElements.equals("r3-r2-r1") ? Integer.toString(endF21+1)+":1" : endF22+":1") + " " +
getFeature(endF22, distancesBetweenSpatialElements, distanceSe1Se2, endF23) + " " +
getFeature(endF23, distancesBetweenSpatialElements, distanceSe1Se3, endF24) + " " +
getFeature(endF24, distancesBetweenSpatialElements, distanceSe2Se3, endF25) + " " +
getFeature(endF25, binnedDistances, binnedDistanceSe1Se2Se3, endF26) + " " +
(sr.se1 == null ? endF27+":1" : getFeature(endF26, elementsTypes, sr.se1.type, endF27)) + " " +
(sr.se2 == null ? endF28+":1" : getFeature(endF27, elementsTypes, sr.se2.type, endF28)) + " " +
(sr.se3 == null ? endF29+":1" : getFeature(endF28, elementsTypes, sr.se3.type, endF29)) + " " +
(sr.se1 == null ? endF30+":1" : getFeature(endF29, elementsRoles, sr.se1.roles, endF30)) + " " +
(sr.se2 == null ? endF31+":1" : getFeature(endF30, elementsRoles, sr.se2.roles, endF31)) + " " +
(sr.se3 == null ? endF32+":1" : getFeature(endF31, elementsRoles, sr.se3.roles, endF32)) +" |EV|";
}
public static List<String> concatenatedLemmaStrs = new ArrayList<>();
public static List<String> concatenatedWordStrs = new ArrayList<>();
public static List<String> lexicalPatternStrs = new ArrayList<>();
public static List<String> inBetweenWords = new ArrayList<>();
public static List<String> se3Words = new ArrayList<>();
public static List<String> se3Phrases = new ArrayList<>();
public static List<String> se1Se3Se2DependencyPaths = new ArrayList<>();
public static List<String> se1Se2DependencyPaths = new ArrayList<>();
public static List<String> se3Se2DependencyPaths = new ArrayList<>();
public static List<String> se3WordLinkedWithSe3Se2DependencyPaths = new ArrayList<>();
public static List<String> allWordNetSynsets = new ArrayList<>();
public static List<String> allWordNetHypernyms = new ArrayList<>();
public static List<String> allSRLs = new ArrayList<>();
public static List<String> allSharedGeneralInquirerClasses = new ArrayList<>();
public static List<String> allSharedVerbNetClasses = new ArrayList<>();
public static List<String> ordersOfElements = new ArrayList<>();
public static List<String> distancesBetweenSpatialElements = new ArrayList<>();
public static List<String> binnedDistances = new ArrayList<>();
public static List<String> elementsTypes = new ArrayList<>();
public static List<String> elementsRoles = new ArrayList<>();
public static final Map<Integer, Integer> BIN_BOUNDS_MAP;
static {
Map<Integer, Integer> aMap = new HashMap<>();
aMap.put(1, -80);
aMap.put(2, -70);
aMap.put(3, -60);
aMap.put(4, -50);
aMap.put(5, -40);
aMap.put(6, -30);
aMap.put(7, -20);
aMap.put(8, -10);
aMap.put(9, 0);
aMap.put(10, 10);
aMap.put(11, 20);
aMap.put(12, 30);
aMap.put(13, 40);
aMap.put(14, 50);
aMap.put(15, 60);
aMap.put(16, 70);
aMap.put(17, 80);
BIN_BOUNDS_MAP = Collections.unmodifiableMap(aMap);
}
public static int endF1; //concat lemma strings
public static int endF2; //concat word strings
public static int endF3; //lexical pattern
public static int endF4; //words in between
public static int endF5; //SE3's words
public static int endF6; //SE2 seen as SE3
public static int endF7; //dependency from SE1 to SE3 to SE2
public static int endF8; //dependency from SE1 to SE2
public static int endF9; //dependency from SE3 to SE2
public static int endF10; //paths from SE3 to SE2 with SE3's string
public static int endF11; //about prep objects
public static int endF12; //wordnet synsets of SE1
public static int endF13; //wordnet synsets of SE2
public static int endF14; //wordnet hypernyms of SE1
public static int endF15; //wordnet hypernyms of SE2
public static int endF16; //srl of SE1
public static int endF17; //srl of SE2
public static int endF18; //srl of SE3
public static int endF19; //GI categories shared by SE1 and SE2
public static int endF20; //VerbNet classes shared by SE1 and SE2
public static int endF21; //order of participants
public static int endF22; //a specific order
public static int endF23; //distanceSe1Se2
public static int endF24; //distanceSe1Se3
public static int endF25; //distanceSe2Se3
public static int endF26; //binnedDistanceSe1Se2Se3
public static int endF27; //spatial element type of SE1
public static int endF28; //spatial element type of SE2
public static int endF29; //spatial element type of SE3
public static int endF30; //spatial element role of SE1
public static int endF31; //spatial element role of SE2
public static int endF32; //spatial element role of SE3
}
|
package hw1;
public class PrintTest2 {
public static void main(String[] args) {
}
}
|
package sax;
import java.io.*;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/*
* Crea un programa que devuelva el número de discos registrados en
“discoteca.xml” de un determinado autor que le pasamos por consola. Si el
autor carece de discos en el archivo, el programa devolverá un mensaje del
estilo: “El autor <xxxxxx> no aparece en el archivo.
*/
public class SAX4 {
static BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
public static void main (String [] args) throws FileNotFoundException, IOException, SAXException {
String nom = "";
System.out.print("Quin es el nom de l'autor? ");
nom=buffer.readLine();
XMLReader procesadorXML = XMLReaderFactory.createXMLReader();
GestionContenido gestor = new GestionContenido(nom);
procesadorXML.setContentHandler(gestor);
InputSource fileXML = new InputSource ("discoteca.xml");
procesadorXML.parse(fileXML);
}
}
class GestionContenido extends DefaultHandler {
private String nom;
public int cont=0;
public GestionContenido(String nom){
super();
this.nom=nom;
}
public void startDocument() {
System.out.println("Comienzo del documento XML");
}
public void endDocument(){
System.out.println("Final del documento XML");
if (cont==0) {
System.out.println("El autor "+nom+" no tiene ningún cd en el disco");
}
else {
System.out.println("El autor "+nom+" tiene "+cont+" cds en el disco");
}
}
public void startElement (String uri, String nombre, String nombreC, Attributes atts) {
System.out.printf("\tPrincipio Elemento: %s %n", nombre);
}
public void endElement (String uri, String nombre, String nombreC){
System.out.printf("\tFin Elemento: %s %n",nombre);
}
public void characters(char[] ch, int inicio, int longitud) throws SAXException {
String car = new String (ch, inicio, longitud);
car = car.replaceAll("[\t\n]","");
System.out.printf("\tCaracteres: %s %n", car);
if(car.equals(nom)) {
cont ++;
}
}
}
|
package com.shangdao.phoenix.entity.customer;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.shangdao.phoenix.entity.entityManager.EntityManager;
import com.shangdao.phoenix.entity.interfaces.IBaseEntity;
import com.shangdao.phoenix.entity.state.State;
import com.shangdao.phoenix.entity.user.User;
@Entity
@Table(name = "evaluation")
public class Evaluation implements IBaseEntity{
/**
*
*/
@Transient
public static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@ManyToOne
@JoinColumn(name = "entity_manager_id")
private EntityManager entityManager;
@Column(name = "name")
private String name;
@Column(name = "deleted_at")
@JsonIgnore
private Date deletedAt;
@ManyToOne
@JoinColumn(name = "state_id")
private State state;
@Column(name = "created_at")
@JsonIgnore
private Date createdAt;
@ManyToOne
@JoinColumn(name = "created_by")
@JsonIgnore
private User createdBy;
@Column(name = "content")
private String content;
@Column(name = "evaluate_at")
private Date evaluateAt;
@ManyToOne
@JoinColumn(name = "customer_id")
private Customer customer;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Date deletedAt) {
this.deletedAt = deletedAt;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getEvaluateAt() {
return evaluateAt;
}
public void setEvaluateAt(Date evaluateAt) {
this.evaluateAt = evaluateAt;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
|
import java.util.Vector;
public class B4Integertest {
public static void main(String[] args) {
Vector v=new Vector();
/*
v.add(new Integer(10));
v.add(new Integer(20));
v.add(new Integer(30));*/
v.add(10); //jdk5 auto-boxing
v.add(20);
v.add(30);
/* int tot=0;
for(int i=0; i<v.size(); i++)
{
tot+=((Integer)v.get(i)).intValue();
}*/
int tot=0;
for(int i=0; i<v.size(); i++)
{
tot+=(Integer)v.get(i); //auto-unboxing
}
System.out.println(tot);
}
}
|
package com.weathair.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.weathair.entities.forum.Post;
import com.weathair.entities.forum.Topic;
/**
* @author MIACHELL
*
* Interface PostRepository for CRUD into Post table
*
*/
public interface PostRepository extends JpaRepository<Post, Integer> {
List<Post> findByTopic(Topic topic);
}
|
package logic;
import java.io.Serializable;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.TemporalAmount;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import collections.BiPredicateMultiMap;
import collections.MultiMap;
/**
* This class is used to store course information retrieved from the Scraper so
* that it can later be manipulated and scheduled
*/
public class Course implements Serializable, Comparable<Course>, Iterable<List<LocalTime[]>> {
/**
* This is used for Serializable compatibility
*/
private static final long serialVersionUID = 8126578523819110122L;
/**
* The int used for tracking the crn, this is used to sign up for the class
*/
private int crn;
/**
* The string used to track what department the class is part of
*/
private String subject;
/**
* This is the "level" of the course, like 3141
*/
private String courseCode;
/**
* Since some courses have a variable amount of credits this will store that
*/
private double[] credits;
/**
* The name of the course like "Team Software Project"
*/
private String title;
/**
* An array that corresponds to the days the course is on. This directly
* correlates with the start/endTime lists.
*/
private ArrayList<String> days;
/**
* An array that corresponds to the time the course starts. This directly
* correlates with the day/endTime lists.
*/
private ArrayList<LocalTime> startTime;
/**
* An array that corresponds to the time the course ends. This directly
* correlates with the day/startTime lists.
*/
private ArrayList<LocalTime> endTime;
/**
* The remaining spots that the class has
*/
private int remaining;
/**
* The instructor that teaches this course
*/
private String instructor;
/**
* The date that the course starts on
*/
private LocalDate startDate;
/**
* The date that the course ends on
*/
private LocalDate endDate;
/**
* The fee of the course
*/
private double fee;
/**
* If the course in question is a lab, used for the toString
*/
private boolean isLab;
/**
* This is the minimum amount of time between classes before they're considered
* to be overlapping I. E. This is a total of 5 minutes between classes
*/
private final TemporalAmount travelTime = Duration.ofMinutes(5);
/**
* Represents the LocalTime object to be used if the class time cannot be parsed
* or is TBA
*/
public static final LocalTime TBA_TIME = parseTime("1:37 am");
/**
* Represents the Date object to be used if the class date cannot be parsed or
* is TBA
*/
public static final LocalDate TBA_DATE = LocalDate.MIN;
/**
* Creates a course based on the information provided. Some strings are expected
* to be in a certain format, the format will be given
*
* @param CRN The CRN for the course, this is used for signing up for the
* class
* @param subject The department the class is in
* @param courseCode The class number, I.E. 3141 for the course
* @param isLab Is this course a lab course?
* @param credits The number of credits the class is worth
* @param title The name of the class I.E. "Team Software Project"
* @param days The days that the class is held
* @param time The times that the class is held. Must be in format h1:m1
* a/pm1-h2:m2 a/pm2
* @param remaining The amount of spots remaining within the class
* @param instructor The instructor for the class
* @param date The dates that the class is held. Must be in format
* M1/D1-M2/D2|YEAR
* @param fee The fee to take the class
*/
public Course(String CRN, String subject, String courseCode, boolean isLab, List<Double> credits, String title, String days, String time, String remaining, String instructor, String date, double fee) {
this.days = new ArrayList<>();
this.startTime = new ArrayList<>();
this.endTime = new ArrayList<>();
this.crn = Integer.parseInt(CRN);
this.subject = subject;
this.courseCode = courseCode;
this.credits = new double[credits.size()];
for (int i = 0; i < credits.size(); i++) {
this.credits[i] = credits.get(i);
}
this.title = title;
this.days.add(days);
String[] timeSplit = time.split("-");
if (!time.equals("TBA")) {
startTime.add(parseTime(timeSplit[0]));
endTime.add(parseTime(timeSplit[1]));
} else {
startTime.add(TBA_TIME); // This will be the TBA time
endTime.add(TBA_TIME);
}
this.remaining = Integer.parseInt(remaining);
this.instructor = instructor;
String[] dateSplit1 = date.split("-");
String[] dateSpllt2 = date.split("\\|");
startDate = parseDate(dateSplit1[0] + "/" + dateSpllt2[1]);
endDate = parseDate(dateSplit1[1].split("\\|")[0] + "/" + dateSpllt2[1]);
this.fee = fee;
this.isLab = isLab;
}
/**
* Returns the CRN, as an int
*
* @return The CRN
*/
public int getCRN() {
return crn;
}
/**
* Returns the subject string representation
*
* @return The subject, i.e. "MA", "CS", etc.
*/
public String getSubject() {
return subject;
}
/**
* Returns the course code
*
* @return MA1161 -> 1161
*/
public String getCourseCode() {
return courseCode;
}
/**
* Returns the amount of credits the class is worth.
*
* @return Most times this array is only of size 1, sometimes it is of size 2
* for variable credit classes.
*/
public double[] getCredits() {
return credits;
}
/**
* Gets the days that the class is held on in full string representation.
*
* @return The days the class is held in an unmodifiable list.
*/
public List<String> getDays() {
ArrayList<String> result = new ArrayList<>(6);
if (!this.days.contains("TBA") || !this.days.contains(" ")) {
for (String day : days) {
if (day.contains("M")) {
result.add("MO");
}
if (day.contains("T")) {
result.add("TU");
}
if (day.contains("W")) {
result.add("WE");
}
if (day.contains("R")) {
result.add("TH");
}
if (day.contains("F")) {
result.add("FR");
}
}
}
return Collections.unmodifiableList(result.stream().distinct().collect(Collectors.toList())); // Create an immutable list that has duplicates removed
}
/**
* Returns the first day of the week the class takes place in a DayOfWeek enum
*
* @return The DayOfWeek enum for the first day
*/
public DayOfWeek firstDay() {
List<String> days = getDays();
String day = days.get(0);
if (day.equals("MO")) {
return DayOfWeek.MONDAY;
} else if (day.equals("TU")) {
return DayOfWeek.TUESDAY;
} else if (day.equals("WE")) {
return DayOfWeek.WEDNESDAY;
} else if (day.equals("TH")) {
return DayOfWeek.THURSDAY;
} else {
return DayOfWeek.FRIDAY;
}
}
/**
* Returns the start time corresponding the the i'th index
*
* @param i The index
* @return Returns a LocalTime object for that class start time
*/
public LocalTime getStartTime(int i) {
return startTime.get(i);
}
/**
* Returns the end time corresponding the the i'th index
*
* @param i The index
* @return Returns a LocalTime object for that class end time
*/
public LocalTime getEndTime(int i) {
return endTime.get(i);
}
/**
* Returns the amount of spots left in the class
*
* @return An int of the amount of spots
*/
public int getRemaining() {
return remaining;
}
/**
* Returns the instructor for the course
*
* @return The instructor, as a String
*/
public String getInstructor() {
return instructor;
}
/**
* This is the date that the class starts on, most (if not all, I'm not sure)
* start on the first day of the semester
*
* @return A date representing the start date of class
*/
public LocalDate getStartDate() {
return startDate;
}
/**
* This is the date that the class ends, classes can be half or full semesters
* (and maybe more, not sure).
*
* @return A date representing the end date of class
*/
public LocalDate getEndDate() {
return endDate;
}
/**
* The fee that it costs to take this class, typically applies to lab courses
*
* @return The fee as an int
*/
public double getFee() {
return fee;
}
/**
* Some classes happen at different times on different days Or maybe they have
* multiple class sessions in the same day, this is for adding the additional
* times for those classes.
*
* @param dayAndTimes Must be in format DAYS(MTWRF)|h1:m1 a/pm1-h2:m2 a/pm2
*/
public void addDayandTime(String dayAndTimes) {
String[] data = dayAndTimes.split("\\|");
days.add(data[0]);
String[] timeSplit = data[1].split("-");
if (!data[1].equals("TBA")) {
startTime.add(parseTime(timeSplit[0]));
endTime.add(parseTime(timeSplit[1]));
} else {
startTime.add(TBA_TIME);
endTime.add(TBA_TIME);
}
}
/**
* Returns the times that the class takes place on that day (start and end).
*
* @param day The day, this is the single character string representation
* @return A list of LocalTime[]'s in which arr[0] = start time and arr[1] = end
* time
*/
public List<LocalTime[]> getTimes(String day) {
ArrayList<LocalTime[]> result = new ArrayList<>();
for (int i = 0; i < days.size(); i++) {
if (days.get(i).contains(day)) {
result.add(new LocalTime[] { startTime.get(i), endTime.get(i) });
}
}
return Collections.unmodifiableList(result);
}
/**
* The method that front facing users call to test if courses conflict. This
* method is to make sure that x.conflicts(y) is equal to y.conflicts(x) because
* of the implementation of the conflicts method is is not reflexive.
*
* @param other The other course to check conflicts with
* @return Returns a boolean based on if a course conflicts with the other
*/
public boolean conflicts(Course other) {
return this.conflictsHelper(other) || other.conflictsHelper(this);
}
/**
* This tests to see if two courses conflict with each other. A conflict is
* defined as a course and other that has overlapping dates, overlapping days,
* as well as overlapping times. A conflict also occurs if there is not at least
* 5 minutes in between classes, but this is configurable.
*
* @param other The other course to check conflicts with
* @return Returns a boolean based on if a course conflicts with the other
*/
private boolean conflictsHelper(Course other) {
if (datesConflict(this.startDate, this.endDate, other.startDate, other.endDate)) {
for (Course.CourseTimeIterator thisTimes = (Course.CourseTimeIterator) this.iterator(); thisTimes.hasNext();) {
for (LocalTime[] thisTime : thisTimes.next()) {
for (LocalTime[] otherTime : other.getTimes(thisTimes.getDay())) {
if (timesConflict(thisTime[0], thisTime[1], otherTime[0], otherTime[1]) || travelTimeConflict(thisTime[0], thisTime[1], otherTime[0], otherTime[1])) {
return true;
}
}
}
}
return false;
} else {
return false; // Can't conflict if classes don't happen during same dates
}
}
/**
* I could have made this into 1 big if statement, but I think that this is
* better as it's easier to read
*
* @param startDate1 The first start date
* @param endDate1 The first end date
* @param startDate2 The second start date
* @param endDate2 The second end date
* @return Return true if the classes overlap in any way date wise.
*/
private boolean datesConflict(LocalDate startDate1, LocalDate endDate1, LocalDate startDate2, LocalDate endDate2) {
if (startDate1.isAfter(startDate2) && startDate1.isBefore(endDate2)) { // First class starts in middle of second class
return true;
} else if (endDate1.isAfter(startDate2) && endDate1.isBefore(endDate2)) { // Second class starts in middle of first class
return true;
} else if (endDate1.equals(startDate2)) { // First class ends when second class starts
return true;
} else if (startDate1.equals(endDate2)) { // First class starts when second class ends
return true;
} else if (startDate1.isBefore(startDate2) && endDate1.isAfter(endDate2)) { // First class starts before and ends after the second class
return true;
} else if (startDate1.isAfter(startDate2) && endDate1.isBefore(endDate2)) { // First class starts after and ends before the second class
return true;
} else { // First class starts and ends at the same date as the second class
return startDate1.equals(startDate2) && endDate1.equals(endDate2);
}
}
/**
* I could have made this into 1 big if statement, but I think that this is
* better as it's easier to read
*
* @param startDate1 The first start time
* @param endDate1 The first end time
* @param startDate2 The second start time
* @param endDate2 The second end time
* @return Return true if the classes overlap in any way time wise.
*/
private boolean timesConflict(LocalTime startTime1, LocalTime endTime1, LocalTime startTime2, LocalTime endTime2) {
if (startTime1.equals(TBA_TIME) || endTime1.equals(TBA_TIME) || startTime2.equals(TBA_TIME) || endTime2.equals(TBA_TIME)) { // Is the time TBA? Just assume it doesn't conflict
return false;
} else if (startTime1.isAfter(startTime2) && startTime1.isBefore(endTime2)) { // First class starts in middle of second class
return true;
} else if (endTime1.isAfter(startTime2) && endTime1.isBefore(endTime2)) { // Second class starts in middle of first class
return true;
} else if (endTime1.equals(startTime2)) { // First class ends when second class starts
return true;
} else if (startTime1.equals(endTime2)) { // First class starts when second class ends
return true;
} else if (startTime1.isBefore(startTime2) && endTime1.isAfter(endTime2)) { // First class starts before and ends after the second class
return true;
} else if (startTime1.isAfter(startTime2) && endTime1.isBefore(endTime2)) { // First class starts after and ends before the second class
return true;
} else { // First class starts and ends at the same time as the second class
return startTime1.equals(startTime2) && endTime1.equals(endTime2);
}
}
/**
* I could have made this into 1 big if statement, but I think that this is
* better as it's easier to read
*
* @param startDate1 The first start time
* @param endDate1 The first end time
* @param startDate2 The second start time
* @param endDate2 The second end time
* @return Return true if the classes overlap after accounting for travel time.
*/
private boolean travelTimeConflict(LocalTime startTime1, LocalTime endTime1, LocalTime startTime2, LocalTime endTime2) {
return timesConflict(startTime1.plus(travelTime), endTime1.plus(travelTime), startTime2, endTime2) || timesConflict(startTime1, endTime1, startTime2.minus(travelTime), endTime2.minus(travelTime));
}
/**
*
* @param date Must be in format MM/dd/yyyy
* @return Returns a LocalDate object representing the date the class takes
* place. If an exception occurs parsing the date it will instead return
* 1/1/1970 00:00:00
*/
private LocalDate parseDate(String date) {
return LocalDate.parse(date, DateTimeFormatter.ofPattern("MM/dd/yyyy"));
}
/**
*
* @param time Must be in format HH:mm am/pm
* @return Returns a LocalTime object that signifies that time to the class
* takes place
*/
private static LocalTime parseTime(String time) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("h:mm a").toFormatter(Locale.ENGLISH);
return LocalTime.parse(time, formatter);
}
/**
* If the class takes place at different times in the same week
*
* @return A boolean if the class doesn't always happen at the same time
*/
public boolean isSplitClass() {
return days.size() > 1;
}
/**
* Tells if the class takes place on a TBA date or TBA time.
*
* @return A boolean if the class is TBA on any date/time.
*/
public boolean isTBAClass() {
boolean TBA = getStartDate().equals(Course.TBA_DATE) || getEndDate().equals(Course.TBA_DATE);
for (int i = 0; i < startTime.size(); i++) {
TBA = TBA || startTime.get(i).equals(Course.TBA_TIME) || endTime.get(i).equals(Course.TBA_TIME);
}
return TBA;
}
/**
* Returns a string representation for a course object. This will be the
* department followed by the course number followed by the course name, I.E.
* CS3141 - Team Software Project, and if the class is a lab it will have "Lab"
* appended to the end of it.
*
* @return Returns the string representation of the class
*/
@Override
public String toString() {
return subject + courseCode + " - " + title + (isLab ? " Lab" : ""); // Appends lab to the end if the course is a lab
}
/**
* Compares a class based on the amount of sections that are available for the
* class in the Scraper, I.E. the Scraper.getAllCourses must be run first!
*/
@Override
public int compareTo(Course other) {
return Scraper.getLast().get(this.toString()).size() - Scraper.getLast().get(other.toString()).size();
}
/**
* Returns an iterator that allows you to iterate through the times that the
* class takes place on that day starting from Monday and going through Friday
*/
@Override
public Iterator<List<LocalTime[]>> iterator() {
return new CourseTimeIterator();
}
/**
* This iterator goes through each day in the week and will return to you the
* times that the class takes place on that day.
*
* @author MagneticZero
*
*/
public class CourseTimeIterator implements Iterator<List<LocalTime[]>> {
/**
* The days the iterator has to go through still, in reverse order to save
* computation power of removing an element from an array list
*/
private ArrayList<String> days = new ArrayList<>(Arrays.asList("FIL", "F", "R", "W", "T", "M"));
/**
* The current day the iterator is on
*/
private String day = "M";
/**
* Returns a boolean based on if there are still days to iterate through
*
* @return Is there any days left to iterate through?
*/
@Override
public boolean hasNext() {
return !days.isEmpty() || day.equals("F");
}
/**
* Returns the times that the class is held on the next element's day
*
* @return
*/
@Override
public List<LocalTime[]> next() {
if (hasNext()) {
List<LocalTime[]> result = getTimes(days.get(days.size() - 1));
day = days.remove(days.size() - 1);
return result;
} else {
throw new NoSuchElementException();
}
}
/**
* Returns the current day that the iterator is on
*
* @return The day the iterator is on
*/
public String getDay() {
return day;
}
/**
* Returns the current day in RRule format that the iterator is on
*
* @return The day the iterator is on
*/
public String getRRuleDay() {
if (day.equals("M")) {
return "MO";
} else if (day.equals("T")) {
return "TU";
} else if (day.equals("W")) {
return "WE";
} else if (day.equals("R")) {
return "TH";
} else {
return "FR";
}
}
/**
* Gets the current day the iterator is on as a DayOfWeek enum
*
* @return The DayOfWeek enum representing the day the iterator is on
*/
public DayOfWeek getDayEnum() {
if (day.equals("M")) {
return DayOfWeek.MONDAY;
} else if (day.equals("T")) {
return DayOfWeek.TUESDAY;
} else if (day.equals("W")) {
return DayOfWeek.WEDNESDAY;
} else if (day.equals("R")) {
return DayOfWeek.THURSDAY;
} else {
return DayOfWeek.FRIDAY;
}
}
}
/**
* Returns a BiPredicateMultiMap that maps an array of courses to the other
* courses in conflicts with
*
* @param <T> The Course or subclass of Course type
* @param courses The array of courses
* @return A BiPredicateMultiMap representing the conflicts
*/
public static MultiMap<Course, Course> getConflicts(Course[] courses) {
BiPredicateMultiMap<Course> map = new BiPredicateMultiMap<>((x, y) -> x.conflicts(y));
for (Course course : courses) {
map.put(course);
}
return map;
}
/**
* Returns a BiPredicateMultiMap that maps a collection of courses to the other
* courses in conflicts with
*
* @param <T> The Course or subclass of Course type
* @param courses The collection of courses
* @return A BiPredicateMultiMap representing the conflicts
*/
public static MultiMap<Course, Course> getConflicts(Collection<Course> courses) {
return getConflicts(courses.toArray(new Course[courses.size()]));
}
}
|
package com.androidbook.networking;
import java.net.MalformedURLException;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;
public class FourthNetworkAsync extends Activity {
TextSwitcher mStatus = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mStatus = (TextSwitcher) findViewById(R.id.status);
mStatus.setFactory(new ViewSwitcher.ViewFactory() {
public View makeView() {
TextView tv = new TextView(FourthNetworkAsync.this);
tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
tv.setTextSize(24);
return tv;
}
});
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
mStatus.setInAnimation(in);
mStatus.setOutAnimation(out);
mStatus.setText("<no status>");
Button go = (Button) findViewById(R.id.do_action);
go.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
new ImageLoader().execute(new URL("http://api.flickr.com/services/feeds/photos_public.gne?id=26648248@N04&lang=en-us&format=atom"));
} catch (MalformedURLException e) {
Log.e("Net", "Failed to generate URL");
}
}
});
}
private class ImageLoader extends AsyncTask<URL, String, String> {
@Override
protected String doInBackground(URL... params) {
// although this pattern takes more than one param, we'll just use
// the first
try {
URL text = params[0];
XmlPullParserFactory parserCreator;
parserCreator = XmlPullParserFactory.newInstance();
XmlPullParser parser = parserCreator.newPullParser();
parser.setInput(text.openStream(), null);
publishProgress("Parsing...");
int imgCount = 0;
int parserEvent = parser.getEventType();
while (parserEvent != XmlPullParser.END_DOCUMENT) {
switch (parserEvent) {
case XmlPullParser.START_TAG:
String tag = parser.getName();
if (tag.compareTo("link") == 0) {
String relType = parser.getAttributeValue(null, "rel");
if (relType.compareTo("enclosure") == 0) {
String encType = parser.getAttributeValue(null, "type");
if (encType.startsWith("image/")) {
String imageSrc = parser.getAttributeValue(null, "href");
Log.i("Net", "image source = " + imageSrc);
final int curImageCount = ++imgCount;
publishProgress("imgCount = " + curImageCount);
}
}
}
break;
}
parserEvent = parser.next();
}
} catch (Exception e) {
Log.e("Net", "Failed in parsing XML", e);
return "Finished with failure.";
}
return "Done...";
}
protected void onCancelled() {
Log.e("Net", "Async task Cancelled");
}
protected void onPostExecute(String result) {
mStatus.setText(result);
}
protected void onPreExecute() {
mStatus.setText("About to load URL");
}
protected void onProgressUpdate(String... values) {
// just one value, please
mStatus.setText(values[0]);
super.onProgressUpdate(values);
}
}
}
|
// O. Bittel
// 19.9.2011
package aufgabe1.dictionary;
import java.util.List;
public interface Dictionary<K,V> {
public static class Element<K, V> {
public K key;
public V value;
public Element() {
super();
}
public Element(K key, V value) {
super();
this.key = key;
this.value = value;
}
}
V insert(K key, V value);
// Associates the specified value with the specified key in this map.
// If the map previously contained a mapping for the key,
// the old value is replaced by the specified value.
// Returns the previous value associated with key,
// or null if there was no mapping for key.
V search(K key);
// Returns the value to which the specified key is mapped,
// or null if this map contains no mapping for the key.
V remove(K key);
// Removes the key-vaue-pair associated with the key.
// Returns the value to which the key was previously associated,
// or null if the key is not contained in the dictionary.
List<Element<K, V>> getEntries();
}
|
package com.tfg.hipersch;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LoginActivity extends AppCompatActivity {
public final static String SHARED_PREF_NAME = "hipersch.SHARED_PREF";
public static final String EMAIL = "hipersch.EMAIL";
public static final String PASSWORD = "hipersch.PASSWORD";
private boolean emailVisited = false;
private boolean passwordVisited = false;
@BindView(R.id.email_field) TextInputEditText _emailText;
@BindView(R.id.email_layout) TextInputLayout _emailLayout;
@BindView(R.id.password) TextInputEditText _passwordText;
@BindView(R.id.password_layout) TextInputLayout _passwordLayout;
@BindView(R.id.login_button) MaterialButton _loginButton;
@BindView(R.id.register_message) TextView _registerMessage;
@BindView(R.id.progress_bar) ProgressBar _progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
_emailText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
if (!emailVisited) emailVisited = true;
} else {
if (emailVisited) validateEmail();
}
}
});
_passwordText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
if (!passwordVisited) passwordVisited = true;
} else {
if (passwordVisited) validatePassword();
}
}
});
_loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
login(v);
}
});
_registerMessage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), SignUpActivity.class);
startActivity(intent);
}
});
checkApiStatus();
}
public void login(View v) {
if (!validate()) {
onLoginFailed();
hideProgress();
return;
}
_loginButton.setEnabled(false);
showProgress();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
// Login
ApiService apiService = ServiceGenerator.createService(ApiService.class);
Call<ApiResponse> call = apiService.userLogin(email, password);
call.enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
if (response.isSuccessful()) {
ApiResponse apiResponse = response.body();
onLoginSuccess(v, apiResponse);
} else {
onLoginCredentialsFailure();
}
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
Log.d("Error:", t.getMessage());
onLoginFailed();
}
});
}
public void onLoginSuccess(View v, ApiResponse response) {
TokenManager.setToken(v.getContext(),response.getToken());
Intent intent = new Intent(v.getContext(), MainActivity.class);
if (response.getUserRole().equals("trainer")) {
intent = new Intent(v.getContext(), TrainerLogin.class);
}
intent.putExtra(EMAIL, _emailText.getText().toString());
intent.putExtra(PASSWORD, _passwordText.getText().toString());
startActivity(intent);
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Please, try again in a few seconds", Toast.LENGTH_LONG).show();
hideProgress();
_loginButton.setEnabled(true);
}
public void onLoginCredentialsFailure() {
Toast.makeText(getBaseContext(), "Wrong credentials", Toast.LENGTH_LONG).show();
hideProgress();
_loginButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailLayout.setError("Enter a valid email address");
valid = false;
} else {
_emailLayout.setError(null);
}
if (password.isEmpty() || password.length() < 4) {
_passwordLayout.setError("Must have more than 4 characters");
valid = false;
} else {
_passwordLayout.setError(null);
}
return valid;
}
public boolean validateEmail() {
boolean valid = true;
String email = _emailText.getText().toString();
if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailLayout.setError("Enter a valid email address");
valid = false;
} else {
_emailLayout.setError(null);
}
return valid;
}
public boolean validatePassword() {
boolean valid = true;
String password = _passwordText.getText().toString();
if (password.isEmpty() || password.length() < 6) {
_passwordLayout.setError("Must have more than 6 characters");
valid = false;
} else {
_passwordLayout.setError(null);
}
return valid;
}
public void showProgress() {
_progressBar.setVisibility(View.VISIBLE);
_registerMessage.setVisibility(View.INVISIBLE);
}
public void hideProgress() {
_progressBar.setVisibility(View.INVISIBLE);
_registerMessage.setVisibility(View.VISIBLE);
}
public void checkApiStatus() {
ApiService apiService = ServiceGenerator.createService(ApiService.class);
Call<ApiResponse> call = apiService.getApiStatus();
call.enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
System.out.println("Api response received");
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
Log.d("Error:", t.getMessage());
}
});
}
}
|
package fr.eni.poo.tp.transporteur.bo;
public interface Livrable {
// METHODE QUI NE PREND AUCUN PARAMETRES (PARENTHESE VIDE) ET RENVOIE FLOAT :
float getTarifLivraison();
}
|
package com.ebanq.web.pageobjects.profiles;
import com.codeborne.selenide.Condition;
import com.ebanq.web.pageobjects.BasePage;
import org.openqa.selenium.By;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.open;
import static com.ebanq.web.other.Urls.*;
public class BaseProfilesPage extends BasePage {
public static final String CREATE_BTN_CSS = ".plus";
public static final String CREATE_PROFILE_BUTTON_CSS = ".def-btn-success";
public static final String PAGE_HEADER_CSS = ".page-name";
@Override
public BaseProfilesPage isPageOpened() {
$(ACTIVE_PAGE_CSS).waitUntil(Condition.visible, 30000);
return this;
}
public BaseProfilesPage openAdministratorProfiles() {
open(ADMIN_PROFILES_PAGE);
isPageOpened();
return this;
}
public BaseProfilesPage clickCreateNew() {
$(CREATE_BTN_CSS).click();
return this;
}
public BaseProfilesPage clickCreateProfile() {
$(CREATE_PROFILE_BUTTON_CSS).click();
return this;
}
}
|
package br.com.mixfiscal.prodspedxnfe.domain.sped;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
public class SPED0000 extends SPEDBase implements Serializable {
private static final long serialVersionUID = -7224068271691261662L;
private String codVer;
private String codFin;
private Date dataIni;
private Date dataFin;
private String nomeEmpresarialEntidade;
private String CNPJ;
private String CPF;
private String UF;
private String IE;
private String codMun;
private String IM;
private String suframa;
private String indPerfil;
private String indAtiv;
public SPED0000() {
this.getIndicesColunas().put("codVer", 2);
this.getIndicesColunas().put("codFin", 3);
this.getIndicesColunas().put("dataIni", 4);
this.getIndicesColunas().put("dataFin", 5);
this.getIndicesColunas().put("nomeEmpresarialEntidade", 6);
this.getIndicesColunas().put("CNPJ", 7);
this.getIndicesColunas().put("CPF", 8);
this.getIndicesColunas().put("UF", 9);
this.getIndicesColunas().put("IE", 10);
this.getIndicesColunas().put("codMun", 11);
this.getIndicesColunas().put("IM", 12);
this.getIndicesColunas().put("suframa", 13);
this.getIndicesColunas().put("indPerfil", 14);
this.getIndicesColunas().put("indAtiv", 15);
}
// <editor-fold desc="Getters e Setters" defaultstate="collapsed">
public String getCodVer() {
return codVer;
}
public void setCodVer(String codVer) {
this.codVer = codVer;
}
public String getCodFin() {
return codFin;
}
public void setCodFin(String codFin) {
this.codFin = codFin;
}
public Date getDataIni() {
return dataIni;
}
public void setDataIni(Date dataIni) {
this.dataIni = dataIni;
}
public Date getDataFin() {
return dataFin;
}
public void setDataFin(Date dataFin) {
this.dataFin = dataFin;
}
public String getNomeEmpresarialEntidade() {
return nomeEmpresarialEntidade;
}
public void setNomeEmpresarialEntidade(String nomeEmpresarialEntidade) {
this.nomeEmpresarialEntidade = nomeEmpresarialEntidade;
}
public String getCNPJ() {
return CNPJ;
}
public void setCNPJ(String CNPJ) {
this.CNPJ = CNPJ;
}
public String getCPF() {
return CPF;
}
public void setCPF(String CPF) {
this.CPF = CPF;
}
public String getUF() {
return UF;
}
public void setUF(String UF) {
this.UF = UF;
}
public String getIE() {
return IE;
}
public void setIE(String IE) {
this.IE = IE;
}
public String getCodMun() {
return codMun;
}
public void setCodMun(String codMun) {
this.codMun = codMun;
}
public String getIM() {
return IM;
}
public void setIM(String IM) {
this.IM = IM;
}
public String getSuframa() {
return suframa;
}
public void setSuframa(String suframa) {
this.suframa = suframa;
}
public String getIndPerfil() {
return indPerfil;
}
public void setIndPerfil(String indPerfil) {
this.indPerfil = indPerfil;
}
public String getIndAtiv() {
return indAtiv;
}
public void setIndAtiv(String indAtiv) {
this.indAtiv = indAtiv;
}
// </editor-fold>
// <editor-fold desc="equals e hashCode" defaultstate="collapsed">
@Override
public int hashCode() {
int hash = 5;
hash = 37 * hash + Objects.hashCode(this.codVer);
hash = 37 * hash + Objects.hashCode(this.codFin);
hash = 37 * hash + Objects.hashCode(this.dataIni);
hash = 37 * hash + Objects.hashCode(this.dataFin);
hash = 37 * hash + Objects.hashCode(this.nomeEmpresarialEntidade);
hash = 37 * hash + Objects.hashCode(this.CNPJ);
hash = 37 * hash + Objects.hashCode(this.CPF);
hash = 37 * hash + Objects.hashCode(this.UF);
hash = 37 * hash + Objects.hashCode(this.IE);
hash = 37 * hash + Objects.hashCode(this.codMun);
hash = 37 * hash + Objects.hashCode(this.IM);
hash = 37 * hash + Objects.hashCode(this.suframa);
hash = 37 * hash + Objects.hashCode(this.indPerfil);
hash = 37 * hash + Objects.hashCode(this.indAtiv);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final SPED0000 other = (SPED0000) obj;
if (!Objects.equals(this.codVer, other.codVer)) {
return false;
}
if (!Objects.equals(this.codFin, other.codFin)) {
return false;
}
if (!Objects.equals(this.nomeEmpresarialEntidade, other.nomeEmpresarialEntidade)) {
return false;
}
if (!Objects.equals(this.CNPJ, other.CNPJ)) {
return false;
}
if (!Objects.equals(this.CPF, other.CPF)) {
return false;
}
if (!Objects.equals(this.UF, other.UF)) {
return false;
}
if (!Objects.equals(this.IE, other.IE)) {
return false;
}
if (!Objects.equals(this.codMun, other.codMun)) {
return false;
}
if (!Objects.equals(this.IM, other.IM)) {
return false;
}
if (!Objects.equals(this.suframa, other.suframa)) {
return false;
}
if (!Objects.equals(this.indPerfil, other.indPerfil)) {
return false;
}
if (!Objects.equals(this.indAtiv, other.indAtiv)) {
return false;
}
if (!Objects.equals(this.dataIni, other.dataIni)) {
return false;
}
if (!Objects.equals(this.dataFin, other.dataFin)) {
return false;
}
return true;
}
// </editor-fold>
}
|
package com.cxxt.mickys.playwithme.model;
import com.cxxt.mickys.playwithme.model.bean.response.CodeResponse;
import com.cxxt.mickys.playwithme.model.bean.response.RegisterResponse;
import com.cxxt.mickys.playwithme.model.bean.response.ResponseResult;
import io.reactivex.Observable;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
/**
* ApiService
* API 连接契约
*
* @author huangyz0918
*/
public interface ApiService {
/**
* 获取短信验证码
*/
@FormUrlEncoded
@POST("identify")
Observable<ResponseResult<CodeResponse>> getAuthCode(@Field("phone") String phoneNum);
/**
* 使用短信验证码登录
*/
@FormUrlEncoded
@POST("login")
Observable<ResponseResult<RegisterResponse>> loginUsingCode(@Field("phone") String phoneNum,
@Field("code") String authCode);
/**
* 使用密码登录
*/
@FormUrlEncoded
@POST("login")
Observable<ResponseResult> loginUsingPasswd(@Field("phone") String phoneNum,
@Field("password") String password);
}
|
package cc.smh.dao;
import cc.smh.common.dao.IBaseDao;
public interface UserDAO extends IBaseDao {
}
|
package com.igs.util;
import com.hl.util.Constants;
import com.hl.util.LogUtils;
import com.igs.entity.req.ReqBodyBaseBean;
import com.igs.entity.rsp.BaseRsp;
import com.igs.entity.rsp.RspBodyLoginBean;
/**
* 类描述:
* 创建人:heliang
* 创建时间:2016/1/11 13:52
* 修改人:8153
* 修改时间:2016/1/11 13:52
* 修改备注:
*/
public class DebugInfoUtils {
public static void debugFailInfo(ReqBodyBaseBean req,BaseRsp response){
if(Constants.Config.DEVELOPER_MODE && response!=null && !response.getResultCode().equals(UrlManager.RSP_OK)){
LogUtils.d("失败描述:" + response.getResDes());
LogUtils.d("请求地址:"+req.getRequestUrl());
LogUtils.d("未加密参数:"+req.getNoEncodeParams());
LogUtils.d("已加密参数:"+req.getEncodeParams());
}
}
}
|
package com.ahav.reserve.pojo;
public class Result {
private int status = 400;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
@Override
public String toString() {
return "Result{" +
"status=" + status +
'}';
}
}
|
package beans;
import java.util.List;
import dao.BookDao;
import pojo.Book;
public class BookBean
{
private String subject;
private BookDao dao;
private List<Book> bookList;
public BookBean() throws Exception{
this.dao = new BookDao();
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<Book> getBookList() {
return bookList;
}
public void setBookList(List<Book> bookList) {
this.bookList = bookList;
}
public void fetchBooks()throws Exception
{
this.bookList = this.dao.getBooks(subject);
}
public void closeDao()throws Exception
{
this.dao.close();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package items;
import game.Constants;
import javax.swing.*;
import java.awt.*;
/**
*
* @author Nitesh
*/
public class Board extends Panel
{
private JLabel border[]= new JLabel[4];
private JLabel leg[]= new JLabel[4];
private JPanel sheet;
private Icon bamboo_v = new ImageIcon(Constants.imageFolder+"bamboo_v.jpg");
private Icon bamboo_h_u = new ImageIcon(Constants.imageFolder+"bamboo_h_u.jpg");
private Icon bamboo_h_b = new ImageIcon(Constants.imageFolder+"bamboo_h_b.jpg");
private Color cream = new Color(239,228,176);
private Grass g;
public JLabel text;
private JLabel apple;
//Counstructor
public Board(Container c,int x,int y)
{
sheet = new JPanel();
this.add(sheet);
sheet.setLayout(null);
sheet.setBounds(0,0,149,147);
sheet.setBackground(cream);
for(int i=0;i<2;i++)
{
leg[i]= new JLabel(bamboo_v);
sheet.add(leg[i]);
border[i] = new JLabel(bamboo_v);
sheet.add(border[i]);
}
border[2] = new JLabel(bamboo_h_u);
sheet.add(border[2]);
border[3] = new JLabel(bamboo_h_b);
sheet.add(border[3]);
leg[0].setBounds(40,115,11,100);
leg[1].setBounds(90,130,11,100);
border[0].setBounds(0,5,11,100);
border[1].setBounds(139,38,11,100);
border[2].setBounds(10,0,139,49);
border[3].setBounds(0,98,139,49);
//grass
g = new Grass(this,0,150);
//text
text = new JLabel("0");
sheet.add(text);
text.setBounds(80,10,100,100);
//apple
Icon apple_small= new ImageIcon(Constants.imageFolder+"apple_small.gif");
apple= new JLabel(apple_small);
sheet.add(apple);
apple.setBounds(20,10,80,100);
//legs
for(int i=2;i<4;i++)
{
leg[i] = new JLabel(bamboo_v);
this.add(leg[i]);
}
leg[2].setBounds(40,147,11,80);
leg[3].setBounds(90,147,11,110);
//board properties
setLayout(null);
setSize(149,270);
c.add(this);
this.setLocation(x,y);
}
}
|
package com.cinema.biz.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cinema.biz.dao.SimPcControlMapper;
import com.cinema.biz.model.SimPcControl;
import com.cinema.biz.model.base.TSimPcControl;
import com.cinema.biz.service.SimPcControlService;
@Service
public class SimPcControlServiceImpl implements SimPcControlService {
@Autowired
private SimPcControlMapper simPcControlDao;
/**列表*/
@Override
public List<SimPcControl> getList(Map<String, Object> paraMap) {
return simPcControlDao.getList(paraMap);
}
/**添加*/
@Override
public int insert(TSimPcControl t) {
return simPcControlDao.insertSelective(t);
}
/**更新*/
@Override
public int update(TSimPcControl t) {
return simPcControlDao.updateByPrimaryKeySelective(t);
}
/**删除*/
@Override
public int delete(String deviceId) {
return simPcControlDao.deleteByPrimaryKey(deviceId);
}
}
|
package com.amazonaws.models.nosql;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBAttribute;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBHashKey;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBIndexHashKey;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBIndexRangeKey;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBRangeKey;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBTable;
import java.util.List;
import java.util.Map;
import java.util.Set;
@DynamoDBTable(tableName = "resecure-mobilehub-1732438160-DeviceInformation")
public class DeviceInformationDO {
private String _userId;
@DynamoDBHashKey(attributeName = "userId")
@DynamoDBAttribute(attributeName = "userId")
public String getUserId() {
return _userId;
}
public void setUserId(final String _userId) {
this._userId = _userId;
}
}
|
package com.zhicai.byteera.activity.community.group;
import com.lidroid.xutils.db.annotation.Table;
import com.zhicai.byteera.commonutil.StringUtil;
import java.io.Serializable;
/** Created by bing on 2015/6/1. */
@Table(name = "GroupEntity")
public class GroupEntity implements Serializable,Comparable<GroupEntity>{
private int id;
private String groupId;
private String name;
private String avatarUrl;
private int peopleCnt;
// private boolean watched;
private String description;
private int dogntaiToadyCnt;
private int commentCnt;
private String chatGroupId;
private boolean joined;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getDogntaiToadyCnt() {
return dogntaiToadyCnt;
}
public void setDogntaiToadyCnt(int dogntaiToadyCnt) {
this.dogntaiToadyCnt = dogntaiToadyCnt;
}
public int getCommentCnt() {
return commentCnt;
}
public void setCommentCnt(int commentCnt) {
this.commentCnt = commentCnt;
}
public String getChatGroupId() {
return chatGroupId;
}
public void setChatGroupId(String chatGroupId) {
this.chatGroupId = chatGroupId;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public int getPeopleCnt() {
return peopleCnt;
}
public void setPeopleCnt(int peopleCnt) {
this.peopleCnt = peopleCnt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public boolean isJoined() {
return joined;
}
public void setJoined(boolean joined) {
this.joined = joined;
}
@Override
public String toString() {
return "GroupEntity{" +
"groupId='" + groupId + '\'' +
", name='" + name + '\'' +
", avatarUrl='" + avatarUrl + '\'' +
", peopleCnt=" + peopleCnt +
", description='" + description + '\'' +
", dogntaiToadyCnt=" + dogntaiToadyCnt +
", commentCnt=" + commentCnt +
", chatGroupId='" + chatGroupId + '\'' +
", joined=" + joined +
'}';
}
public GroupEntity() {
}
public GroupEntity(String groupId, String name, String avatarUrl, String description,int peopleCnt,boolean joined) {
this.groupId = groupId;
this.name = name;
this.avatarUrl = avatarUrl;
this.description = description;
this.peopleCnt = peopleCnt;
this.joined = joined;
}
public GroupEntity(String groupId, String name, String avatarUrl, String description,int peopleCnt) {
this.groupId = groupId;
this.name = name;
this.avatarUrl = avatarUrl;
this.description = description;
this.peopleCnt = peopleCnt;
}
public GroupEntity(String groupId, String name, String avatarUrl, String description,boolean joined) {
this.groupId = groupId;
this.name = name;
this.avatarUrl = avatarUrl;
this.description = description;
this.joined = joined;
}
@Override
public int compareTo(GroupEntity another) {
return StringUtil.getPinYinHeadChar(this.getName()).charAt(0) - StringUtil.getPinYinHeadChar(another.getName()).charAt(0);
}
}
|
// Copyright (C) 2016 The Android Open Source Project
//
// 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.google.reviewit;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.view.View;
import android.view.ViewGroup;
import com.google.gerrit.extensions.common.AccountInfo;
import com.google.reviewit.app.ApprovalData;
import com.google.reviewit.app.Change;
import com.google.reviewit.widget.ApprovalEntry;
import com.google.reviewit.widget.ApprovalsHeader;
import static com.google.reviewit.util.LayoutUtil.matchAndFixedLayout;
public class ApprovalsFragment extends PageFragment {
private Change change;
@Override
protected int getLayout() {
return R.layout.content_approvals;
}
@Override
public @StringRes int getTitle() {
return R.string.approvals_title;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ViewGroup approvalList = vg(R.id.approvalList);
ApprovalData approvalData = change.getApprovalData();
ApprovalsHeader reviewersHeader = new ApprovalsHeader(getContext());
reviewersHeader.init(change, getString(R.string.reviewers), true);
approvalList.addView(reviewersHeader);
addSeparator(approvalList);
for (AccountInfo account : approvalData.reviewers) {
ApprovalEntry approvalEntry = new ApprovalEntry(getContext());
approvalEntry.init(getApp(), change, account);
approvalList.addView(approvalEntry);
addSeparator(approvalList);
}
if (!approvalData.ccs.isEmpty()) {
ApprovalsHeader ccsHeader = new ApprovalsHeader(getContext());
ccsHeader.init(change, getString(R.string.ccs), false);
approvalList.addView(ccsHeader);
addSeparator(approvalList);
for (AccountInfo account : approvalData.ccs) {
ApprovalEntry approvalEntry = new ApprovalEntry(getContext());
approvalEntry.init(getApp(), change, account);
approvalList.addView(approvalEntry);
addSeparator(approvalList);
}
}
}
public void setChange(Change change) {
this.change = change;
}
private void addSeparator(ViewGroup viewGroup) {
View separator = new View(getContext());
separator.setLayoutParams(
matchAndFixedLayout(widgetUtil.dpToPx(1)));
separator.setBackgroundColor(widgetUtil.color(R.color.separator));
viewGroup.addView(separator);
}
}
|
package Revise.graphs;
import java.util.*;
public class Dijkstra {
static GraphAdjList graphAdjList = null;
public static void minDistanceDijkstra(String srcVertex, String endVertex) {
Node srcNode = graphAdjList.graph.get(srcVertex);
PriorityQueue<Node> pq = new PriorityQueue<>(new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return Double.compare(o1.minWeight, o2.minWeight);
}
});
srcNode.minWeight = 0;
pq.offer(srcNode);
while (!pq.isEmpty()) {
Node v = pq.poll();
for (Edge e : v.neighbours) {
Node edgeVertex = e.dest;
double totalWeight = v.minWeight + e.weight;
if (totalWeight < edgeVertex.minWeight) {
edgeVertex.minWeight = totalWeight;
edgeVertex.previous = v;
pq.offer(edgeVertex);
}
}
}
List<String> path = new ArrayList<>();
Node n = graphAdjList.graph.get(endVertex);
for (; n != null && !n.equals(srcNode); n = n.previous) {
path.add(n.label);
}
path.add(n.label);
Collections.reverse(path);
System.out.println(path);
}
public static void main(String[] args) throws Exception {
graphAdjList = new GraphAdjList(6);
graphAdjList.addVertex("A");
graphAdjList.addVertex("B");
graphAdjList.addVertex("C");
graphAdjList.addVertex("D");
graphAdjList.addVertex("E");
graphAdjList.graph.get("A").addEdge(10, graphAdjList.graph.get("B"));
graphAdjList.graph.get("A").addEdge(7, graphAdjList.graph.get("C"));
graphAdjList.graph.get("A").addEdge(3, graphAdjList.graph.get("E"));
graphAdjList.graph.get("B").addEdge(2, graphAdjList.graph.get("C"));
graphAdjList.graph.get("C").addEdge(2, graphAdjList.graph.get("D"));
graphAdjList.graph.get("D").addEdge(1, graphAdjList.graph.get("C"));
graphAdjList.graph.get("E").addEdge(2, graphAdjList.graph.get("C"));
graphAdjList.graph.get("E").addEdge(9, graphAdjList.graph.get("D"));
System.out.println(graphAdjList.graph);
minDistanceDijkstra("A", "C");
}
}
|
package com.logicbig.example;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("trades")
public class TradeController {
@RequestMapping("/{trade}")
public String handleTradeRequest (Trade trade, Model model) {
System.out.println(trade);
if (trade.getTradeId() == 0) {
model.addAttribute("msg", "No trade found");
return "no-trade-page";
}
return "trade-page";
}
}
|
package com.nisira.core.dao;
import com.nisira.core.entity.*;
import java.util.List;
import android.database.sqlite.SQLiteDatabase;
import com.nisira.core.database.DataBaseClass;
import android.content.ContentValues;
import android.database.Cursor;
import com.nisira.core.util.ClaveMovil;
import java.util.ArrayList;
import java.util.LinkedList;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Estructura_costos_clieprovDao extends BaseDao<Estructura_costos_clieprov> {
public Estructura_costos_clieprovDao() {
super(Estructura_costos_clieprov.class);
}
public Estructura_costos_clieprovDao(boolean usaCnBase) throws Exception {
super(Estructura_costos_clieprov.class, usaCnBase);
}
public Boolean insert(Estructura_costos_clieprov estructura_costos_clieprov) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ContentValues initialValues = new ContentValues();
initialValues.put("IDEMPRESA",estructura_costos_clieprov.getIdempresa());
initialValues.put("CODIGO",estructura_costos_clieprov.getCodigo());
initialValues.put("IDCLIEPROV",estructura_costos_clieprov.getIdclieprov());
initialValues.put("ESTADO",estructura_costos_clieprov.getEstado());
resultado = mDb.insert("ESTRUCTURA_COSTOS_CLIEPROV",null,initialValues)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
public Boolean update(Estructura_costos_clieprov estructura_costos_clieprov,String where) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ContentValues initialValues = new ContentValues();
initialValues.put("IDEMPRESA",estructura_costos_clieprov.getIdempresa()) ;
initialValues.put("CODIGO",estructura_costos_clieprov.getCodigo()) ;
initialValues.put("IDCLIEPROV",estructura_costos_clieprov.getIdclieprov()) ;
initialValues.put("ESTADO",estructura_costos_clieprov.getEstado()) ;
resultado = mDb.update("ESTRUCTURA_COSTOS_CLIEPROV",initialValues,where,null)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Boolean delete(String where) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
resultado = mDb.delete("ESTRUCTURA_COSTOS_CLIEPROV",where,null)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
public ArrayList<Estructura_costos_clieprov> listar(String where,String order,Integer limit) {
if(limit == null){
limit =0;
}
ArrayList<Estructura_costos_clieprov> lista = new ArrayList<Estructura_costos_clieprov>();
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
Cursor cur = mDb.query("ESTRUCTURA_COSTOS_CLIEPROV",
new String[] {
"IDEMPRESA" ,
"CODIGO" ,
"IDCLIEPROV" ,
"ESTADO"
},
where, null, null, null, order);
if (cur!=null){
cur.moveToFirst();
int i=0;
while (cur.isAfterLast() == false) {
int j=0;
Estructura_costos_clieprov estructura_costos_clieprov = new Estructura_costos_clieprov() ;
estructura_costos_clieprov.setIdempresa(cur.getString(j++));
estructura_costos_clieprov.setCodigo(cur.getString(j++));
estructura_costos_clieprov.setIdclieprov(cur.getString(j++));
estructura_costos_clieprov.setEstado(cur.getDouble(j++));
lista.add(estructura_costos_clieprov);
i++;
if(i == limit){
break;
}
cur.moveToNext();
}
cur.close();
}
} catch (Exception e) {
}finally {
mDb.close();
}
return lista;
}
}
|
package de.trispeedys.resourceplanning.delegate.requesthelp;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import de.trispeedys.resourceplanning.datasource.Datasources;
import de.trispeedys.resourceplanning.entity.Helper;
import de.trispeedys.resourceplanning.execution.BpmVariables;
import de.trispeedys.resourceplanning.service.AssignmentService;
import de.trispeedys.resourceplanning.util.StringUtil;
import de.trispeedys.resourceplanning.util.configuration.AppConfiguration;
public class CheckHelperConditionDelegate implements JavaDelegate
{
public void execute(DelegateExecution execution) throws Exception
{
/*
if (execution.getVariable(BpmVariables.RequestHelpHelper.VAR_HELPER_CODE) == null)
{
throw new ResourcePlanningException("helper code must not be NULL!!");
}
*/
AppConfiguration.getInstance();
Long helperId = (Long) execution.getVariable(BpmVariables.RequestHelpHelper.VAR_HELPER_ID);
Helper helper = (Helper) Datasources.getDatasource(Helper.class).findById(helperId);
boolean firstAssignment = AssignmentService.isFirstAssignment(helperId);
if ((firstAssignment) || (StringUtil.isBlank(helper.getEmail())))
{
execution.setVariable(
BpmVariables.RequestHelpHelper.VAR_SUPERVISION_REQUIRED,
true);
}
else
{
execution.setVariable(
BpmVariables.RequestHelpHelper.VAR_SUPERVISION_REQUIRED,
false);
}
//set mails attempts to 0
execution.setVariable(BpmVariables.RequestHelpHelper.VAR_MAIL_ATTEMPTS, 0);
}
}
|
/**
* This class will process all the information for the females
*
* @author Carlos
*/
public class Female extends HumanBeing implements Comparable<HumanBeing> {
private String lastDegree;
//Constructor
public Female(String name, int age, String lastDegree) throws notHumanBeingException {
super(name, age);
this.lastDegree = lastDegree;
this.setIntLvl();
if (this.getAge() >= 110) {
throw new notHumanBeingException(super.getAge());
}
}
//Methods
/**
* this method will return a String with the information of the person
*
* @return out
*/
public String toString() {
String out = "\n" + getClass().getName();
out += "\nName: " + super.getName() + "\n\tAge: " + super.getAge()
+ "\n\tLast Degree: " + this.lastDegree + "\n\tIntelligence Level: "
+ super.getIntLvl();
return out;
}
/**
* this method will calculate the intelligence level of a Female
*/
public void setIntLvl() {
if (lastDegree.equals("Ph.D.")) {
super.setIntLvl(5);
} else if (lastDegree.equals("MS")) {
super.setIntLvl(4);
} else if (lastDegree.equals("BS")) {
super.setIntLvl(3);
} else if (lastDegree.equals("AA")) {
super.setIntLvl(2);
} else {
super.setIntLvl(1);
}
}
//Setters
public void setLastDegree(String lastDegree) {
this.lastDegree = lastDegree;
}
//Getters
public String getLastDegree() {
return lastDegree;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.core.namedparam;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.lang.Nullable;
/**
* Class that provides helper methods for the use of {@link SqlParameterSource},
* in particular with {@link NamedParameterJdbcTemplate}.
*
* @author Thomas Risberg
* @author Juergen Hoeller
* @since 2.5
*/
public abstract class SqlParameterSourceUtils {
/**
* Create an array of {@link SqlParameterSource} objects populated with data
* from the values passed in (either a {@link Map} or a bean object).
* This will define what is included in a batch operation.
* @param candidates object array of objects containing the values to be used
* @return an array of {@link SqlParameterSource}
* @see MapSqlParameterSource
* @see BeanPropertySqlParameterSource
* @see NamedParameterJdbcTemplate#batchUpdate(String, SqlParameterSource[])
*/
public static SqlParameterSource[] createBatch(Object... candidates) {
return createBatch(Arrays.asList(candidates));
}
/**
* Create an array of {@link SqlParameterSource} objects populated with data
* from the values passed in (either a {@link Map} or a bean object).
* This will define what is included in a batch operation.
* @param candidates collection of objects containing the values to be used
* @return an array of {@link SqlParameterSource}
* @since 5.0.2
* @see MapSqlParameterSource
* @see BeanPropertySqlParameterSource
* @see NamedParameterJdbcTemplate#batchUpdate(String, SqlParameterSource[])
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static SqlParameterSource[] createBatch(Collection<?> candidates) {
SqlParameterSource[] batch = new SqlParameterSource[candidates.size()];
int i = 0;
for (Object candidate : candidates) {
batch[i] = (candidate instanceof Map map ? new MapSqlParameterSource(map) :
new BeanPropertySqlParameterSource(candidate));
i++;
}
return batch;
}
/**
* Create an array of {@link MapSqlParameterSource} objects populated with data from
* the values passed in. This will define what is included in a batch operation.
* @param valueMaps array of {@link Map} instances containing the values to be used
* @return an array of {@link SqlParameterSource}
* @see MapSqlParameterSource
* @see NamedParameterJdbcTemplate#batchUpdate(String, Map[])
*/
public static SqlParameterSource[] createBatch(Map<String, ?>[] valueMaps) {
SqlParameterSource[] batch = new SqlParameterSource[valueMaps.length];
for (int i = 0; i < valueMaps.length; i++) {
batch[i] = new MapSqlParameterSource(valueMaps[i]);
}
return batch;
}
/**
* Create a wrapped value if parameter has type information, plain object if not.
* @param source the source of parameter values and type information
* @param parameterName the name of the parameter
* @return the value object
* @see SqlParameterValue
*/
@Nullable
public static Object getTypedValue(SqlParameterSource source, String parameterName) {
int sqlType = source.getSqlType(parameterName);
if (sqlType != SqlParameterSource.TYPE_UNKNOWN) {
return new SqlParameterValue(sqlType, source.getTypeName(parameterName), source.getValue(parameterName));
}
else {
return source.getValue(parameterName);
}
}
/**
* Create a Map of case-insensitive parameter names together with the original name.
* @param parameterSource the source of parameter names
* @return the Map that can be used for case-insensitive matching of parameter names
*/
public static Map<String, String> extractCaseInsensitiveParameterNames(SqlParameterSource parameterSource) {
Map<String, String> caseInsensitiveParameterNames = new HashMap<>();
String[] paramNames = parameterSource.getParameterNames();
if (paramNames != null) {
for (String name : paramNames) {
caseInsensitiveParameterNames.put(name.toLowerCase(), name);
}
}
return caseInsensitiveParameterNames;
}
}
|
package com.hb.framework.business.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hb.framework.business.entity.Order;
import com.hb.framework.business.service.ProductService;
@Controller
@RequestMapping("/background/system/product")
public class ProductController {
@Autowired
private ProductService productService;
@RequestMapping("/query")
@ResponseBody
public List<Order> getProducts(HttpServletRequest request, String productCd) throws JSONException{
return productService.getProducts(request, productCd);
}
@RequestMapping("/queryMer")
@ResponseBody
public List<Order> getMerchant() throws JSONException{
return productService.getMerchant();
}
}
|
package com.rndapp.t.models.mbta;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
/**
* Created by ell on 2/7/15.
*/
public class MBTAMode {
@SerializedName("route_type")
private String mRouteType;
@SerializedName("route")
private ArrayList<MBTARoute> mRoutes;
public String getRouteType() {
return mRouteType;
}
public ArrayList<MBTARoute> getRoutes() {
return mRoutes;
}
}
|
package com.bistel.flink.function;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks;
import org.apache.flink.streaming.api.watermark.Watermark;
import com.bistel.tracereport.model.TraceReportInfo;
public class MyWatermarkEmitter implements AssignerWithPunctuatedWatermarks<Tuple4<String, String, TraceReportInfo, Long>> {
@Override
public long extractTimestamp(Tuple4<String, String, TraceReportInfo, Long> element, long previousElementTimestamp) {
// TODO Auto-generated method stub
return 0;
}
@Override
public Watermark checkAndGetNextWatermark(Tuple4<String, String, TraceReportInfo, Long> lastElement, long extractedTimestamp) {
// TODO Auto-generated method stub
return null;
}
}
|
package com.mercadolibre.bootcampmelifrescos.integration;
public class PurchaseOrderControllerTest {
}
|
package ca.deuterium.assignment1;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private RecyclerView pRecyclerView;
private RecyclerView.Adapter pAdapter;
private RecyclerView.LayoutManager pLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), EditPersonActivity.class);
startActivity(intent);
}
});
pRecyclerView = (RecyclerView) findViewById(R.id.person_recycler_view);
pRecyclerView.setHasFixedSize(true);
// use a linear layout manager
pLayoutManager = new LinearLayoutManager(this);
pRecyclerView.setLayoutManager(pLayoutManager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume(){
super.onResume();
// specify an adapter fpr the recycle view
AppStateSingleton.loadList(this);
ArrayList<Person> pl = AppStateSingleton.getPersonList();
pAdapter = new PersonAdapter(pl);
pRecyclerView.setAdapter(pAdapter);
TextView countView = (TextView) findViewById(R.id.count);
countView.setText(Integer.toString(pl.size()));
}
}
|
package com.training.utils;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.training.beans.Customer;
public class CustomerDAOImpl implements DAO{
private Connection conn;
public CustomerDAOImpl(Connection con){
super();
// conn=DbConnections.getConnection(inStream);
this.conn=con;
}
@Override
public int add(Customer customer) throws SQLException {
// TODO Auto-generated method stub
String sql="insert into customerhv values(?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setLong(1, customer.getCustomerId());
ps.setString(2, customer.getCustomerName());
ps.setLong(3, customer.getMobileNumber());
int row=ps.executeUpdate();
ps.close();
return row;
}
@Override
public List<Customer> getAllCustomers() throws SQLException{
List<Customer> customerList=new ArrayList<>();
String sql="select * from customerhv";
PreparedStatement ps=conn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
while(rs.next()){
long customerId=rs.getLong(1);
String customerName=rs.getString(2);
long mobileNumber=rs.getLong(3);
Customer customer=new Customer(customerId, customerName, mobileNumber);
customerList.add(customer);
}
return customerList;
}
}
|
package io.nuls.base.data;
import io.nuls.base.basic.NulsByteBuffer;
import io.nuls.core.crypto.HexUtil;
import io.nuls.core.exception.NulsException;
import org.junit.Test;
import java.io.IOException;
/**
* 测试extend字段
*
* @author captain
* @version 1.0
* @date 2019/6/21 11:13
*/
public class BlockExtendsDataTest {
/**
* 测试扩展字段hex
*
* @throws NulsException
* @throws IOException
*/
@Test
public void test() throws NulsException, IOException {
String string = "010000000100010000000100010001003c64002056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421";
BlockExtendsData data = new BlockExtendsData();
data.parse(new NulsByteBuffer(HexUtil.decode(string)));
System.out.println(data.getMainVersion());
System.out.println(data.getBlockVersion());
System.out.println(data.getEffectiveRatio());
System.out.println(data.getContinuousIntervalCount());
System.out.println(data.getConsensusMemberCount());
System.out.println(data.getRoundIndex());
System.out.println(data.getRoundStartTime());
System.out.println(data.getPackingIndexOfRound());
System.out.println(HexUtil.encode(data.getStateRoot()));
}
/**
* 设置扩展字段的值,并返回hex,通常用于设置创世块
*
* @throws NulsException
* @throws IOException
*/
@Test
public void test1() throws NulsException, IOException {
BlockExtendsData data = new BlockExtendsData();
data.setConsensusMemberCount(1);
data.setPackingIndexOfRound(1);
data.setRoundIndex(1);
data.setRoundStartTime(1594278000L);
data.setMainVersion((short) 1);
data.setBlockVersion((short) 1);
data.setEffectiveRatio((byte) 90);
data.setContinuousIntervalCount((short) 100);
data.setStateRoot(HexUtil.decode("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"));
System.out.println(HexUtil.encode(data.serialize()));
}
@Test
public void test2() {
// ,
// {
// "address": "NERVEepb6FhfgWLyqHUQgHoHwRGuw3huvchBus",
// "amount": 2000000000000000,
// "lockTime": 1628524800
// }
long start = 1628524800L;
StringBuilder ss = new StringBuilder();
for (int i = 0; i < 20; i++) {
ss.append(",{\"address\":\"NERVEepb6FhfgWLyqHUQgHoHwRGuw3huvchBus\",\"amount\": 2000000000000000,\"lockTime\":");
long lockTime = start+i*30*24*60*60;
ss.append(lockTime);
ss.append("}");
}
System.out.println(ss.toString());
}
}
|
package indi.jcl.magicblog.controller;
import indi.jcl.magicblog.service.IUserService;
import indi.jcl.magicblog.vo.Response;
import indi.jcl.magicblog.vo.User;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/")
public class LoginController {
@Resource
private IUserService userService;
@Resource
private HttpSession session;
@RequestMapping("login")
@ResponseBody
public Response login(User user) throws Exception {
String userName = user.getUserName();
String pwd = user.getPwd();
if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(pwd)) {
return Response.FAIL().setMsg("用户名或密码不能为空");
}
user = userService.login(userName, pwd);
if (user == null) {
return Response.FAIL().setMsg("用户名或密码错误");
}
session.setAttribute("session", user);
return Response.SUCCESS().setMsg("登录成功");
}
}
|
package com.cairone.webdriver;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class App
{
private static SeleniumConfig DRIVER;
private static String HOST;
private static String CUIT_PARA_INFORMAR;
static {
DRIVER = new SeleniumConfig();
HOST = "http://www.informescea.com.ar";
CUIT_PARA_INFORMAR = "***";
}
public static void main( String[] args ) throws Throwable
{
WebDriver webDriver = DRIVER.getDriver();
// *** LOGIN EN ESTUDIO CEA
webDriver.get(HOST + "/login.php");
WebElement usernameInput = webDriver.findElement(By.id("username"));
WebElement pwdInput = webDriver.findElement(By.id("password"));
usernameInput.sendKeys("***");
pwdInput.sendKeys("***");
WebElement submitBtn = webDriver.findElement(By.className("buttonsubmit"));
DRIVER.clickElement(submitBtn);
// *** BUSCAR PERSONA POR CUIT
WebElement elemTypeSelect = webDriver.findElement(By.id("type"));
WebElement elemCriterioInput = webDriver.findElement(By.id("s"));
WebElement elemReportTypeRadio = webDriver.findElement(By.name("reporttype"));
Select typeSelect = new Select(elemTypeSelect);
typeSelect.selectByValue("cuit");
elemCriterioInput.sendKeys(CUIT_PARA_INFORMAR);
DRIVER.clickElement(elemReportTypeRadio);
WebElement submitBtn2 = webDriver.findElement(By.name("search")).findElement(By.className("buttonsubmit"));
DRIVER.clickElement(submitBtn2);
WebElement elemResultDiv = webDriver.findElement(By.cssSelector("div.twelve.columns.result"));
DRIVER.clickElement(elemResultDiv);
// *** IMPRIMIR EN PDF
waitForPageLoaded();
((JavascriptExecutor)webDriver).executeScript("window.print();");
try {
Thread.sleep(5000);
} catch (Throwable error) {
throw error;
}
// *** CERRAR SESION
WebElement elemLogout = webDriver.findElement(By.cssSelector("a.link-button.logout"));
DRIVER.clickElement(elemLogout);
// *** CERRAR BROWSER
webDriver.close();
System.out.println("Listo!");
}
public static void waitForPageLoaded() throws Throwable {
ExpectedCondition<Boolean> expectation = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete");
}
};
try {
Thread.sleep(1000);
WebDriverWait wait = new WebDriverWait(DRIVER.getDriver(), 30);
wait.until(expectation);
} catch (Throwable error) {
throw error;
}
}
}
|
package Vorlesung06;
import java.util.ArrayList;
public class FahrzeugList<T extends Auto> extends ArrayList<T> {
public T getFastest() {
T result = null;
for (T t : this) {
if (result == null) {
result = t;
} else if (t.vMax > result.vMax) {
result = t;
}
}
return result;
}
}
|
package com.adidas.microservices.publicservice.controller;
import com.adidas.microservices.publicservice.entity.Subscription;
import com.adidas.microservices.publicservice.proxy.SubscriptionServiceProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
public class PublicController {
private static Logger log = LoggerFactory.getLogger(PublicController.class.getName());
@Autowired
private SubscriptionServiceProxy subscriptionServiceProxy;
@PostMapping("/newsletter-subscription")
public Long submitSubscription(@Valid @RequestBody Subscription subscription) {
log.info("Received subscription " + subscription + " to be created");
return subscriptionServiceProxy.createSubscription(subscription);
}
}
|
package com.example.mad;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class content extends AppCompatActivity {
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_about,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.about:
Intent i=new Intent(getApplicationContext(),content.class);
startActivity(i);
return true;
case R.id.contact:
Intent i1=new Intent(getApplicationContext(),about.class);
startActivity(i1);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
}
public void view(View view)
{
Intent i = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel","+918971673209","null"));
startActivity(i);
}
public void view1(View view)
{
Intent i1 = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel","9742251638","null"));
startActivity(i1);
}
public void back2(View view) {
Intent i=new Intent(content.this,MainActivity.class);
startActivity(i);
}
}
|
package swivl.demo.entities;
public class Matches {
}
|
class SevenRC
{
public static void main(String args[])
{
int Arr[][]={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,16},{17,18,19,20,21},{22,23,24,25,26}};
int sum=0;
for(int i=0;i<Arr.length;i++)
{
for(int j=0;j<=2;j=j+2)
{
sum=sum+Arr[i][j];
System.out.print(Arr[i][j]+" ");
}
System.out.println();
}
System.out.println("Sum Of 0th 2nd Columns are :"+sum);
}
}
|
package com.cs.rest.status;
import com.cs.security.AccessDeniedException;
/**
* @author Joakim Gottzén
*/
public class AccessDeniedMessage extends ErrorMessage {
private static final long serialVersionUID = 1L;
private AccessDeniedMessage(final String message) {
super(StatusCode.ACCESS_DENIED, message);
}
public static AccessDeniedMessage of(final AccessDeniedException exception) {
return new AccessDeniedMessage(exception.getMessage());
}
}
|
package web.id.azammukhtar.subico.UI.HomeFragment;
import android.util.Log;
import android.view.View;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.jetbrains.annotations.NotNull;
import static androidx.constraintlayout.widget.Constraints.TAG;
abstract public class HomePagination extends RecyclerView.OnScrollListener {
private LinearLayoutManager layoutManager;
private int currentPage = 0;
private int previousTotalItemCount = 0;
private boolean loading = true;
protected HomePagination(GridLayoutManager layoutManager) {
this.layoutManager = layoutManager;
}
@Override
public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Log.d(TAG, "onScrolled: scroll ");
int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
int totalItemCount = layoutManager.getItemCount();
if (totalItemCount < previousTotalItemCount) {
this.currentPage = 0;
this.previousTotalItemCount = totalItemCount;
if (totalItemCount == 0) {
this.loading = true;
}
}
if (loading && (totalItemCount > previousTotalItemCount)) {
loading = false;
previousTotalItemCount = totalItemCount;
}
int visibleThreshold = 5;
if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount) {
currentPage++;
onLoadMore(currentPage, totalItemCount, recyclerView);
loading = true;
}
}
abstract public void onLoadMore(int currentPage, int totalItemCount, View view);
}
|
package com.xcl.community.dto;
import lombok.Data;
/**
* GithupUser
*
* @author 徐长乐
* @date 2020/5/1
*/
@Data
public class GithupUser {
private String name;
private Long id;
private String bio;
}
|
package fabricas;
import entidades.Loja;
public class FabricaLoja {
public FabricaLoja(){
}
public Loja criarLoja(String nome, String endereco, String cnpj, String imagem){
return Loja.CriarLoja(nome,endereco,cnpj,imagem);
}
}
|
/*
* 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 logica;
import java.sql.SQLException;
import java.util.List;
import persistencia.EquipoAlmacen;
import persistencia.PersistenciaEquipo;
/**
* contiene los datos de un equipo además de métodos para registrar un
* mantenimiento o un préstamo.
*
* @author ferc
* @author Giss
* @author Pao
*/
public class Equipo implements InterfaceEquipo {
private String identificador;
private String modelo;
private String numeroSerie;
private String tipoEquipo;
private String marca;
private String responsableUbicacion;
private String disponibilidad;
private PersistenciaEquipo persistencia = new EquipoAlmacen();
public Equipo(String identificador, String modelo, String numeroSerie,
String tipoEquipo, String marca, String responsableUbicacion, String disponibilidad) {
this.modelo = modelo;
this.numeroSerie = numeroSerie;
this.tipoEquipo = tipoEquipo;
this.identificador = identificador;
this.marca = marca;
this.responsableUbicacion = responsableUbicacion;
this.disponibilidad = disponibilidad;
}
public Equipo(String modelo, String numeroSerie,
String tipoEquipo, String marca, String responsableUbicacion) {
this.modelo = modelo;
this.numeroSerie = numeroSerie;
this.tipoEquipo = tipoEquipo;
this.marca = marca;
this.responsableUbicacion = responsableUbicacion;
}
public Equipo(String identificador, String modelo, String numeroSerie,
String tipoEquipo, String marca, String disponibilidad) {
this.modelo = modelo;
this.numeroSerie = numeroSerie;
this.tipoEquipo = tipoEquipo;
this.identificador = identificador;
this.marca = marca;
this.disponibilidad = disponibilidad;
}
public Equipo() {
}
public Equipo(String identificador) {
this.identificador = identificador;
}
@Override
public String getDisponibilidad() {
return this.disponibilidad;
}
@Override
public String getIdentificador() {
return this.identificador;
}
@Override
public String getModelo() {
return this.modelo;
}
@Override
public String getNumeroSerie() {
return this.numeroSerie;
}
@Override
public String getTipoEquipo() {
return this.tipoEquipo;
}
@Override
public String getMarca() {
return this.marca;
}
@Override
public String getResponsableUbicacion() {
return this.responsableUbicacion;
}
/**
* Recupera una lista conequipos disponibles.
*
* @return lista de Strings.
* @throws SQLException Cuando no es posible recuperar el producto.
*/
@Override
public List<String> obtenerDisponibles() throws SQLException {
return this.persistencia.obtenerDisponibles();
}
/**
* Recupera los productos.
*
* @param identificador String
* @return String.
* @throws SQLException Cuando no es posible recuperar el producto.
*/
@Override
public String obtenerProducto(String identificador) throws SQLException {
return this.persistencia.obtenerProducto(identificador);
}
}
|
package com.junzhao.base.http;
import com.junzhao.base.base.APP;
import com.junzhao.base.utils.MLLogUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import org.apache.http.protocol.HTTP;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by alan on 2016/4/25.
*/
public class HttpUtil {
public static void doRequest(String url, RequestCallBack<String> callBack) {
HttpUtils utils = APP.getInstance().getHttpUtils();
utils.send(HttpRequest.HttpMethod.GET, url, callBack);
}
public static void doGetRequest(String url, RequestCallBack<String> callBack) {
HttpUtils utils = APP.getInstance().getHttpUtils();
RequestParams params = new RequestParams(url);
params.addHeader(HTTP.CONTENT_LEN, "0");
utils.send(HttpRequest.HttpMethod.GET, url, params, callBack);
}
public static void doPostRequest(String url, Map<String, String> map, RequestCallBack<String> callBack) {
HttpUtils utils = APP.getInstance().getHttpUtils();
RequestParams params = null;
if (map != null) {
params = new RequestParams();
Set<String> set = map.keySet();
for (String string : set) {
params.addBodyParameter(string, map.get(string));
}
}
utils.send(HttpRequest.HttpMethod.POST, url, params, callBack);
}
/**
* 上传文件到服务器
*
* @param url
* @param
* @param updataFile
* @param callBack
*/
public static void uploadFile(String url, String fileName, File updataFile, RequestCallBack<String> callBack) {
HttpUtils utils = APP.getInstance().getHttpUtils();
RequestParams params = new RequestParams();
params.addBodyParameter("path","shaidan");
/*if (map != null) {
Set<String> set = map.keySet();
for (String string : set) {
params.addBodyParameter(string, map.get(string));
}
}*/
params.addBodyParameter(fileName, updataFile);
utils.send(HttpRequest.HttpMethod.POST, url, params, callBack);
}
public static void uploadFile2(String url, String fileName, List<File> updataFile, HashMap<String, String> paramsMap, RequestCallBack<String> callBack) {
HttpUtils utils = APP.getInstance().getHttpUtils();
RequestParams params = new RequestParams();
// params.addBodyParameter("path","touimg");
/*if (map != null) {
Set<String> set = map.keySet();
for (String string : set) {
params.addBodyParameter(string, map.get(string));
}
}*/
for(Map.Entry<String, String> entry : paramsMap.entrySet()){
params.addBodyParameter(entry.getKey(), entry.getValue());
// System.out.println("key= "+entry.getKey()+" and value= "+entry.getValue());
}
for(int i=0;i<updataFile.size();i++){
params.addBodyParameter(fileName, updataFile.get(i), "multipart/form-data");
}
// params.setMultipart(true);
// for (File file : updataFile ){
// params.addBodyParameter("file", new File(updataFile.get(i)));
// params.addBodyParameter(fileName, file);
// // MLLogUtil.d("request", String.format("请求的参数{%s:%s}", params.getParamName(), params.getParamValue()));
// }
MLLogUtil.d("上传参数", params.toString() + "");
// params.addBodyParameter(fileName, updataFile);
utils.send(HttpRequest.HttpMethod.POST, url, params, callBack);
}
/**
* 下载文件
* @param url
* @param fileName
* @param updataFile
* @param callBack
*/
public static void downLoadFile(String url, String fileName, File updataFile, RequestCallBack<String> callBack) {
HttpUtils utils = APP.getInstance().getHttpUtils();
RequestParams params = new RequestParams();
params.addBodyParameter(fileName, updataFile);
utils.send(HttpRequest.HttpMethod.POST, url, params, callBack);
}
}
|
package com.Nikolovska.spring.HRManagement.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import com.Nikolovska.spring.HRManagement.model.Employee;
import com.Nikolovska.spring.HRManagement.model.Items;
import com.Nikolovska.spring.HRManagement.model.JobPosition;
import com.Nikolovska.spring.HRManagement.model.Vacations;
import com.Nikolovska.spring.HRManagement.service.EmployeeService;
//import com.Nikolovska.spring.HRManagement.service.FilesService;
import com.Nikolovska.spring.HRManagement.service.ItemsService;
import com.Nikolovska.spring.HRManagement.service.JobPositionService;
import com.Nikolovska.spring.HRManagement.service.VacationsService;
@Controller
@SessionAttributes(names = "employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@Autowired
private VacationsService vacationsService;
@Autowired
private ItemsService itemsService;
@Autowired
private JobPositionService jobpositionService;
@RequestMapping(path = "/listemployees", method = RequestMethod.GET)
public String getEmployees(Model model) {
// if (model.getAttribute("id") == null) {
// model.addAttribute("errorMessage", "Employee does not exist!");
// return "redirect:/";
// } else {
// Employee employee = (Employee)model.getAttribute("employee");
List<Employee> employees = employeeService.getAllEmployees();
model.addAttribute("employees", employees);
return "listemployees";
// }
}
@RequestMapping(path = "/new_employee", method = RequestMethod.POST)
public String registerEmployee(@RequestBody String body, Employee employee, Model model) {
employee = employeeService.saveEmployee(employee);
return "redirect:/menu";
}
@RequestMapping(path = "/new_employee/view/{id}", method = RequestMethod.GET)
public String viewEmployeeByName(@PathVariable Long id, Model model) {
List<Vacations> vacations = vacationsService.findByEmployee_id(id);
model.addAttribute("vacations", vacations);
model.addAttribute("disabled", "disabled");
// model.addAttribute("checkedItem", "checked");
model.addAttribute("selected", "selected");
getEmployeeByName(id, model);
Optional<Employee> optEmployee = employeeService.findById(id);
Employee employee = optEmployee.get();
List<Items> items = employee.getItems();
if (items != null) {
model.addAttribute("items", items);
model.addAttribute("checkedItem", "checked");
}
return "new_employee";
}
@RequestMapping(path = "/new_employee/{id}", method = RequestMethod.GET)
public String getEmployeeByName(@PathVariable Long id, Model model) {
Optional<Employee> optEmployee = employeeService.findById(id);
Employee employee = optEmployee.get();
model.addAttribute("employee_id", id);
model.addAttribute("name", employee.getName());
model.addAttribute("surname", employee.getSurname());
model.addAttribute("personal_number", employee.getPersonal_number());
model.addAttribute("birthyear", employee.getBirthyear());
model.addAttribute("adress", employee.getAdress());
model.addAttribute("phone", employee.getPhone());
model.addAttribute("email", employee.getEmail());
model.addAttribute("type_contract", employee.getType_contract());
model.addAttribute("begin_date", employee.getBegin_date());
model.addAttribute("end_date", employee.getEnd_date());
model.addAttribute("salary", employee.getSalary());
model.addAttribute("bonus", employee.getBonus());
model.addAttribute("username", employee.getUsername());
model.addAttribute("password", employee.getPassword());
JobPosition job_position_tmp = employee.getJob_position();
List<JobPosition> job_position = jobpositionService.getAllPositions();
job_position.add(job_position_tmp);
if (job_position != null) {
model.addAttribute("job_position", job_position);
}
List<Items> items = itemsService.getAllItems();
// model.addAttribute("items", items);
// List<Items> items = employee.getItems();
if (items != null) {
model.addAttribute("items", items);
}
model.addAttribute("job_position_tmp", job_position_tmp);
return "new_employee";
}
@RequestMapping(path = "/new_employee/{id}", method = RequestMethod.POST)
public String updateEmployeeById(@PathVariable Long id, Employee employee, Model model) {
employeeService.updateEmplpoyee(employee);
return "redirect:/listemployees";
}
}
|
/**
* Package contenant les classes graphiques
*/
package GUI;
|
package algorithms.context;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by Chen Li on 2018/5/4.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppTestContext.class)
public abstract class AbstractContextTest {
@Autowired
private ApplicationContext appContext;
public <T> T getBean(String name) {
return (T) appContext.getBean(name);
}
}
|
package com.cc.multirecycleview.bean;
import static com.cc.multirecycleview.holder.SimpleCategoryViewHolder.CATEGORY_TYPE_LIST;
/**
* 底部分页类型
*
* @author 陈聪 2020-05-06 15:33
*/
public class CategoryProBean extends CategoryBean {
/** 配置的展示布局 */
public int layout = 0;
/** 配置背景颜色 */
public int bgColor = 0;
/** 配置的展示布局排版类型 */
public int itemType = CATEGORY_TYPE_LIST;
/** itemType为grid或flow时,配置的横向展示个数 */
public int hcount;
/**是否已加载完数据,刷新时改为false*/
private boolean loadFinished;
public CategoryProBean(String title, String type, int layout, int itemType, int hcount) {
setTitle(title);
setType(type);
this.layout = layout;
this.itemType = itemType;
this.hcount = hcount;
}
public CategoryProBean(String title, String type, int layout, int itemType, int hcount, int bgColor) {
setTitle(title);
setType(type);
this.layout = layout;
this.itemType = itemType;
this.hcount = hcount;
this.bgColor = bgColor;
}
public boolean isLoadFinished() {
return loadFinished;
}
public void setLoadFinished(boolean loadFinished) {
this.loadFinished = loadFinished;
}
}
|
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.shape.Rectangle;
public class Player{
Rectangle player = new Rectangle();
KeyCode moveUp;
KeyCode moveDown;
boolean up = false, down = false;
double[] info;
public Player(int p, double[] info){
// Set width and height of player to that in array
player.setWidth(info[2]);
player.setHeight(info[3]);
// Add curves to player
player.setArcHeight(10);
player.setArcWidth(10);
this.info = info;
// Set variables after which player it is
if (p == 1){
player.setX(info[5]);
player.setY(info[6]);
moveUp = KeyCode.W;
moveDown = KeyCode.S;
}
if (p == 2){
player.setX(info[0] - 30);
player.setY(30);
moveUp = KeyCode.UP;
moveDown = KeyCode.DOWN;
}
}
public void keyPressed(KeyEvent e){
// If up key is pressed, set up = true
if (e.getCode() == moveUp){
up = true;
}
// If down key is pressed, set down = true
if (e.getCode() == moveDown){
down = true;
}
}
public void keyReleased(KeyEvent e){
// If up key is released, set up = false
if (e.getCode() == moveUp){
up = false;
}
// If down key is pressed, set down = false
if (e.getCode() == moveDown){
down = false;
}
}
public void frame(){
// If up is pressed and does not hit top, move up
if (up && info[6] >= 0){
player.setY(info[6] - info[4]);
info[6] = info[6] - info[4];
}
// If down is pressed and does not hit bottom, move down
if (down && player.getY() <= info[1] - info[3] + 10){
player.setY(info[6] + info[4]);
info[6] = info[6] + info[4];
}
}
// Return Rectangle object
public Rectangle returnNode(){ return player; }
}
|
package xyz.spacexplorer.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import xyz.spacexplorer.dto.atom.AtomDTO;
import xyz.spacexplorer.dto.atom.AtomDTOExample;
import xyz.spacexplorer.utils.OriginalMapper;
public interface AtomDao extends OriginalMapper<AtomDTO> {
int countByExample(AtomDTOExample example);
int deleteByExample(AtomDTOExample example);
int deleteByPrimaryKey(Integer atomId);
int insert(AtomDTO record);
int insertSelective(AtomDTO record);
List<AtomDTO> selectByExample(AtomDTOExample example);
AtomDTO selectByPrimaryKey(Integer atomId);
int updateByExampleSelective(@Param("record") AtomDTO record, @Param("example") AtomDTOExample example);
int updateByExample(@Param("record") AtomDTO record, @Param("example") AtomDTOExample example);
int updateByPrimaryKeySelective(AtomDTO record);
int updateByPrimaryKey(AtomDTO record);
/**
*
* @Title: getAllAtom
* @Description: TODO:(描述这个方法的作用)
* @param @param qName
* @param @return
* @return List<AtomDTO>
* @throws
*/
List<AtomDTO> getAllAtom(String qName);
}
|
package util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import sun.misc.BASE64Decoder;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Description
*
* @author minhho242 on 3/24/15.
*/
public class HoSoCongTyUtils {
private static final Map<String, String> decodes = new HashMap<>();
static {
decodes.put("y", "0");
decodes.put("z", "1");
decodes.put("e", "2");
decodes.put("g", "3");
decodes.put("b", "4");
decodes.put("c", "5");
decodes.put("a", "6");
decodes.put("d", "7");
decodes.put("o", "8");
decodes.put("p", "9");
decodes.put("f", "/");
}
public static String extractByCSSQuery(Document document, String cssQuery) {
Elements elements = document.select(cssQuery);
if ( elements.size() > 0 ) {
return elements.get(0).ownText();
}
return null;
}
public static String extractValueMatchingText(Document document, String text) {
Elements elements = document.getElementsMatchingOwnText(text);
if ( elements.size() > 0 ) {
return elements.get(0).child(0).text();
}
return null;
}
public static String extractValueFromImageAndMatchingText(Document document, String text) {
Elements elements = document.getElementsMatchingOwnText(text);
if ( elements.size() > 0 ) {
Node tempNode = elements.get(0).childNode(1);
String imageValue;
if ( tempNode.nodeName().equals("img") ) {
String imageSource = tempNode.attr("src");
imageValue = decodeImageValue(imageSource);
} else {
String imageSource = tempNode.childNode(0).attr("src");
imageValue = decodeImageValue(imageSource);
}
return imageValue;
}
return null;
}
public static String extractBusinessLicense(Document document) {
Elements elements = document.getElementsMatchingOwnText("Giấy phép kinh doanh");
if ( elements.size() > 0 ) {
String businessLicenseImageSource = elements.get(0).childNode(1).attr("src");
String businessLicense = decodeImageValue(businessLicenseImageSource);
return businessLicense;
}
return null;
}
public static String extractBusinessLicenseIssueDate(Document document) {
Elements elements = document.getElementsMatchingOwnText("Giấy phép kinh doanh");
if ( elements.size() > 0 ) {
String businessLicenseIssuedDateImageSource = elements.get(0).childNode(3).attr("src");
String businessLicenseIssuedDate = decodeImageValue(businessLicenseIssuedDateImageSource);
return businessLicenseIssuedDate;
}
return null;
}
public static String extractBusinesses(Document document) {
Elements elements = document.select("table tr");
if ( elements.size() == 0 ) {
return null;
}
List<List<String>> businesses = new ArrayList<>();
for (int i = 1; i < elements.size(); i++) {
Element trElement = elements.get(i);
Element tdBusinessNameElement = trElement.child(1); //business name;
String mainOperation = "N";
if ( tdBusinessNameElement.childNodes().size() > 1 ) {
mainOperation = "Y";
}
List<String> business = new ArrayList<>();
business.add(tdBusinessNameElement.text());
business.add(trElement.child(2).text());
business.add(mainOperation);
businesses.add(business);
}
ObjectMapper objectMapper = new ObjectMapper();
try {
String jsonString = objectMapper.writeValueAsString(businesses);
return jsonString;
} catch (JsonProcessingException e) {
return null;
}
}
public static String decodeImageValue(String imageSource) {
try {
imageSource = URLDecoder.decode(imageSource, "UTF-8");
} catch (UnsupportedEncodingException e) {
return null;
}
Pattern pattern = Pattern.compile(".*char=(.*)&", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(imageSource);
String code;
if ( matcher.find() ) {
code = matcher.group(1);
} else {
return null;
}
code = _base64Decode(code);
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < code.length(); i++) {
String decodedChar = decodes.get(String.valueOf(code.charAt(i)));
resultBuilder.append(decodedChar);
}
return resultBuilder.toString();
}
private static String _base64Decode(String code) {
byte[] byteBuffer = Base64.decode(code);
return new String(byteBuffer);
}
}
|
package com.github.fierioziy.particlenativeapi.core.asm;
import com.github.fierioziy.particlenativeapi.core.asm.mapping.SpigotClassRegistry;
import org.objectweb.asm.Opcodes;
public class BaseASM implements Opcodes {
/*
Constant names to ease possibly future refactoring
*/
// API
public static final String DETACH_COPY_METHOD_NAME = "detachCopy";
public static final String SEND_TO_METHOD_NAME = "sendTo";
public static final String IS_PRESENT_METHOD_NAME = "isPresent";
public static final String PACKET_METHOD_NAME = "packet";
public static final String OF_METHOD_NAME = "of";
public static final String COLOR_METHOD_NAME = "color";
public static final String ROLL_METHOD_NAME = "roll";
public static final String DELAY_METHOD_NAME = "delay";
public static final String FLYING_TO_METHOD_NAME = "flyingTo";
// ASM
public static final String PACKET_FIELD_NAME = "packet";
public static final String PACKET_WRAPPER_FIELD_NAME = "packetWrapper";
public static final String PARTICLE_FIELD_NAME = "particle";
public static final String PARTICLE_DATA_FIELD_NAME = "data";// for 1.8
public static final String PARTICLE_WRAPPER_FIELD_NAME = "particleWrapper";
public static final String SET_PARTICLE_METHOD_NAME = "setParticle";
public static final String SET_PACKET_METHOD_NAME = "setPacket";
protected final ContextASM context;
protected final SpigotClassRegistry refs;
public BaseASM(ContextASM context) {
this.context = context;
this.refs = context.refs;
}
}
|
package cuj.DemoOfSmack.Config;
/*
*
* project_name: DemoOfSmack
* class_name:
* class_description:
* author: cujamin
* create_time: 2016年7月13日
* modifier:
* modify_time:
* modify_description:
* @version
*
*/
public class SmackConfig {
private String serviceName ;
private String host ;
private int port ;
public SmackConfig(String serviceName , String host , int port )
{
this.serviceName = serviceName;
this.host = host;
this.port = port;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
|
package juego;
import java.util.ArrayList;
import java.util.List;
import cartas.BrazoDerechoExodia;
import cartas.BrazoIzquierdoExodia;
import cartas.CabezaExodia;
import cartas.Carta;
import cartas.PiernaDerechaExodia;
import cartas.PiernaIzquierdaExodia;
import excepciones.CapacidadMaximaException;
import excepciones.CartaNoEstaEnContenedorDeCartasException;
import excepciones.TengoTodasLasPartesDeExodiaException;
public class RecolectorDePartesDeExodia {
private ContenedorDeCartas lugarParaLaCabeza;
private ContenedorDeCartas lugarParaElBrazoIzquierdo;
private ContenedorDeCartas lugarParaElBrazoDerecho;
private ContenedorDeCartas lugarParaLaPiernaIzquierda;
private ContenedorDeCartas lugarParaLaPiernaDerecha;
private List<ContenedorDeCartas> lugares;
public RecolectorDePartesDeExodia() {
this.lugarParaLaCabeza = new ContenedorDeCartas(1);
this.lugarParaElBrazoIzquierdo = new ContenedorDeCartas(1);
this.lugarParaElBrazoDerecho = new ContenedorDeCartas(1);
this.lugarParaLaPiernaIzquierda = new ContenedorDeCartas(1);
this.lugarParaLaPiernaDerecha = new ContenedorDeCartas(1);
this.lugares = new ArrayList<ContenedorDeCartas>();
lugares.add(this.lugarParaLaCabeza);
lugares.add(this.lugarParaElBrazoDerecho);
lugares.add(this.lugarParaElBrazoIzquierdo);
lugares.add(this.lugarParaLaPiernaDerecha);
lugares.add(this.lugarParaLaPiernaIzquierda);
}
public void siEsUnaParteDelExodiaQueNoTeniaRecolectar(Carta carta) throws TengoTodasLasPartesDeExodiaException {
carta.serRecolectadaPorElRecolectorDePartesDeExodia(this);
}
public void recolectarBrazoIzquierdo(BrazoIzquierdoExodia brazoIzquierdoExodia) throws TengoTodasLasPartesDeExodiaException {
if (!this.lugarParaElBrazoIzquierdo.hayCartas())
try {
this.lugarParaElBrazoIzquierdo.agregar(brazoIzquierdoExodia);
} catch (CapacidadMaximaException e) {
// e.printStackTrace();
}
if (this.tengoTodasLasPartesDeExodia())
throw new TengoTodasLasPartesDeExodiaException();
}
public void recolectarBrazoDerecho(BrazoDerechoExodia brazoDerechoExodia) throws TengoTodasLasPartesDeExodiaException {
if (!this.lugarParaElBrazoDerecho.hayCartas())
try {
this.lugarParaElBrazoDerecho.agregar(brazoDerechoExodia);
} catch (CapacidadMaximaException e) {
// e.printStackTrace();
}
if (this.tengoTodasLasPartesDeExodia())
throw new TengoTodasLasPartesDeExodiaException();
}
public void recolectarPiernaDerecha(PiernaDerechaExodia piernaDerechaExodia) throws TengoTodasLasPartesDeExodiaException {
if (!this.lugarParaLaPiernaDerecha.hayCartas())
try {
this.lugarParaLaPiernaDerecha.agregar(piernaDerechaExodia);
} catch (CapacidadMaximaException e) {
// e.printStackTrace();
}
if (this.tengoTodasLasPartesDeExodia())
throw new TengoTodasLasPartesDeExodiaException();
}
public void recolectarPiernaIzquierda(PiernaIzquierdaExodia piernaIzquierdaExodia) throws TengoTodasLasPartesDeExodiaException {
if (!this.lugarParaLaPiernaIzquierda.hayCartas())
try {
this.lugarParaLaPiernaIzquierda.agregar(piernaIzquierdaExodia);
} catch (CapacidadMaximaException e) {
// e.printStackTrace();
}
if (this.tengoTodasLasPartesDeExodia())
throw new TengoTodasLasPartesDeExodiaException();
}
public void recolectarCabeza(CabezaExodia cabezaExodia) throws TengoTodasLasPartesDeExodiaException {
if (!this.lugarParaLaCabeza.hayCartas())
try {
this.lugarParaLaCabeza.agregar(cabezaExodia);
} catch (CapacidadMaximaException e) {
// e.printStackTrace();
}
if (this.tengoTodasLasPartesDeExodia())
throw new TengoTodasLasPartesDeExodiaException();
}
private boolean tengoTodasLasPartesDeExodia() {
return this.lugarParaLaCabeza.hayCartas() && this.lugarParaElBrazoDerecho.hayCartas()
&& this.lugarParaElBrazoIzquierdo.hayCartas() && this.lugarParaLaPiernaDerecha.hayCartas()
&& this.lugarParaLaPiernaIzquierda.hayCartas();
}
public void remover(Carta carta) {
for (ContenedorDeCartas lugar : this.lugares) {
if (lugar.estaDentro(carta))
try {
lugar.remover(carta);
} catch (CartaNoEstaEnContenedorDeCartasException e) {
// e.printStackTrace();
}
}
}
}
|
package org.shiro.demo.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.bouncycastle.jcajce.provider.asymmetric.dsa.DSASigner.noneDSA;
import org.shiro.demo.controller.app.vo.AppAttendVO;
import org.shiro.demo.controller.app.vo.AppDBplanVO;
import org.shiro.demo.dao.util.Pagination;
import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.Customer;
import org.shiro.demo.entity.DBAttend;
import org.shiro.demo.entity.DBPlan;
import org.shiro.demo.entity.DBSituation;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IDBAttendService;
import org.shiro.demo.service.IDBPlanService;
import org.shiro.demo.util.FastJsonTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("dbattendService")
public class DBAttendServiceImpl extends DefultBaseService implements IDBAttendService{
@Resource(name="baseService")
private IBaseService baseService;
@Autowired
private IDBPlanService dbPlanService;
public int insertDBAttend(DBAttend dbAttend,int usebalance) {
/*boolean flag = false;
try {
baseService.save(dbAttend);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;*/
int flag = 0;
try {
String sql = "call p_insertattend("+dbAttend.getCustomer().getCustomerid()+","+dbAttend.getDbPlan().getDbplanid()+","+usebalance+")";
System.out.println(sql);
List<Object> executeBySQLList = baseService.executeBySQLList(sql);
int returndata = new Integer(executeBySQLList.get(0).toString());
return returndata;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
public boolean deleteDBAttend(Long id) {
boolean flag = false;
try {
baseService.delete(DBAttend.class, id);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
public boolean updateDBAttend(DBAttend dbAttend) {
boolean flag = false;
try {
baseService.update(dbAttend);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
public Map<String, Object> getDBAttendVOWithWechatid(int page,int pageSize, String wechatid,int isfinish) {
String jpql = "";
List<Object[]> paginationJpql = null;
Integer total = 0;
if(isfinish==2){
jpql = "select count(o.customer.wechatid),o from DBAttend o where customer.wechatid=? group by o.dbPlan.dbplanid order by attendid desc";
paginationJpql = baseService.getPaginationJpql(page, pageSize, jpql, wechatid);
total = baseService.getByJpql(jpql, wechatid).size();
}else{
jpql = "select count(o.customer.wechatid),o from DBAttend o where customer.wechatid=? and o.dbPlan.isfinish=? group by o.dbPlan.dbplanid order by attendid desc";
paginationJpql = baseService.getPaginationJpql(page, pageSize, jpql, wechatid,isfinish);
total = baseService.getByJpql(jpql, wechatid,isfinish).size();
}
List<AppAttendVO> appAttendVOs = new ArrayList<AppAttendVO>();
for(Object item[] : paginationJpql){
DBAttend dbAttend = (DBAttend) item[1];
AppAttendVO appAttendVO = new AppAttendVO(dbAttend);
appAttendVO.setSelfCount(Integer.parseInt(item[0]+""));
appAttendVOs.add(appAttendVO);
}
List<AppAttendVO> returnappAttendVOs = new ArrayList<AppAttendVO>();
for(AppAttendVO appAttendVO : appAttendVOs){
AppDBplanVO appDBplanVO = dbPlanService.getAppDBplanVObyId(appAttendVO.getDbplanid());
appAttendVO.setAttendNumber(appDBplanVO.getAttendNumber());
List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
queryConditions.add(new QueryCondition("dbPlan.dbplanid="+appAttendVO.getDbplanid()));
List<DBSituation> dbSituations = baseService.get(DBSituation.class, queryConditions );
Customer customer = null;
if(dbSituations.size()==0){
appAttendVO.setSituation(AppAttendVO.SITUATIONING);//进行中
}else{
customer = dbSituations.get(0).getCustomer();
}
if(null==customer){
appAttendVO.setLuckdogWechatid("");
appAttendVO.setSituation(AppAttendVO.SITUATIONNULL);//流标
}else{
appAttendVO.setLuckdogWechatid(customer.getWechatid());
appAttendVO.setSituation(AppAttendVO.SITUATIONFULL);//未流标
}
returnappAttendVOs.add(appAttendVO);
}
Map<String, Object> returnMap = new HashMap<String, Object>();
returnMap.put("rows", returnappAttendVOs);
returnMap.put("total",total);
return returnMap;
}
}
|
package com.blog.asktask.service.impl;
import com.blog.asktask.domain.Post;
import com.blog.asktask.repos.PostRepository;
import com.blog.asktask.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PostServiceImpl implements PostService {
private final PostRepository repository;
@Autowired
public PostServiceImpl(PostRepository repository) {
this.repository = repository;
}
@Override
public Post save(Post post) {
return repository.save(post);
}
@Override
public List<Post> getAll() {
return repository.findAll();
}
@Override
public List<Post> getByTitle(String title) {
return repository.getByTitle(title);
}
@Override
public void remove(Post post) {
repository.delete(post);
}
@Override
public void removeByTitle(String title) {
repository.deleteByTitle(title);
}
@Override
public void removeById(long id) {
repository.deleteById(id);
}
}
|
package com.dubeboard.dubeboard;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Created by edgar on 12/02/16.
*/
public class clsImage {
protected Context Context;
protected int _id;
protected String _name;
protected clsCategory _category;
protected byte[] _image;
protected byte[] _sound;
public clsImage() { }
public clsImage(Context Context, int Category_ID) {
clsImage res_image = new clsImage(Context).getById(Category_ID);
this._id = res_image.get_id();
this._name = res_image.get_name();
this._image = res_image.get_image();
this._category = res_image.get_category();
}
public clsImage(Context Context) { this.Context = Context; }
public clsImage(int _id, String _name, clsCategory _category, byte[] _image, byte[] _sound) {
this._id = _id;
this._name = _name;
this._category = _category;
this._image = _image;
this._sound = _sound;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_name() {
return _name;
}
public void set_name(String _name) {
this._name = _name;
}
public clsCategory get_category() {
return _category;
}
public void set_category(clsCategory _category) {
this._category = _category;
}
public byte[] get_image() {
return _image;
}
public void set_image(Bitmap bmp) {
this.set_image(gl.BitmaptoByteArray(bmp));
}
public void set_image(byte[] _image) {
this._image = _image;
}
public byte[] get_sound() {
return _sound;
}
public void set_sound(byte[] _sound) {
this._sound = _sound;
}
public int AddRecord(String Name, int intImg, int CategoryID) {
clsImage record = getByName(Name);
Bitmap bmp = BitmapFactory.decodeResource(Context.getResources(), intImg);
bmp = gl.scaleDown(bmp, 220, true);
byte[] Img = gl.BitmaptoByteArray(bmp);
clsCategory NewCategory = new clsCategory(Context, CategoryID);
if (record == null){
clsImage NewRecord = new clsImage();
NewRecord.set_name(Name);
NewRecord.set_category(NewCategory);
NewRecord.set_image(Img);
AddRecord(NewRecord);
record = getByName(Name);
} else {
ContentValues vals = new ContentValues();
vals.put(ManageDB.ColumnsImage.IMAGE_IMAGE, Img);
vals.put(ManageDB.ColumnsImage.IMAGE_CATEGORY_ID, NewCategory.get_id());
Update(record.get_id(), vals);
}
return record.get_id();
}
public void AddRecord(clsImage NewRecord) {
SQLiteDatabase db = new ManageDB(Context).getWritableDatabase();
// Armar el Insert
ContentValues values = new ContentValues();
values.put(ManageDB.ColumnsImage.IMAGE_NAME, NewRecord.get_name()); // Nombre
values.put(ManageDB.ColumnsImage.IMAGE_CATEGORY_ID, NewRecord.get_category().get_id()); // Categoria
values.put(ManageDB.ColumnsImage.IMAGE_IMAGE, NewRecord.get_image()); // Imagen
values.put(ManageDB.ColumnsImage.IMAGE_SOUND, NewRecord.get_sound()); // Sonido
// Insertar registro
db.insert(ManageDB.TABLE_IMAGE, null, values);
db.close();
}
// Obtener una Imagen
public clsImage getById(int Image_ID) {
clsImage result = null;
List<clsImage> Images = getRecords(Image_ID);
if (Images.size() > 0)
result = Images.get(0);
return result;
}
public clsImage getByName(String Name) {
clsImage result = null;
List<Object[]> args = new ArrayList<Object[]>();
args.add(new Object[]{ManageDB.ColumnsImage.IMAGE_NAME, "=", Name});
List<clsImage> res = getRecords(args);
if ( res.size() > 0){
result = res.get(0);
}
return result;
}
// Obtener todas las categorias
public List<clsImage> getAll() {
return getRecords(new ArrayList<Object[]>());
}
public List<clsImage> getRecords(int Image_ID) {
List<Object[]> args = new ArrayList<Object[]>();
args.add(new Object[] {ManageDB.ColumnsImage.IMAGE_ID, "=", Image_ID});
return getRecords(args);
}
public List<clsImage> getRecords(Object[] arg) {
List<Object[]> args = new ArrayList<Object[]>();
args.add(new Object[]{arg[0], arg[1], arg[2]});
return getRecords(args);
}
public List<clsImage> getRecords(List<Object[]> args) {
List<clsImage> RecordList = new ArrayList<clsImage>();
SQLiteDatabase db = new ManageDB(Context).getWritableDatabase();
// Select All Query
String selectQuery = "SELECT "
+ ManageDB.ColumnsImage.IMAGE_ID + ","
+ ManageDB.ColumnsImage.IMAGE_NAME + ","
+ ManageDB.ColumnsImage.IMAGE_CATEGORY_ID + ","
+ ManageDB.ColumnsImage.IMAGE_IMAGE + ","
+ ManageDB.ColumnsImage.IMAGE_SOUND
+ " FROM " + ManageDB.TABLE_IMAGE;
String WhereQuery = "";
String _and = " and ";
if (args.size() > 0)
WhereQuery = " WHERE ";
for (Object[] arg: args) {
String field = arg[0].toString();
String operator = arg[1].toString();
Object value = arg[2];
if (field != null && value != null){
if (value instanceof String){
value = "'" + value + "'";
}
WhereQuery = WhereQuery + field + " " + operator + " " + value + _and;
}
}
if (WhereQuery.length() > _and.length() && WhereQuery.substring(WhereQuery.length() - _and.length(), WhereQuery.length()).equals(_and)){
WhereQuery = WhereQuery.substring(0, WhereQuery.length() - _and.length());
}
selectQuery = selectQuery + WhereQuery + " ORDER BY " + ManageDB.ColumnsImage.IMAGE_CATEGORY_ID + "," + ManageDB.ColumnsImage.IMAGE_NAME;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
clsImage Record = new clsImage(
Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
new clsCategory(Context, Integer.parseInt(cursor.getString(2))),
cursor.getBlob(3),
cursor.getBlob(4)
);
// Add Record
RecordList.add(Record);
} while (cursor.moveToNext());
}
db.close();
return RecordList;
}
// Update
public int Update(int record_id, ContentValues values) {
SQLiteDatabase db = new ManageDB(Context).getWritableDatabase();
return db.update(ManageDB.TABLE_IMAGE, values, ManageDB.ColumnsImage.IMAGE_ID + " = " + record_id, null);
}
// Delete
public void Delete(int record_id) {
ManageDB.DeleteRecord(Context, ManageDB.TABLE_IMAGE, record_id);
}
// Count Records
public int CountRecords() {
return CountRecords(new ArrayList<Object[]>());
}
public int CountRecords(Object[] arg) {
List<Object[]> args = new ArrayList<Object[]>();
args.add(new Object[]{arg[0], arg[1], arg[2]});
return CountRecords(args);
}
public int CountRecords(List<Object[]> args) {
SQLiteDatabase db = new ManageDB(Context).getWritableDatabase();
String selectQuery = "SELECT " + ManageDB.ColumnsImage.IMAGE_ID + " FROM " + ManageDB.TABLE_IMAGE;
String WhereQuery = "";
String _and = " and ";
if (args.size() > 0)
WhereQuery = " WHERE ";
for (Object[] arg: args) {
String field = arg[0].toString();
String operator = arg[1].toString();
Object value = arg[2];
if (field != null && value != null){
if (value instanceof String){
value = "'" + value + "'";
}
WhereQuery = WhereQuery + field + " " + operator + " " + value + _and;
}
}
if (WhereQuery.length() > _and.length() && WhereQuery.substring(WhereQuery.length() - _and.length(), WhereQuery.length()).equals(_and)){
WhereQuery = WhereQuery.substring(0, WhereQuery.length() - _and.length());
}
selectQuery = selectQuery + WhereQuery;
Cursor cursor = db.rawQuery(selectQuery, null);
int result = cursor.getCount();
db.close();
return result;
}
}
|
/*
* Copyright (c) 2020.
* Kamalita's coding
*/
package RegularProgramming.Thread;
public class TestSingleThread {
public static void main(String[] args) throws Throwable {
Thread checkextends=new Checkextends();
Thread t=Thread.currentThread();
checkextends.start();
Thread checkextends1=new Checkextends();
checkextends1.start();
{
for(int i: new int[]{1, 3, 2, 1, 5, 3}){
System.out.println("main added "+ i);
}
System.out.println(checkextends.getName()+" and "+t.getName() );
}
}
}
class Checkextends extends Thread{
static int count=1;
@Override
public void run() {
for(int i: new int[]{1, 3, 2, 1, 5, 3}){
System.out.println("child added "+count+" and "+ i);
}
count++;
}
}
|
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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.alibaba.druid.pool.ha.selector;
import com.alibaba.druid.pool.ha.HighAvailableDataSource;
/**
* A Factory pattern for DataSourceSelector.
*
* @author DigitalSonic
*/
public class DataSourceSelectorFactory {
/**
* Get a new instance of the given selector name.
*
* @return null if the given name do not represent a DataSourceSelector
*/
public static DataSourceSelector getSelector(String name, HighAvailableDataSource highAvailableDataSource) {
for (DataSourceSelectorEnum e : DataSourceSelectorEnum.values()) {
if (e.getName().equalsIgnoreCase(name)) {
return e.newInstance(highAvailableDataSource);
}
}
return null;
}
}
|
package com.carsonjones.tuber;
/**
* Created by macuser on 12/17/15.
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class RegisterUserClass {
// Sends the post request to the register.php file which looks through the database to check
// if the entered values are already in the User table of the madmen7_tuber database and then returns
// a response read from the register.php file in string form.
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
// Creates a new URL
url = new URL(requestURL);
// Creates the connection which is in the form of sending a URL to the internet
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Sets the maximum time to wait for an input stream read to complete before giving up.
conn.setReadTimeout(15000);
// Sets the maximum time in milliseconds to wait while connecting.
// Connecting to a server will fail with a SocketTimeoutException
conn.setConnectTimeout(15000);
// Tells the server that it is sending a HTTP POST method.
conn.setRequestMethod("POST");
// Sets the flag indicating whether this URLConnection allows input.
// It cannot be set after the connection is established.
conn.setDoInput(true);
// Sets the flag indicating whether this URLConnection allows output.
// It cannot be set after the connection is established.
conn.setDoOutput(true);
// OutputStream - A writable sink for bytes.
// getOutputStream() - Returns an output stream that is connected to the standard
// input stream of the native process represented by our HttpURLConnection object.
// So this is used to edit what we send to the server.
OutputStream os = conn.getOutputStream();
// A writer is a means of writing data to a target in a character-wise manner.
// With this writer we can write on what we send to the server
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
// This writer writes the POST data string to the
// connection which uses the getPostDataString() connection
writer.write(getPostDataString(postDataParams));
// Most output streams expect the flush() method to be called before closing the stream,
// to ensure all data is actually written out.
writer.flush();
writer.close();
// Close the output stream
os.close();
// Returns the response code returned by the remote HTTP server.
int responseCode=conn.getResponseCode();
// if the server says that works
if (responseCode == HttpsURLConnection.HTTP_OK) {
// getInputStream() - Returns an InputStream for reading data from the resource
// pointed by this URLConnection. It throws an UnknownServiceException by default.
// This creates a reader that can read what the register.php file says back to us
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
// Reads the first line in the response from the register.php file
response = br.readLine();
}
else {
response="Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
// Creates the string needed to send the post request to the server
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first) {
first = false;
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
else {
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
}
return result.toString();
}
}
|
package com.kinsella.people.business.service;
import com.kinsella.people.data.entity.Address;
import com.kinsella.people.data.entity.Person;
import java.util.List;
import java.util.Optional;
public interface PersonService {
Optional<Person> create(Person person);
Optional<Person> create(long id, String firstName, String lastName);
Optional<Person> get(long id);
List<Person> getAll();
Optional<Person> update(long id, String firstName, String LastName);
boolean removeAddress(Person person, Address address);
boolean delete(long id);
long count();
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.apache.hadoop.mapreduce;
import java.util.Properties;
import java.util.concurrent.Callable;
/**
*
* @author ashwinkayyoor
*/
public class CallableCombiner implements Callable {
private final Combiner combiner;
private final Combiner.Context context;
private final Properties prop;
private Object[] returnData = new Object[2];
private int id;
private Object[][] intermArray;
public CallableCombiner(final Combiner combiner, final Combiner.Context context, final Properties prop, Object[][] intermArray, int id) {
this.combiner = combiner;
this.context = context;
this.prop = prop;
this.id = id;
this.intermArray = intermArray;
}
/**
* @see java.util.concurrent.Callable#call()
*/
@Override
public final Object call() {
try {
combiner.run(context, prop);
//returnData[0] = combiner.getDataArray();
//returnData[1] = combiner.getOffsetsArray();
intermArray[this.id][0] = combiner.getDataArray();
intermArray[this.id][1] = combiner.getOffsetsArray();
return returnData;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
package nesto.mediaplayer;
import android.content.res.Configuration;
import android.graphics.Point;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.VideoView;
import java.io.File;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import nesto.base.ui.activity.ActionBarActivity;
import nesto.base.util.AppUtil;
/**
* Created on 2016/7/9.
* By nesto
*/
public class VideoActivity extends ActionBarActivity {
@BindView(R.id.video) VideoView video;
@BindView(R.id.buttons) LinearLayout buttons;
private int progress;
private int videoWidth;
private int videoHeight;
private Handler handler = new Handler();
private boolean isPlaying;
@Override
public int getLayoutId() {
return R.layout.activity_video;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
init();
}
private void init() {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "video", "1.mp4");
video.setVideoPath(file.getPath());
video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
videoWidth = mp.getVideoWidth();
videoHeight = mp.getVideoHeight();
setSize();
}
});
}
private void setSize() {
float videoProportion = (float) videoWidth / (float) videoHeight;
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
float screenProportion = (float) size.x / (float) size.y;
ViewGroup.LayoutParams lp = video.getLayoutParams();
if (videoProportion > screenProportion) {
lp.width = size.x;
lp.height = (int) ((float) size.x / videoProportion);
} else {
lp.width = (int) (videoProportion * (float) size.y);
lp.height = size.y;
}
video.setLayoutParams(lp);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setSize();
}
private void showButton() {
buttons.setVisibility(View.VISIBLE);
handler.postDelayed(new Runnable() {
@Override
public void run() {
buttons.setVisibility(View.GONE);
}
}, 5000);
}
@OnClick({R.id.play, R.id.pause, R.id.replay, R.id.stop, R.id.main})
public void onClick(View view) {
showButton();
switch (view.getId()) {
case R.id.play:
if (!video.isPlaying()) {
video.start();
isPlaying = true;
}
break;
case R.id.pause:
if (video.isPlaying()) {
video.pause();
isPlaying = false;
}
break;
case R.id.replay:
// the name is resume, but what it really do is replay
video.resume();
isPlaying = true;
break;
case R.id.stop:
if (video.isPlaying()) {
video.stopPlayback();
isPlaying = false;
}
break;
default:
break;
}
}
@Override
protected void onResume() {
super.onResume();
final boolean needResume = video != null && progress != 0 && isPlaying;
if (needResume) {
video.start();
video.seekTo(progress);
}
AppUtil.acquireScreenOn(this);
}
@Override
protected void onPause() {
super.onPause();
AppUtil.releaseScreenOn(this);
if (video != null) {
progress = video.getCurrentPosition();
video.stopPlayback();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (video != null) {
video.suspend();
}
}
}
|
package test;
public class Person {
//FIELDS
private String fname, lname;
private int age, day, month, year;
//CONSTRUCT
public Person() {}
public Person(String fname, String lname, int age) {
setFname(fname);
setLname(lname);
setAge(age);
}
//GETTER AND SETTER
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public void setBD(int d, int m, int y) {
setDay(d);
setMonth(m);
setYear(y);
}
}
|
package practico17.Steps;
import org.testng.Assert;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import practico17.PageObject.LandingPage;
public class CRMSteps extends BaseSteps {
@When("hago click en CRM")
public void hago_click_en_crm() {
landingPage = new LandingPage(driver);
crmPage = landingPage.goToCrmPage();
}
@Then("ingreso a la pagina de CRM")
public void ingreso_a_la_pagina_de_crm() {
Assert.assertEquals(crmPage.getPageUrl(), "https://www.salesforce.com/mx/crm/", "Se esperaba otra URL");
Assert.assertTrue(crmPage.getPageUrl().contains("crm"));
}
@Then("encuentro informacion sobre los CRM")
public void encuentro_informacion_sobre_los_crm() {
Assert.assertEquals(crmPage.getTextById("que-es-crm"), "¿Qué es CRM?", "Se esperaba otro elemento");
crmPage.closeDriver();
}
}
|
package com.stackroute.userservice.controller;
import com.stackroute.userservice.domain.User;
import com.stackroute.userservice.domain.UserCredentialsDTO;
import com.stackroute.userservice.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* RestController annotation is used to create Restful web services using Spring MVC
*/
@RestController
/**
* RequestMapping annotation maps HTTP requests to handler methods
*/
@RequestMapping("/")
@CrossOrigin
public class UserController {
private UserServiceImpl service;
/*
Constructor autowiring
*/
@Autowired
public UserController(UserServiceImpl service) {
this.service = service;
}
/*
Mapping for registering user
*/
@PostMapping("register")
public ResponseEntity<?> registerUser(@RequestBody User user) {
try {
return new ResponseEntity<User>(service.saveUser(user), HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.CONFLICT);
}
}
/*
Mapping for login of existing user
*/
@PostMapping("login")
public Map<?, ?> login(@RequestBody UserCredentialsDTO credentials) throws Exception {
if(credentials.getEmailId() == null || credentials.getPassword() == null)
throw new Exception("Email and password cannot be empty");
return service.authenticateUser(credentials);
}
/*
Maoping for getting user details based on emailId
*/
@GetMapping("user/{emailId}")
public ResponseEntity<?> getUserDetails(@PathVariable String emailId) {
try {
return new ResponseEntity<User>(service.getUser(emailId), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.CONFLICT);
}
}
}
|
package com.logicbig.example.beanmethodparameters;
public class BeanC {
}
|
class practice //output is 13 and 6//
{
public static void main(String[]arg)
{
int a=10;
int b=a+3;
int c=a-4;
System.out.println(b);
System.out.println(c);
}
}
|
/*
* ### Copyright (C) 2006-2009 Michael Fuchs ###
* ### All Rights Reserved. ###
*
* Author: Michael Fuchs
* E-Mail: michael.fuchs@unico-group.com
* URL: http://www.michael-a-fuchs.de
*/
package org.dbdoclet.tidbit;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.help.HelpBroker;
import javax.help.HelpSet;
import javax.help.HelpSetException;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.MenuElement;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dbdoclet.jive.Anchor;
import org.dbdoclet.jive.Colspan;
import org.dbdoclet.jive.Fill;
import org.dbdoclet.jive.JiveFactory;
import org.dbdoclet.jive.Rowspan;
import org.dbdoclet.jive.dialog.ExceptionBox;
import org.dbdoclet.jive.dialog.Splash;
import org.dbdoclet.jive.model.Settings;
import org.dbdoclet.jive.text.IConsole;
import org.dbdoclet.jive.widget.GridPanel;
import org.dbdoclet.jive.widget.SideBar;
import org.dbdoclet.jive.widget.TopPanel;
import org.dbdoclet.jive.widget.sidebar.SideBarButton;
import org.dbdoclet.jive.widget.sidebar.SideBarGroup;
import org.dbdoclet.manager.RecentManager;
import org.dbdoclet.service.ResourceServices;
import org.dbdoclet.tidbit.action.ActionGenerate;
import org.dbdoclet.tidbit.action.ActionOpenPerspective;
import org.dbdoclet.tidbit.action.ActionOpenProject;
import org.dbdoclet.tidbit.application.Application;
import org.dbdoclet.tidbit.common.Constants;
import org.dbdoclet.tidbit.common.Context;
import org.dbdoclet.tidbit.common.OsgiRuntime;
import org.dbdoclet.tidbit.common.StaticContext;
import org.dbdoclet.tidbit.common.TidbitExceptionHandler;
import org.dbdoclet.tidbit.importer.ImportService;
import org.dbdoclet.tidbit.medium.Generator;
import org.dbdoclet.tidbit.medium.MediumService;
import org.dbdoclet.tidbit.perspective.Perspective;
import org.dbdoclet.tidbit.project.Project;
import org.dbdoclet.trafo.TrafoService;
public class Tidbit extends JFrame implements Application, ChangeListener,
VetoableChangeListener {
class TidbitWindowListener extends WindowAdapter {
@Override
public void windowClosing(WindowEvent event) {
shutdown();
System.exit(0);
}
}
private static Application application;
private static Log logger = LogFactory.getLog(Tidbit.class);
private static final long serialVersionUID = 1L;
private static Splash splash = null;
private final Context context;
private final ArrayList<Generator> generatorList;
private HelpBroker helpBroker;
private boolean locked;
private TidbitMenu menuBar;
private Perspective perspective;
private JPanel perspectivePanel;
private final TidbitComponent serviceComponent;
private SideBar sideBar;
private final String startPerspective = "project";
private TidbitToolBar toolBar;
private TopPanel topPanel;
private JiveFactory wm;
private RecentManager recentManager;
private Tidbit(TidbitComponent serviceComponent, Context context) {
super();
this.serviceComponent = serviceComponent;
this.context = context;
generatorList = new ArrayList<Generator>();
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("F5"), "generate");
StaticContext.setDialogOwner(this);
updatePerspectives();
}
public static Application getApplication(TidbitComponent serviceComponent,
Context context) {
if (application == null) {
application = new Tidbit(serviceComponent, context);
}
return application;
}
@Override
public void addGenerator(Generator generator) {
synchronized (generatorList) {
generatorList.add(generator);
}
}
public void addImportService(ImportService importer) {
if (menuBar != null) {
menuBar.updateImportServices();
}
}
@Override
public void addMenu(String id, JMenu menu) {
if (id == null) {
throw new IllegalArgumentException(
"The argument id must not be null!");
}
if (menu == null) {
throw new IllegalArgumentException(
"The argument menu must not be null!");
}
if (menuBar != null) {
for (int i = 0; i < menuBar.getMenuCount(); i++) {
JMenu m = menuBar.getMenu(i);
if (m != null) {
String name = m.getName();
if (name != null && id.equals(name)) {
return;
}
}
}
menuBar.add(menu, 2);
}
}
public void addPerspective(Perspective perspective) {
if (perspective == null) {
return;
}
perspective.setApplication(this);
if (perspective.isAbstract()) {
return;
}
try {
if (sideBar != null) {
if (sideBar.findButton(perspective.getId()) == null) {
refreshSideBar();
}
sideBar.setSelected(startPerspective);
}
openPerspective(findPerspective(startPerspective));
} catch (IOException oops) {
logger.error("addPerspective", oops);
}
}
/**
* Fügt die Datei der Liste der zuletzt geöffneten Projekte hinzu.
*/
@Override
public void addRecent(File file) {
try {
if (file.isFile()) {
menuBar.addRecent(file);
}
} catch (IOException oops) {
logger.error("addRecent", oops);
}
}
@Override
public void addToolBarButton(String id, AbstractAction action) {
if (id == null) {
throw new IllegalArgumentException(
"The argument id must not be null!");
}
if (toolBar != null) {
for (Component comp : toolBar.getComponents()) {
if (comp != null && comp instanceof JButton) {
JButton button = (JButton) comp;
if (id.equals(button.getName())) {
return;
}
}
}
JButton button = new JButton();
button.setName(id);
button.setAction(action);
toolBar.add(button);
}
}
public void createAndShowGUI() {
try {
logger.debug("createAndShowGui...");
splash.setMessage("GUI");
Settings settings = context.getSettings();
String lnfClassName = settings.getProperty("look-and-feel");
if (lnfClassName != null && lnfClassName.trim().length() > 0) {
try {
UIManager.setLookAndFeel(lnfClassName);
SwingUtilities.updateComponentTreeUI(this);
for (Perspective perspective : application
.getPerspectiveList()) {
if (perspective != null
&& perspective.getPanel() != null) {
SwingUtilities.updateComponentTreeUI(perspective
.getPanel());
}
}
} catch (Throwable oops) {
logger.fatal("Can't create Look and Feel " + lnfClassName,
oops);
}
}
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(2, 2, 2, 2);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
setTitle(Constants.WND_NEW_PROJECT_TITLE);
addWindowListener(new TidbitWindowListener());
menuBar = new TidbitMenu(this);
setJMenuBar(menuBar);
menuBar.createMenu();
toolBar = new TidbitToolBar(this);
toolBar.createInitialToolBar();
GridPanel contentPanel = new GridPanel();
getContentPane().add(contentPanel);
topPanel = new TopPanel();
topPanel.setBackground(Color.white);
topPanel.setLeftImage(ResourceServices.getResourceAsUrl(
"/images/handschrift.png", Tidbit.class.getClassLoader()));
topPanel.setRightImage(ResourceServices.getResourceAsUrl(
"/images/head.gif", Tidbit.class.getClassLoader()));
contentPanel.addComponent(topPanel, Colspan.CS_2, Rowspan.RS_1,
Anchor.NORTHWEST, Fill.HORIZONTAL, new Insets(0, 0, 0, 0));
contentPanel.incrRow();
contentPanel.addComponent(toolBar, Colspan.CS_2, Anchor.NORTHWEST,
Fill.HORIZONTAL);
contentPanel.incrRow();
perspectivePanel = new JPanel();
perspectivePanel.setLayout(new GridLayout());
sideBar = new SideBar();
sideBar.setName("sb.perspective");
refreshSideBar();
contentPanel.addComponent(sideBar, Anchor.NORTHWEST, Fill.VERTICAL);
contentPanel.addComponent(new JScrollPane(perspectivePanel),
Anchor.NORTHWEST, Fill.BOTH);
// contentPanel.addComponent(perspectivePanel,
// Anchor.NORTHWEST, Fill.BOTH);
contentPanel.incrRow();
openPerspective(findPerspective(startPerspective));
sideBar.setSelected(startPerspective);
wm.disableSaveWidgets();
pack();
restoreSizeAndPosition();
lock();
} catch (Exception oops) {
shutdown();
ExceptionBox ebox = new ExceptionBox("Can't create GUI!", oops);
ebox.setVisible(true);
}
}
@Override
public Context getContext() {
return context;
}
public HelpBroker getHelpBroker() {
return helpBroker;
}
@Override
public List<ImportService> getImportServiceList() {
return serviceComponent.getImportServiceList();
}
@Override
public MediumService getMediumService(String id) {
if (id == null) {
throw new IllegalArgumentException(
"The argument id must not be null!");
}
for (MediumService mediumService : getMediumServiceList()) {
if (id.equals(mediumService.getId())) {
return mediumService;
}
}
return null;
}
@Override
public ArrayList<MediumService> getMediumServiceList() {
return serviceComponent.getMediumServiceList();
}
@Override
public List<MediumService> getMediumServiceList(String category) {
List<MediumService> serviceList = serviceComponent
.getMediumServiceList(category);
if (serviceList == null) {
return new ArrayList<MediumService>();
}
return serviceList;
}
@Override
public Perspective getPerspective() {
return perspective;
}
public Perspective getPerspective(String name) {
return serviceComponent.getPerspective(name);
}
@Override
public List<Perspective> getPerspectiveList() {
return serviceComponent.getPerspectiveList();
}
@Override
public Project getProject() {
return context.getProject();
}
public RecentManager getRecentManager() {
if (recentManager == null) {
recentManager = new RecentManager(".tidbit.d");
}
return recentManager;
}
@Override
public TrafoService getTrafoService(String id) {
if (id == null) {
throw new IllegalArgumentException(
"The argument id must not be null!");
}
for (TrafoService trafoService : serviceComponent
.getTrafoServiceList(id)) {
return trafoService;
}
return null;
}
/**
* Das Programm <code>TiDBiT</code> bietet eine grafische Oberfläche zur
* Erstellung und Verwaltung von JavaDoc-Projekten. Die Projekte werden als
* Ant-Dateien gespeichert und stehen so auch zut automatisierten Ausführung
* zur Verfügung.
*
* Die Klasse <code>Tidbit</code> erzeugt die Oberfläche der Anwendung.
*
* @throws IOException
* @throws HelpSetException
* @throws UnsupportedLookAndFeelException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
*/
public void initialize() throws IOException, HelpSetException,
ClassNotFoundException, InstantiationException,
IllegalAccessException, UnsupportedLookAndFeelException {
Toolkit toolkit = Toolkit.getDefaultToolkit();
splash = Splash.getSplash();
URL imageURL = ResourceServices.getResourceAsUrl("/images/splash.gif",
Tidbit.class.getClassLoader());
if (imageURL != null) {
splash.splashImage(toolkit.createImage(imageURL), "TiDBiT");
} else {
logger.error("Couldn't find images!");
}
wm = JiveFactory.getInstance();
wm.setHelpAreaBackground(new Color(240, 224, 208));
wm.setHelpAreaBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.black),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
URL helpSetUrl = ResourceServices.getResourceAsUrl("jhelpset.hs",
Tidbit.class.getClassLoader());
if (helpSetUrl != null) {
HelpSet helpSet = new HelpSet(null, helpSetUrl);
helpBroker = helpSet.createHelpBroker();
helpBroker.enableHelpKey(getRootPane(), "d0e1", helpSet);
wm.setHelpBroker(helpBroker);
wm.setHelpSet(helpSet);
} else {
logger.warn("Couldn't find help set for javahelp system. Help will not be available.");
}
context.getResourceBundle();
URL iconUrl = ResourceServices.getResourceAsUrl("/images/icon.png",
Tidbit.class.getClassLoader());
ImageIcon icon = new ImageIcon(iconUrl, "The dbdoclet icon.");
setIconImage(icon.getImage());
}
public boolean isLocked() {
return locked;
}
/**
* Sperren der Applikation für die Zeit, in der kein Projekt aktiv ist.
*/
@Override
public void lock() {
setLocked(true);
sideBar.setEnabled(false);
perspectivePanel.setVisible(false);
}
@Override
public AbstractAction newGenerateAction(IConsole console,
MediumService service, Perspective perspective) throws IOException {
ResourceBundle res = StaticContext.getResourceBundle();
ActionGenerate action = new ActionGenerate(this, console, service);
JPanel panel = perspective.getPanel();
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F5"), "generate");
panel.getActionMap().put("generate", action);
application.addToolBarButton(
perspective.getId() + ".generate." + service.getId(), action);
JMenu menu = new JMenu(ResourceServices.getString(res, "C_BUILD"));
menu.setName(perspective.getId() + ".menu");
JMenuItem menuItem = new JMenuItem();
menuItem.setAction(action);
menuItem.setAccelerator(KeyStroke.getKeyStroke("F5"));
menu.add(menuItem);
addMenu(perspective.getId() + ".menu", menu);
return action;
}
public void openPerspective(Perspective next) throws IOException {
if (next == null) {
return;
}
if (perspective != null) {
perspective.onLeave();
perspective.setActive(false);
}
next.setActive(true);
next.onEnter();
perspectivePanel.removeAll();
JPanel nextPanel = next.getPanel();
perspectivePanel.add(nextPanel);
perspectivePanel.revalidate();
perspectivePanel.repaint();
nextPanel.revalidate();
perspective = next;
}
@Override
public void refresh() {
//
}
@Override
public void removeGenerator(Generator generator) {
synchronized (generatorList) {
generatorList.remove(generator);
}
}
public void removeImportService(ImportService importer) throws IOException {
for (Perspective perspective : serviceComponent.getPerspectiveList()) {
perspective.refresh();
}
}
public void removeMediumService(MediumService service) throws IOException {
for (Perspective perspective : serviceComponent.getPerspectiveList()) {
perspective.refresh();
}
}
@Override
public void removeMenu(String id) {
if (menuBar != null) {
for (MenuElement menu : menuBar.getSubElements()) {
String name = menu.getComponent().getName();
if (name != null && id.equals(name)) {
menuBar.remove(menu.getComponent());
menuBar.repaint();
return;
}
}
}
}
public void removePerspective(Perspective perspective) {
for (Perspective p : serviceComponent.getPerspectiveList()) {
AbstractAction action = new ActionOpenPerspective(this, p);
sideBar.addButton(new SideBarButton(action));
}
sideBar.prepare();
}
@Override
public void removeToolBarButton(String id) {
if (id == null) {
throw new IllegalArgumentException(
"The argument id must not be null!");
}
if (toolBar != null) {
for (Component comp : toolBar.getComponents()) {
if (comp != null && comp instanceof JButton) {
JButton button = (JButton) comp;
if (id.equals(button.getName())) {
toolBar.remove(comp);
toolBar.repaint();
}
}
}
}
}
@Override
public void reset() {
for (Perspective perspective : serviceComponent.getPerspectiveList()) {
perspective.reset();
}
try {
openPerspective(findPerspective(startPerspective));
sideBar.setSelected(startPerspective);
} catch (IOException oops) {
logger.fatal("reset", oops);
}
}
@Override
public void setDefaultCursor() {
setCursor(Cursor.getDefaultCursor());
setFocusable(true);
setFocusableWindowState(true);
}
@Override
public void setFrameTitle(String title) {
setTitle(Constants.WND_PROJECT_TITLE + title);
topPanel.setTitle(title);
}
public void setLocked(boolean locked) {
this.locked = locked;
}
@Override
public void setProject(Project project) {
context.setProject(project);
}
public void settingsChanged(Settings settings) {
//
}
/**
* Sperrt die Applikation für Änderungen an den Daten und setzt den
* Wait-Cursor.
*/
@Override
public void setWaitCursor() {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
setFocusable(false);
// setEnabled(false);
setFocusableWindowState(false);
}
@Override
public void shutdown() {
for (Generator generator : generatorList) {
generator.kill();
}
Settings settings = context.getSettings();
if (isVisible()) {
Point point = getLocationOnScreen();
if (point.x < 0) {
point.x = 10;
}
if (point.y < 0) {
point.y = 10;
}
settings.setProperty("frame.position.x", String.valueOf(point.x));
settings.setProperty("frame.position.y", String.valueOf(point.y));
Dimension size = getSize();
if (size.width < 640) {
size.width = 640;
}
if (size.height < 380) {
size.height = 380;
}
settings.setProperty("frame.width", String.valueOf(size.width));
settings.setProperty("frame.height", String.valueOf(size.height));
}
settings.setProperty("look-and-feel", UIManager.getLookAndFeel()
.getClass().getName());
if (getProject() != null && getProject().getProjectFile() != null) {
settings.setProperty("project.file", getProject().getProjectFile()
.getAbsolutePath());
}
if (getPerspective() != null) {
settings.setProperty("perspective", getPerspective().getName());
}
try {
settings.store();
} catch (IOException oops) {
oops.printStackTrace();
}
OsgiRuntime osgiRuntime = StaticContext.getOsgiRuntime();
if (osgiRuntime != null) {
osgiRuntime.shutdown();
}
}
public void start(final String[] args, final TidbitComponent host) {
try {
logger.info("Starting Dodo...");
final Tidbit app = this;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
app.createAndShowGUI();
app.setVisible(true);
app.toFront();
app.requestFocus();
} catch (Throwable oops) {
ExceptionBox ebox = new ExceptionBox(
"Error creating GUI!", oops);
ebox.setVisible(true);
ebox.toFront();
return;
}
}
});
if (splash != null) {
splash.close();
}
setWaitCursor();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
while (app.isReady() == false) {
Thread.sleep(300);
}
Settings settings = context.getSettings();
String lastProjectPath = settings
.getProperty("project.file");
if (lastProjectPath != null) {
File lastProjectFile = new File(lastProjectPath);
if (lastProjectFile.exists() == true
&& lastProjectFile.isFile()) {
try {
ActionOpenProject.openProject(app,
lastProjectFile);
} catch (Throwable oops) {
RecentManager recentManager = app
.getRecentManager();
recentManager.remove(lastProjectFile
.getAbsolutePath());
settings.remove("project.file");
TidbitExceptionHandler
.handleException(oops);
}
}
}
String lastPerspective = settings
.getProperty("perspective");
if (lastPerspective != null) {
Perspective perspective = app
.getPerspective(lastPerspective);
if (perspective != null) {
sideBar.setSelected(perspective.getId());
app.openPerspective(perspective);
}
}
app.setDefaultCursor();
} catch (Throwable oops) {
ExceptionBox ebox = new ExceptionBox(
"Error creating GUI!", oops);
ebox.setVisible(true);
ebox.toFront();
return;
}
}
});
} catch (Throwable oops) {
shutdown();
oops.printStackTrace();
if (splash != null) {
splash.close();
}
ExceptionBox ebox = new ExceptionBox("Can't startup GUI!", oops);
ebox.setVisible(true);
ebox.toFront();
}
}
@Override
public void stateChanged(ChangeEvent event) {
try {
Validator validator = new Validator(this, "tab.changed");
validator.check();
} catch (Exception oops) {
ExceptionBox ebox = new ExceptionBox(context.getDialogOwner(), oops);
ebox.setVisible(true);
ebox.toFront();
}
}
@Override
public synchronized void unlock() {
setLocked(false);
sideBar.setEnabled(true);
perspectivePanel.setVisible(true);
toolBar.unlock();
menuBar.unlock();
}
@Override
public void vetoableChange(PropertyChangeEvent event)
throws PropertyVetoException {
logger.debug("vetableChangeEvent=" + event);
}
private Perspective findPerspective(String id) throws IOException {
for (Perspective perspective : serviceComponent.getPerspectiveList()) {
if (perspective.getId().equals(id)) {
return perspective;
}
}
return null;
}
private boolean isReady() {
if (System.getProperty("org.dbdoclet.doclet.debug", "false").equals(
"true")) {
return true;
}
if (serviceComponent.getPerspective("project") != null
&& serviceComponent.getPerspective("Herold") != null
&& serviceComponent.getPerspective("dbdoclet") != null
&& serviceComponent.getPerspective("RTF") != null
&& serviceComponent.getPerspective("PDF") != null
&& serviceComponent.getPerspective("HTML") != null
&& serviceComponent.getPerspective("EPUB") != null
&& serviceComponent.getPerspective("Eclipse") != null
&& serviceComponent.getPerspective("JavaHelp") != null
&& serviceComponent.getPerspective("WordML") != null) {
return true;
}
return false;
}
private void refreshSideBar() throws IOException {
sideBar.clear();
ResourceBundle res = context.getResourceBundle();
SideBarGroup docbookGroup = new SideBarGroup("DocBook", 0);
SideBarGroup htmlGroup = new SideBarGroup("HTML", 1);
SideBarGroup foGroup = new SideBarGroup("XSL:FO", 2);
SideBarGroup othersGroup = new SideBarGroup(ResourceServices.getString(
res, "C_OTHERS"), 3);
for (Perspective perspective : serviceComponent.getPerspectiveList()) {
if (perspective.isAbstract()) {
continue;
}
AbstractAction action = new ActionOpenPerspective(this, perspective);
String id = perspective.getId();
if (id.startsWith("docbook")) {
if (id.startsWith("docbook-html")) {
sideBar.addButton(htmlGroup, new SideBarButton(action),
perspective.getId());
} else if (id.startsWith("docbook-fo")) {
sideBar.addButton(foGroup, new SideBarButton(action),
perspective.getId());
} else {
sideBar.addButton(othersGroup, new SideBarButton(action),
perspective.getId());
}
} else if (id.equals("project")) {
SideBarButton button = new SideBarButton(action, 0);
sideBar.addButton(docbookGroup, button, perspective.getId());
} else {
sideBar.addButton(docbookGroup, new SideBarButton(action),
perspective.getId());
}
}
sideBar.prepare();
if (isLocked()) {
sideBar.setEnabled(false);
}
}
private void restoreSizeAndPosition() {
Settings settings = context.getSettings();
String property;
try {
int x, y, width, height;
property = settings.getProperty("frame.width", "-1");
width = Integer.parseInt(property);
property = settings.getProperty("frame.height", "-1");
height = Integer.parseInt(property);
if (width > 1024 && height > 768) {
setSize(new Dimension(width, height));
}
property = settings.getProperty("frame.position.x", "112");
if (property != null) {
x = Integer.parseInt(property);
property = settings.getProperty("frame.position.y", "34");
if (property != null) {
y = Integer.parseInt(property);
setLocation(x, y);
}
}
} catch (NumberFormatException oops) {
ExceptionBox ebox = new ExceptionBox(this, oops);
ebox.setVisible(true);
ebox.toFront();
setLocationRelativeTo(null);
}
}
private void updatePerspectives() {
for (Perspective perspective : serviceComponent.getPerspectiveList()) {
if (perspective.isAbstract()) {
continue;
}
perspective.setApplication(this);
}
}
}
|
package factoring.fermat;
import java.util.Collection;
import factoring.FactorizationOfLongs;
import factoring.math.PrimeMath;
/**
* Created by Thilo Harich on 02.03.2017.
*/
public class FermatFact implements FactorizationOfLongs {
protected int [] smallFactors = {2,3,5,7,11,13,17,19};
protected int minFactor;
public FermatFact(int minFactor)
{
this.minFactor = minFactor;
}
// TODO take smallFactors[smallFactors.lenght - 1]
public FermatFact()
{
minFactor = 3;
}
// /**
// * In contrast to the trial division we can not be sure that a found factor is a prime
// * so we have to factorize it again
// * @param n
// * @return
// */
// public TreeMultiset<Long> findAllPrimeFactors(long n) {
// TreeMultiset<Long> primeFactors = TreeMultiset.create();
// TreeMultiset<Long> factors = findAllFactors(n);
// while (factors.size() > 0) {
// Multiset.Entry<Long> entry = factors.pollLastEntry();
// long factor = entry.getElement();
//// if (factor*factor > n || factor < 30)
//// primeFactors.add(factor, entry.getCount());
//// else
// {
// TreeMultiset<Long> newFactors = TreeMultiset.create();
// storeFactors(factor, newFactors);
// // if no factor found it is a prime factor
// if (newFactors.lastEntry().getElement() == factor) {
// primeFactors.add(factor, entry.getCount());
// newFactors.pollLastEntry();
// }
// else {
// for (long newFactor : newFactors) {
// factors.add(newFactor, entry.getCount());
// }
// }
// }
// }
// return primeFactors;
// }
//
// /**
// *
// * @param n
// * @param factors
// * @return
// */
// public Collection<Long> storeFactors(long n, Collection<Long> factors) {
// // first make the number odd, this is required by the fermat factorizations
// while ((n & 1) == 0)
// {
// factors.add(2l);
// n = n >> 1;
// }
// if (n>1) {
// long remainder = findFactors(n, factors);
// if (remainder != 1)
// factors.add(remainder);
// }
// return factors;
// }
@Override
public long findFactors(long n, Collection<Long> factors) {
// This part is needed for the mod variants. It also improves performance
for (final int factor : smallFactors)
if (n%factor == 0)
{
if (n/factor > 1)
factors.add(n/factor);
return factor;
}
final long sqrtN = (long) Math.ceil(Math.sqrt(n));
final long xEnd = (n / minFactor + minFactor) / 2;
for (long x = sqrtN; x <= xEnd; x++) {
final long right = x*x - n;
if (PrimeMath.isSquare(right)) {
final long y = PrimeMath.sqrt(right);
final long factorHigh = x + y;
factors.add(factorHigh);
return x - y;
}
}
return n;
}
}
|
/*
* Copyright 2018 Neil Lee <cnneillee@163.com>
*
* 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.bilibili.socialize.login.core.handler.qq;
/**
* @author NeilLee
* @since 2018/1/30 17:04
*/
public class QQLoginInfo {
/**
* ret : 0
* pay_token : xxxxxxxxxxxxxxxx
* pf : openmobile_android
* expires_in : 7776000
* openid : xxxxxxxxxxxxxxxxxxx
* pfkey : xxxxxxxxxxxxxxxxxxx
* msg : sucess
* access_token : xxxxxxxxxxxxxxxxxxxxx
*/
// 表示登录成功
private int ret;
private String pay_token;
private String pf;
private String expires_in;
private String openid;
private String pfkey;
private String msg;
private String access_token;
public int getRet() {
return ret;
}
public void setRet(int ret) {
this.ret = ret;
}
public String getPay_token() {
return pay_token;
}
public void setPay_token(String pay_token) {
this.pay_token = pay_token;
}
public String getPf() {
return pf;
}
public void setPf(String pf) {
this.pf = pf;
}
public String getExpires_in() {
return expires_in;
}
public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getPfkey() {
return pfkey;
}
public void setPfkey(String pfkey) {
this.pfkey = pfkey;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
}
|
package ru.avokin.highlighting;
import java.util.List;
/**
* User: Andrey Vokin
* Date: 05.10.2010
*/
public interface CodeHighlighter {
List<HighlightedCodeBlock> highlight(String text);
}
|
package main.java.algorithms.tsp;
import java.util.ArrayList;
import javafx.application.Platform;
import main.java.graphs.DistanceGrid;
import main.java.graphs.grid.GridTile;
import main.java.main.Vector2;
import main.java.pane.simulation.TspSimulation;
public class TotalEnumeration extends Thread
{
// Variables
private ArrayList<GridTile> tileList;
ArrayList<ArrayList<Integer>> possibilities;
private EnumPath shortestPath;
private DistanceGrid dG;
private TspSimulation simulation;
private boolean logging = false;
private double pathLength = 0;
private int possiblePaths;
private int factor = 0;
private int progress = 0;
private int state = 0; // 0 = inactive, 1 = suspended, 2 = active
private int frameCounter = 0;
// Algorithm controls
public synchronized void suspendII()
{
state = 1;
notify();
}
public synchronized void resumeII()
{
state = 2;
notify();
}
public synchronized void killII()
{
state = 0;
notify();
cleanKill();
}
// Constructors
public TotalEnumeration(ArrayList<GridTile> tileList)
{
this.tileList = tileList;
this.simulation = new TspSimulation();
dG = new DistanceGrid(tileList);
}
public TotalEnumeration(TspSimulation simulation)
{
this(new ArrayList<GridTile>(), simulation);
}
public TotalEnumeration(ArrayList<GridTile> tileList, TspSimulation simulation)
{
this.tileList = tileList;
this.simulation = simulation;
logging = true;
dG = new DistanceGrid(tileList);
}
// getters and/or setters
public ArrayList<Vector2> getShortestPath()
{
return shortestPath.getTiles();
}
public void setTileList(ArrayList<GridTile> tileList) {
this.tileList = tileList;
dG = new DistanceGrid(tileList);
}
public int getPossiblePaths()
{
return possiblePaths;
}
public void showPermutations(int startindex, int[] input)
{
permute(input, 0);
}
// Methods
public int showState()
{
return state;
}
// Main thread
public void run()
{
// preparing algorithm
state = 2;
if (logging)
{
Platform.runLater(new Runnable()
{
@Override
public void run()
{
simulation.addConsoleItem("Starting thread", "ALERT");
}
});
}
// setting up path structure
int[] tileIndexes = new int[tileList.size()];
for (int i = 0; i < tileList.size(); i++)
{
tileIndexes[i] = i;
}
// Calculate amount of "possible" paths
if (state != 0)
{
setFactor(tileList.size());
if (logging)
{
Platform.runLater(new Runnable()
{
@Override
public void run()
{
simulation.addConsoleItem(factor + " Possible paths", "INFO");
}
});
}
}
/* ================= ALGORITHM =============================== */
long startTime = System.nanoTime();
// Calculating shortest path
if(state != 0){
showPermutations(0, tileIndexes);
}
/* ================= ALGORITHM =============================== */
// Applying shortest path
ArrayList<Vector2> shortestPath = new ArrayList<Vector2>();
if (state != 0)
{
shortestPath = this.getShortestPath();
simulation.updatePath(shortestPath);
}
// Finishing algorithm
long stopTime = System.nanoTime();
float duration = ( (stopTime - startTime) / 1000000f) / 1000f; // naar sec
ArrayList<Vector2> pathLength = shortestPath;
if (logging)
{
Platform.runLater(new Runnable()
{
@Override
public void run()
{
simulation.addConsoleItem("duration: " + duration + " ms", "INFO");
simulation.addConsoleItem("Total path distance: " + TspSimulation.CalculatePathLength(pathLength),
"INFO");
}
});
}
// Progress bar resetten
simulation.changeProgression(0);
simulation.grid.setActive(false);
}
// Misc
/* ====================================| Process shortest path |=========================================== */
public void processShortestPath(int[] indexList)
{
double totalLength = 0;
ArrayList<Vector2> tileCoordinates = new ArrayList<>();
int lastIndex = 0;
// loop through indexes
for (int index : indexList)
{
// get difference
double xyDiff = dG.distanceGrid[lastIndex][index];
lastIndex = index;
tileCoordinates.add(new Vector2(tileList.get(index).getXcoord(), tileList.get(index).getYcoord()));
totalLength += xyDiff;
}
int lastCoorX = tileList.get(lastIndex).getXcoord();
int lastCoorY = tileList.get(lastIndex).getYcoord();
double xyDiff = Math.hypot(lastCoorX, lastCoorY);
totalLength += xyDiff;
tileCoordinates.add(new Vector2(lastCoorX, lastCoorY));
if (totalLength < this.pathLength || this.pathLength == 0)
{
this.pathLength = totalLength;
shortestPath = new EnumPath(this.pathLength, tileCoordinates);
}
if(simulation.isFancy.isSelected()){
EnumPath curPath = new EnumPath(this.pathLength, tileCoordinates);
if(frameCounter >= 50000){
simulation.updatePath(curPath.getTiles());
frameCounter = 0;
}else{
frameCounter++;
}
}
if (logging)
{
double calc = (double) this.progress / factor;
simulation.progression.setProgress(calc);
}
}
void permute(int[] a, int k)
{
synchronized (this)
{
while (state == 1)
{
try
{
wait();
}
catch (Exception ex)
{
System.out.println("Something went wrong");
}
}
}
if (state != 0)
{
if (k == a.length)
{
processShortestPath(a);
this.progress++;
}
else
{
for (int i = k; i < a.length; i++)
{
int temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
}
public void setFactor(int m)
{
for (int y = (m - 1); y > 0; y--)
{
m = m * y;
}
this.factor = m;
}
public void cleanKill()
{
simulation.addConsoleItem("The process has been killed", "ALERT");
simulation.addConsoleItem("Removing evidence..", "INFO");
tileList = new ArrayList<GridTile>();
simulation.addConsoleItem("Evidence succesfully removed", "INFO");
}
}
|
package kr.co.hangsho.orders.mappers;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import kr.co.hangsho.customers.vo.Customer;
import kr.co.hangsho.orders.vo.Order;
@Mapper
public interface OrderMapper {
void addOrder(Order order);
int getSeq();
List<Order> getOrders();
Order getOrder(int id);
List<Order> getOrdersByCustomer(Customer customer);
}
|
package mediadif.dataManagement;
import java.util.ArrayList;
/**
*
* @author antnhu
*/
public class ProjectManager extends Staff{
private ArrayList<Project> projects;
public ProjectManager(String code, String firstName, String lastName) {
super(code, firstName, lastName);
projects = new ArrayList();
}
}
|
package net.tnemc.ghost.core.account;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/*
* Ghost Server Plugin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public class GhostAccount {
Map<String, BigDecimal> holdings = new HashMap<>();
private String name;
private UUID id;
public GhostAccount(String name) {
this.name = name;
}
public GhostAccount(UUID id) {
this.id = id;
}
public Map<String, BigDecimal> getHoldings() {
return holdings;
}
public void setHoldings(Map<String, BigDecimal> holdings) {
this.holdings = holdings;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public void setHoldings(String world, String currency, BigDecimal holdings) {
this.holdings.put(world + ":" + currency, holdings);
}
public BigDecimal getHoldings(String world, String currency) {
return this.holdings.getOrDefault(world + ":" + currency, BigDecimal.ZERO);
}
}
|
package com.meritamerica.assignment1;
public class MeritAmericaBankApp {
public static void main(String args[]){
AccountHolder newAccount = new AccountHolder("Reuben", "E", "Pena", "123-45-4567", 100, 1000);
System.out.print(newAccount);
newAccount.checkingAccount.deposit(500);
newAccount.savingsAccount.withdraw(800);
System.out.println(newAccount.checkingAccount);
System.out.println(newAccount.savingsAccount);
AccountHolder newerAccount = new AccountHolder("Alicia", "L", "Gutierrez", "123-44-4567", 200, 500);
newerAccount.checkingAccount.deposit(-500);
newerAccount.savingsAccount.withdraw(600);
System.out.println(newerAccount);
}
}
|
package appium.practice;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.URL;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.service.local.AppiumDriverLocalService;
public class Cclass {
//==================================================================================== START SERVER =====================================================================================================
public static AppiumDriverLocalService service;
public static AndroidDriver<AndroidElement> driver;
public AppiumDriverLocalService startServer() {
//
boolean flag = checkIfServerIsRunnning(4723);
if (!flag) {
service = AppiumDriverLocalService.buildDefaultService();
service.start();
}
return service;
}
public static boolean checkIfServerIsRunnning(int port) {
boolean isServerRunning = false;
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(port);
serverSocket.close();
} catch (IOException e) {
// If control comes here, then it means that the port is in use
isServerRunning = true;
} finally {
serverSocket = null;
}
return isServerRunning;
}
//==================================================================================== RUN EMULATOR ====================================================================================================
public static void startEmulator() throws IOException, InterruptedException {
Runtime.getRuntime().exec(System.getProperty("user.dir") + "\\RunEmulator.bat");
Thread.sleep(6000);
}
//======================================================================================================================================================================================================
public void setUp(String device) throws MalformedURLException {
if (device.equals("iOS")) {
getSetup_ios();
}
if (device.equals("android")) {
getSetup_android();
}
}
public void getSetup_ios() throws MalformedURLException {
URL serverAddress = new URL("http://127.0.0.1:4723/wd/hub");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "");
capabilities.setCapability("automationName", "Appium");
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("platformVersion", "");
capabilities.setCapability("deviceName", "iPhone 5s");
//Set appPath
String userDir = System.getProperty("user.dir");
String localApp = "Lazada.app.zip";
String appPath = userDir + "/" + localApp;
capabilities.setCapability("app", appPath);
driver = new IOSDriver(serverAddress, capabilities);
driverWait = new WebDriverWait(driver, 90);
}
public AndroidDriver<AndroidElement> getSetup_android() throws IOException, InterruptedException {
FileInputStream fis = new FileInputStream(System.getProperty("user.dir") + "\\data.properties");
Properties prop = new Properties();
prop.load(fis);
File appDir = new File("App");
File app = new File(appDir, (String) prop.get(appName));
DesiredCapabilities capabilities = new DesiredCapabilities();
String device = (String) prop.get("device");
// String device= System.getProperty("deviceName");
if (device.contains("Pixel")) {
startEmulator();
}
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, device);
capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "");
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "uiautomator2");
capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 14);
capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
driver = new AndroidDriver<AndroidElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
public void tearDown() throws Exception {
if (driver != null) driver.quit();
}
}
|
package ch.mitti.tetris;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class GameFrame extends JFrame{
JPanel panBackground;
JPanel panGame;
JPanel panScore;
int blocksH;
int blocksW;
GridBagLayout layBackground;
GridBagConstraints c;
BoxLayout layScore;
JLabel score;
JLabel next;
public GameFrame(){
//Initializing Background Panel
layBackground = new GridBagLayout();
panBackground = new JPanel(layBackground);
panBackground.addComponentListener(new ComponentAdapter(){
@Override
public void componentResized(ComponentEvent e){
resizePreview(panGame, panBackground);
}
});
//Amount of Blocks in GameField
blocksH = 20;
blocksW = 10;
//Gridbaglayount and basic Contraint Setup
c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.insets = new Insets(10,10,10,10);
c.anchor = GridBagConstraints.FIRST_LINE_START;
//Score and Preview Panel
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
c.gridwidth = 10;
score = new JLabel("Score");
next = new JLabel("Next");
panScore = new JPanel();
panScore.setLayout(new BoxLayout(panScore, BoxLayout.Y_AXIS));
panScore.add(score);
panScore.add(next);
panBackground.add(panScore);
//Create Game Panel and fill it with fields
panGame = new JPanel(new GridLayout(blocksH, blocksW));
for(int i=0; i<(blocksH*blocksW);i++){
JLabel label = new JLabel("Label");
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panGame.add(label);
}
c.gridy = 0;
c.gridx = 10;
c.gridwidth = 50;
c.gridheight = 100;
panBackground.add(panGame);
//Create Frame
this.getContentPane().add(panBackground);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(800,800);
this.setVisible(true);
this.setResizable(false);
}
//Resize so Field is always same size
public void resizePreview(JPanel panGame, JPanel panBackground){
int w = this.panBackground.getWidth();
int field = (w/100*50)/blocksW;
int dimW = field*blocksW;
int dimH = field*blocksH;
this.panGame.setPreferredSize(new Dimension(dimW, dimH));
this.panBackground.revalidate();
}
public static void main(String[] args) {
GameFrame frame = new GameFrame();
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.service.invoker;
import org.reactivestreams.Publisher;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.ReactiveAdapter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.http.HttpEntity;
import org.springframework.http.codec.multipart.Part;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestPart;
/**
* {@link HttpServiceArgumentResolver} for {@link RequestPart @RequestPart}
* annotated arguments.
*
* <p>The argument may be:
* <ul>
* <li>String -- form field
* <li>{@link org.springframework.core.io.Resource Resource} -- file part
* <li>Object -- content to be encoded (e.g. to JSON)
* <li>{@link HttpEntity} -- part content and headers although generally it's
* easier to add headers through the returned builder
* <li>{@link Part} -- a part from a server request
* <li>{@link Publisher} of any of the above
* </ul>
*
* @author Rossen Stoyanchev
* @since 6.0
*/
public class RequestPartArgumentResolver extends AbstractNamedValueArgumentResolver {
private static final boolean REACTOR_PRESENT =
ClassUtils.isPresent("reactor.core.publisher.Mono", RequestPartArgumentResolver.class.getClassLoader());
@Nullable
private final ReactiveAdapterRegistry reactiveAdapterRegistry;
/**
* Constructor with a {@link HttpExchangeAdapter}, for access to config settings.
* @since 6.1
*/
public RequestPartArgumentResolver(HttpExchangeAdapter exchangeAdapter) {
if (REACTOR_PRESENT) {
this.reactiveAdapterRegistry =
(exchangeAdapter instanceof ReactorHttpExchangeAdapter reactorAdapter ?
reactorAdapter.getReactiveAdapterRegistry() :
ReactiveAdapterRegistry.getSharedInstance());
}
else {
this.reactiveAdapterRegistry = null;
}
}
@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
RequestPart annot = parameter.getParameterAnnotation(RequestPart.class);
return (annot == null ? null :
new NamedValueInfo(annot.name(), annot.required(), null, "request part", true));
}
@Override
protected void addRequestValue(
String name, Object value, MethodParameter parameter, HttpRequestValues.Builder requestValues) {
if (this.reactiveAdapterRegistry != null) {
Class<?> type = parameter.getParameterType();
ReactiveAdapter adapter = this.reactiveAdapterRegistry.getAdapter(type);
if (adapter != null) {
MethodParameter nestedParameter = parameter.nested();
String message = "Async type for @RequestPart should produce value(s)";
Assert.isTrue(!adapter.isNoValue(), message);
Assert.isTrue(nestedParameter.getNestedParameterType() != Void.class, message);
if (requestValues instanceof ReactiveHttpRequestValues.Builder reactiveValues) {
reactiveValues.addRequestPartPublisher(
name, adapter.toPublisher(value), asParameterizedTypeRef(nestedParameter));
}
else {
throw new IllegalStateException(
"RequestPart with a reactive type is only supported with reactive client");
}
return;
}
}
requestValues.addRequestPart(name, value);
}
private static ParameterizedTypeReference<Object> asParameterizedTypeRef(MethodParameter nestedParam) {
return ParameterizedTypeReference.forType(nestedParam.getNestedGenericParameterType());
}
}
|
package adefault.loginscreen;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ListsActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView basic_list;
String[] names = new String[]{"Lokesh", "Vishnu", "Roshan", "XYZ", "ABC"};
NameAdapter adapter;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> defaultAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lists);
basic_list = findViewById(R.id.basic_list);
//Why you need to do this you can pass String array
for (int i = 0; i < names.length; i++)
list.add(names[i]);
//Put adapter as instance variable
// final BasicList adapter = new BasicList(this, android.R.layout.simple_list_item_1, list);
// basic_list.setAdapter(adapter);
// adapter = new NameAdapter(this,android.R.layout.simple_list_item_1,list);
defaultAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
// basic_list.setAdapter(adapter);
basic_list.setOnItemClickListener(this);
basic_list.setAdapter(defaultAdapter);
}
@NonNull
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
Intent a = new Intent(ListsActivity.this, LokeshActivity.class);
String name = (String) adapterView.getItemAtPosition(i);
a.putExtra("title", name);
startActivity(a);
}
// Use name as ListAdapter o
//BaseAdapter
public class NameAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<>();
public NameAdapter(Context context, int textViewResourceId, List<String> objects) {
super(context, textViewResourceId, objects);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// return super.getView(position, convertView, parent);
String name = getItem(position);
convertView = getLayoutInflater().inflate(android.R.layout.simple_list_item_single_choice, null);
TextView title = convertView.findViewById(android.R.id.text1);
title.setText(name);
title.setAllCaps(true);
if (position == 2) {
title.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
} else
title.setTextColor(getResources().getColor(android.R.color.holo_purple));
return convertView;
}
}
}
|
package commands.client;
import java.util.List;
import core.client.ClientFrame;
import net.UserInfo;
import net.client.ClientConnection;
import ui.client.RoomGui;
public class UpdateRoomUIClientCommand implements ClientCommand {
private static final long serialVersionUID = 706856426348903599L;
private final List<UserInfo> userInfos;
public UpdateRoomUIClientCommand(List<UserInfo> userInfos) {
this.userInfos = userInfos;
}
@Override
public void execute(ClientFrame ui, ClientConnection connection) {
RoomGui room = (RoomGui) ui.getPanel().getPanelUI();
room.updatePlayers(userInfos);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.