blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
ea41ef68111f45b85c6ed89f67a902999dbe84b2
|
Java
|
standa/crmf
|
/src/main/java/cz/crmf/model/bo/invoicing/OrderItem.java
|
UTF-8
| 6,301
| 2.171875
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cz.crmf.model.bo.invoicing;
import cz.crmf.model.bo.AbstractBusinessObject;
import java.util.Date;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author standa
*/
@Entity
@Table(name = "orders")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "OrderItem.findAll", query = "SELECT o FROM OrderItem o"),
@NamedQuery(name = "OrderItem.findById", query = "SELECT o FROM OrderItem o WHERE o.id = :id"),
@NamedQuery(name = "OrderItem.findByProductName", query = "SELECT o FROM OrderItem o WHERE o.productName = :productName"),
@NamedQuery(name = "OrderItem.findByDescription", query = "SELECT o FROM OrderItem o WHERE o.description = :description"),
@NamedQuery(name = "OrderItem.findByQuantity", query = "SELECT o FROM OrderItem o WHERE o.quantity = :quantity"),
@NamedQuery(name = "OrderItem.findByUnitPrice", query = "SELECT o FROM OrderItem o WHERE o.unitPrice = :unitPrice"),
@NamedQuery(name = "OrderItem.findByVatRate", query = "SELECT o FROM OrderItem o WHERE o.vatRate = :vatRate"),
@NamedQuery(name = "OrderItem.findByCurrency", query = "SELECT o FROM OrderItem o WHERE o.currency = :currency"),
@NamedQuery(name = "OrderItem.findBySubtotal", query = "SELECT o FROM OrderItem o WHERE o.subtotal = :subtotal"),
@NamedQuery(name = "OrderItem.findByValidFrom", query = "SELECT o FROM OrderItem o WHERE o.validFrom = :validFrom"),
@NamedQuery(name = "OrderItem.findByValidUntil", query = "SELECT o FROM OrderItem o WHERE o.validUntil = :validUntil"),
@NamedQuery(name = "OrderItem.findByReminderDays", query = "SELECT o FROM OrderItem o WHERE o.reminderDays = :reminderDays")})
public class OrderItem extends AbstractBusinessObject {
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 100)
@Column(name = "product_name", nullable = false, length = 100)
private String productName;
@Size(max = 200)
@Column(name = "description", length = 200)
private String description;
@Basic(optional = false)
@NotNull
@Column(name = "quantity", nullable = false)
private int quantity;
@Basic(optional = false)
@NotNull
@Column(name = "unit_price", nullable = false)
private float unitPrice;
@Basic(optional = false)
@NotNull
@Column(name = "vat_rate", nullable = false)
private float vatRate;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 10)
@Column(name = "currency", nullable = false, length = 10)
private String currency;
@Basic(optional = false)
@NotNull
@Column(name = "subtotal", nullable = false)
private float subtotal;
@Column(name = "valid_from")
@Temporal(TemporalType.TIMESTAMP)
private Date validFrom;
@Column(name = "valid_until")
@Temporal(TemporalType.TIMESTAMP)
private Date validUntil;
@Column(name = "reminder_days")
private Integer reminderDays;
@JoinColumn(name = "invoice_id", referencedColumnName = "id", nullable = false)
@ManyToOne(optional = false)
private Invoice invoiceId;
public OrderItem() {
}
public OrderItem(Integer id) {
this.id = id;
}
public OrderItem(Integer id, String productName, int quantity, float unitPrice, float vatRate, String currency, float subtotal) {
this.id = id;
this.productName = productName;
this.quantity = quantity;
this.unitPrice = unitPrice;
this.vatRate = vatRate;
this.currency = currency;
this.subtotal = subtotal;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(float unitPrice) {
this.unitPrice = unitPrice;
}
public float getVatRate() {
return vatRate;
}
public void setVatRate(float vatRate) {
this.vatRate = vatRate;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public float getSubtotal() {
return subtotal;
}
public void setSubtotal(float subtotal) {
this.subtotal = subtotal;
}
public Date getValidFrom() {
return validFrom;
}
public void setValidFrom(Date validFrom) {
this.validFrom = validFrom;
}
public Date getValidUntil() {
return validUntil;
}
public void setValidUntil(Date validUntil) {
this.validUntil = validUntil;
}
public Integer getReminderDays() {
return reminderDays;
}
public void setReminderDays(Integer reminderDays) {
this.reminderDays = reminderDays;
}
public Invoice getInvoiceId() {
return invoiceId;
}
public void setInvoiceId(Invoice invoiceId) {
this.invoiceId = invoiceId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof OrderItem)) {
return false;
}
OrderItem other = (OrderItem) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "cz.crmf.bo.OrderItem[ id=" + id + " ]";
}
}
| true
|
bcb72b5e27ed3ede91f7e51a76e0a4b2de985cca
|
Java
|
EricSeokgon/easyexcelmaker
|
/EasyExcelMaker/src/kr/pe/lahuman/excel/ExcelUtil.java
|
UTF-8
| 14,245
| 2.453125
| 2
|
[] |
no_license
|
package kr.pe.lahuman.excel;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import kr.pe.lahuman.bean.DataMap;
import kr.pe.lahuman.utils.DateUtil;
/**
* The Class ExcelUtil.
*
* @author : lahuman
*/
public class ExcelUtil {
/**
* Make excel. title에서 TITLEVAL$0,0-1 : $x,y값 1개 이상일 경우 startVal-endVal
* keys에서 KEYVAL$type : TYPE 종류 - XY:x,y값 1개 이상일 경우 startVal-endVal - H 시간 만
* 뽑을 경우 - dateType yyyy-MM-dd HH:mm 등등... 주의 사항 : 띄어쓰기 금지!!!
*
* @param response
* the response
* @param fileName
* the file name
* @param searchText
* the search text
* @param titles
* the titles
* @param keys
* the keys
* @param dataMap
* the data map
*/
public static void makeExcel(HttpServletResponse response, String fileName,
String searchText, String[] titles, String[] keys, Map[] dataMap) {
makeExcelCommon(response, fileName, searchText, titles, keys, dataMap,
false);
}
public static void makeExcel(HttpServletResponse response, String fileName,
String searchText, String[] titles, String[] keys, List<Map<String, String>> dataMap) {
makeExcelCommon(response, fileName, searchText, titles, keys, dataMap,
false);
}
/**
* Make excel total.
*
* @param response
* the response
* @param fileName
* the file name
* @param searchText
* the search text
* @param titles
* the titles
* @param keys
* the keys
* @param dataMap
* the data map
*/
public static void makeExcelTotal(HttpServletResponse response,
String fileName, String searchText, String[] titles, String[] keys,
Map[] dataMap) {
makeExcelCommon(response, fileName, searchText, titles, keys, dataMap,
true);
}
/**
* Make excel common.
*
* @param response
* the response
* @param fileName
* the file name
* @param searchText
* the search text
* @param titles
* the titles
* @param keys
* the keys
* @param dataMap
* the data map
* @param isTotal
* the is total
*/
private static void makeExcelCommon(HttpServletResponse response,
String fileName, String searchText, String[] titles, String[] keys,
Map[] dataMap, boolean isTotal) {
WritableWorkbook workbook = null;
try {
// Total 관련 Map
DataMap<String, Integer> totalMap = new DataMap<String, Integer>();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename="
+ fileName);
workbook = Workbook.createWorkbook(response.getOutputStream());
WritableSheet sheet = workbook.createSheet("Sheet1", 0);
jxl.write.WritableCellFormat format = new WritableCellFormat();
jxl.write.WritableCellFormat format0 = new WritableCellFormat();
format.setBackground(jxl.format.Colour.GRAY_25);
format.setBorder(jxl.format.Border.ALL,
jxl.format.BorderLineStyle.THIN);
format.setAlignment(jxl.format.Alignment.CENTRE);
format0.setBackground(jxl.format.Colour.WHITE);
format0.setBorder(jxl.format.Border.ALL,
jxl.format.BorderLineStyle.THIN);
format0.setAlignment(jxl.format.Alignment.CENTRE);
format0.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
sheet.setColumnView(0, 8);
jxl.write.Label label = null;
jxl.write.Blank blank = null;
int heightTemp = 0;
// 검색 조건 삽입
label = new jxl.write.Label(0, 0, searchText);
sheet.addCell(label);
// 해더 만들기
for (int i = 0; i < titles.length; i++) {
if (titles[i].indexOf("$") == -1) {
label = new jxl.write.Label(i, 3, titles[i], format);
heightTemp = 3;
} else {
String[] strs = titles[i].split("\\$");
String[] xy = strs[1].split(",");
// 셀 병합 작업
int startX = 0;
int endX = 0;
int startY = 3;
int endY = 3;
if (xy[0].indexOf("-") != -1 || xy[1].indexOf("-") != -1) {
String[] sxNex = resultScope(xy[0]);
startX = Integer.parseInt(sxNex[0]);
endX = Integer.parseInt(sxNex[1]);
String[] syNey = resultScope(xy[1]);
startY += Integer.parseInt(syNey[0]);
endY += Integer.parseInt(syNey[1]);
if (endY > heightTemp) {
heightTemp = endY;
}
sheet.mergeCells(startX, startY, endX, endY);
} else {
startX = Integer.parseInt(xy[0]);
startY += Integer.parseInt(xy[1]);
}
// 타이틀 삽입
label = new jxl.write.Label(startX, startY, strs[0], format);
}
sheet.addCell(label);
}
heightTemp += 1;
// 내용 붙이기
for (int h = heightTemp; h < (dataMap.length + heightTemp); h++) {
for (int i = 0; i < keys.length; i++) {
DataMap<String, String> data = (DataMap<String, String>) dataMap[h
- heightTemp];
if (keys[i].indexOf("$") == -1) {
label = new jxl.write.Label(i, h, data
.getString(keys[i]), format0);
} else {
String[] strs = keys[i].split("\\$");
if ("H".equals(strs[1])) {
label = new jxl.write.Label(i, h, data.getString(
strs[0]).substring(8, 10)
+ "H", format0);
} else if ("TOT".equals(strs[1])) {
label = new jxl.write.Label(i, h, data
.getString(strs[0]), format0);
totalMap.put(strs[0], totalMap.getInt(strs[0])
+ data.getInt(strs[0]));
} else if (strs[1].indexOf("XY:") != -1) {
if ("".equals(data.getString(strs[0]))) {
continue;
}
String[] xy = strs[1].replaceAll("XY:", "").split(
",");
// 셀 병합 작업
int startX = i;
int endX = i;
int startY = h;
int endY = h;
if (xy[0].indexOf("-") != -1
|| xy[1].indexOf("-") != -1) {
String[] sxNex = resultScope(xy[0]);
startX += Integer.parseInt(sxNex[0]);
endX += Integer.parseInt(sxNex[1]);
String[] syNey = resultScope(xy[1]);
startY += Integer.parseInt(syNey[0]);
endY += Integer.parseInt(syNey[1]);
sheet.mergeCells(startX, startY, endX, endY);
}
label = new jxl.write.Label(i, h, data
.getString(strs[0]), format0);
} else {
label = new jxl.write.Label(i, h, DateUtil
.dateFormat(data.getString(strs[0]),
strs[1]), format0);
}
}
sheet.addCell(label);
}
}
// total 붙이가
if (isTotal) {
label = new jxl.write.Label(0, dataMap.length + heightTemp,
"Total", format);
sheet.addCell(label);
for (int i = 0; i < keys.length; i++) {
String[] strs = keys[i].split("\\$");
if ("TOT".equals(strs[1])) {
label = new jxl.write.Label(i, dataMap.length
+ heightTemp, totalMap.getString(strs[0]),
format);
sheet.addCell(label);
}
}
}
workbook.write();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.flushBuffer();
workbook.close();
} catch (Exception e) {
}
}
}
private static void makeExcelCommon(HttpServletResponse response,
String fileName, String searchText, String[] titles, String[] keys,
List<Map<String, String>> dataList, boolean isTotal) {
WritableWorkbook workbook = null;
try {
// Total 관련 Map
DataMap<String, Integer> totalMap = new DataMap<String, Integer>();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename="
+ fileName);
workbook = Workbook.createWorkbook(response.getOutputStream());
WritableSheet sheet = workbook.createSheet("Sheet1", 0);
jxl.write.WritableCellFormat format = new WritableCellFormat();
jxl.write.WritableCellFormat format0 = new WritableCellFormat();
format.setBackground(jxl.format.Colour.GRAY_25);
format.setBorder(jxl.format.Border.ALL,
jxl.format.BorderLineStyle.THIN);
format.setAlignment(jxl.format.Alignment.CENTRE);
format0.setBackground(jxl.format.Colour.WHITE);
format0.setBorder(jxl.format.Border.ALL,
jxl.format.BorderLineStyle.THIN);
format0.setAlignment(jxl.format.Alignment.CENTRE);
format0.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
sheet.setColumnView(0, 8);
jxl.write.Label label = null;
jxl.write.Blank blank = null;
int heightTemp = 0;
// 검색 조건 삽입
label = new jxl.write.Label(0, 0, searchText);
sheet.addCell(label);
// 해더 만들기
for (int i = 0; i < titles.length; i++) {
if (titles[i].indexOf("$") == -1) {
label = new jxl.write.Label(i, 3, titles[i], format);
heightTemp = 3;
} else {
String[] strs = titles[i].split("\\$");
String[] xy = strs[1].split(",");
// 셀 병합 작업
int startX = 0;
int endX = 0;
int startY = 3;
int endY = 3;
if (xy[0].indexOf("-") != -1 || xy[1].indexOf("-") != -1) {
String[] sxNex = resultScope(xy[0]);
startX = Integer.parseInt(sxNex[0]);
endX = Integer.parseInt(sxNex[1]);
String[] syNey = resultScope(xy[1]);
startY += Integer.parseInt(syNey[0]);
endY += Integer.parseInt(syNey[1]);
if (endY > heightTemp) {
heightTemp = endY;
}
sheet.mergeCells(startX, startY, endX, endY);
} else {
startX = Integer.parseInt(xy[0]);
startY += Integer.parseInt(xy[1]);
}
// 타이틀 삽입
label = new jxl.write.Label(startX, startY, strs[0], format);
}
sheet.addCell(label);
}
heightTemp += 1;
// 내용 붙이기
for (int h = heightTemp; h < (dataList.size()+ heightTemp); h++) {
for (int i = 0; i < keys.length; i++) {
DataMap<String, String> data = (DataMap<String, String>) dataList.get(h- heightTemp);
if (keys[i].indexOf("$") == -1) {
label = new jxl.write.Label(i, h, data
.getString(keys[i]), format0);
} else {
String[] strs = keys[i].split("\\$");
if ("H".equals(strs[1])) {
label = new jxl.write.Label(i, h, data.getString(
strs[0]).substring(8, 10)
+ "H", format0);
} else if ("TOT".equals(strs[1])) {
label = new jxl.write.Label(i, h, data
.getString(strs[0]), format0);
totalMap.put(strs[0], totalMap.getInt(strs[0])
+ data.getInt(strs[0]));
} else if (strs[1].indexOf("XY:") != -1) {
if ("".equals(data.getString(strs[0]))) {
continue;
}
String[] xy = strs[1].replaceAll("XY:", "").split(
",");
// 셀 병합 작업
int startX = i;
int endX = i;
int startY = h;
int endY = h;
if (xy[0].indexOf("-") != -1
|| xy[1].indexOf("-") != -1) {
String[] sxNex = resultScope(xy[0]);
startX += Integer.parseInt(sxNex[0]);
endX += Integer.parseInt(sxNex[1]);
String[] syNey = resultScope(xy[1]);
startY += Integer.parseInt(syNey[0]);
endY += Integer.parseInt(syNey[1]);
sheet.mergeCells(startX, startY, endX, endY);
}
label = new jxl.write.Label(i, h, data
.getString(strs[0]), format0);
} else {
label = new jxl.write.Label(i, h, DateUtil
.dateFormat(data.getString(strs[0]),
strs[1]), format0);
}
}
sheet.addCell(label);
}
}
// total 붙이가
if (isTotal) {
label = new jxl.write.Label(0, dataList.size() + heightTemp,
"Total", format);
sheet.addCell(label);
for (int i = 0; i < keys.length; i++) {
String[] strs = keys[i].split("\\$");
if ("TOT".equals(strs[1])) {
label = new jxl.write.Label(i, dataList.size()
+ heightTemp, totalMap.getString(strs[0]),
format);
sheet.addCell(label);
}
}
}
workbook.write();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.flushBuffer();
workbook.close();
} catch (Exception e) {
}
}
}
/**
* Result scope.
*
* @param val
* the val
* @return the string[]
*/
private static String[] resultScope(String val) {
if (val.indexOf("-") != -1) {
return val.split("-");
} else {
return new String[] { val, val };
}
}
public static List<List<String>> readExcelFile(String filePath) throws Exception {
Workbook workbook = null;
Sheet sheet = null;
List<List<String>> resultList = new ArrayList<List<String>>();
try {
workbook = Workbook.getWorkbook(new File(filePath)); // 존재하는 엑셀파일 경로를 지정
sheet = workbook.getSheet(0); // 첫번째 시트를 지정합니다.
int rowCount = sheet.getRows(); // 총 로우수를 가져옵니다.
int colCount = sheet.getColumns(); // 총 열의 수를 가져옵니다.
if (rowCount <= 0) {
throw new Exception("Read 할 데이터가 엑셀에 존재하지 않습니다.");
}
// 엑셀데이터를 배열에 저장
for (int i = 0; i < rowCount; i++) {
List<String> rowList = new ArrayList<String>();
for (int k = 0; k < colCount; k++) {
Cell cell = sheet.getCell(k, i); // 해당위치의 셀을 가져오는 부분입니다.
if (cell == null)
continue;
// 가져온 셀의 실제 콘텐츠 즉
// 데이터(문자열)를 가져오는 부분입니다.
rowList.add(cell.getContents());
}
resultList.add(rowList);
}
// 데이터 검증 테스트
for(List<String> row : resultList){
for(String cell : row){
System.out.print(cell);
System.out.print("\t");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
try {
if (workbook != null)
workbook.close();
} catch (Exception e) {
}
}
return resultList;
}
}
| true
|
9ad47334a877d3265d97c4e59907d0e78f39d6cb
|
Java
|
sajadalipour7/JPI-Man
|
/jpi-man-phase-3/src/FormDataElementPanel.java
|
UTF-8
| 4,391
| 2.875
| 3
|
[] |
no_license
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* This is a class for Form Data element in middle side
* Also this class extends from JPanel
*/
public class FormDataElementPanel extends JPanel {
//parent panel
private JPanel parentPanel;
private JTextField key;
private JTextField value;
private JCheckBox isActive;
private JButton removeButton;
public static Color colorOfPanel = ColorsForThemes.purpleFore;
public FormDataElementPanel(JPanel parentPanel) {
this.parentPanel = parentPanel;
key = new JTextField("New Name", 14);
key.setForeground(Color.GRAY);
value = new JTextField("New Value", 14);
value.setForeground(Color.GRAY);
isActive = new JCheckBox("", true);
//add icon to remove button
ImageIcon trashIcon = new ImageIcon("./trash.png");
Image scaleImage = trashIcon.getImage().getScaledInstance(15, 20, Image.SCALE_SMOOTH);
ImageIcon scaleImageIcon = new ImageIcon(scaleImage);
removeButton = new JButton(scaleImageIcon);
removeButton.setBackground(new Color(255, 84, 52));
//hover effect for remove button
removeButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
removeButton.setBackground(Color.RED);
}
@Override
public void mouseExited(MouseEvent e) {
removeButton.setBackground(new Color(255, 84, 52));
}
});
removeButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
this.add(key);
this.add(value);
this.add(isActive);
this.add(removeButton);
FormDataElementPanel thisPanel = this;
//Action Listener for remove button
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
thisPanel.setVisible(false);
thisPanel.validate();
parentPanel.remove(thisPanel);
parentPanel.validate();
}
});
Color defaultBackgroundColor = key.getBackground();
//FocusListener for hover effect for key
key.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
if (key.getText().equals("New Name")) {
key.setText("");
key.setForeground(Color.BLACK);
}
//key.setBackground(new Color(147, 215, 218));
key.setBackground(new Color(201, 255, 170));
}
@Override
public void focusLost(FocusEvent e) {
if (key.getText().isEmpty()) {
key.setForeground(Color.GRAY);
key.setText("New Name");
}
key.setBackground(defaultBackgroundColor);
}
});
//FocusListener for hover effect for value
value.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
if (value.getText().equals("New Value")) {
value.setText("");
value.setForeground(Color.BLACK);
}
//value.setBackground(new Color(147, 215, 218));
value.setBackground(new Color(201, 255, 170));
}
@Override
public void focusLost(FocusEvent e) {
if (value.getText().isEmpty()) {
value.setForeground(Color.GRAY);
value.setText("New Value");
}
value.setBackground(defaultBackgroundColor);
}
});
this.setBackground(colorOfPanel);
this.setMaximumSize(new Dimension(410, 35));
this.setMinimumSize(new Dimension(200, 35));
}
public JButton getRemoveButton() {
return removeButton;
}
public JCheckBox getIsActive() {
return isActive;
}
public JPanel getParentPanel() {
return parentPanel;
}
public JTextField getKey() {
return key;
}
public JTextField getValue() {
return value;
}
}
| true
|
846c9663fd8f45397c929fa8ebece90497776dc2
|
Java
|
ajbolous/labRep
|
/serverBackup/GHealth/src/Records/Confirmation.java
|
UTF-8
| 336
| 2.125
| 2
|
[] |
no_license
|
package Records;
import java.util.Date;
public class Confirmation {
private String id;
private Date openDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getOpenDate() {
return openDate;
}
public void setOpenDate(Date openDate) {
this.openDate = openDate;
}
}
| true
|
d72cc4f963f25620c3897e94e3ac28d962593fc6
|
Java
|
yildiz-online/module-window
|
/src/main/java/be/yildizgames/module/window/widget/animation/AnimationBehavior.java
|
UTF-8
| 3,814
| 2.3125
| 2
|
[
"MIT"
] |
permissive
|
/*
* MIT License
*
* Copyright (c) 2019 Grégory Van den Borre
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package be.yildizgames.module.window.widget.animation;
import java.time.Duration;
/**
* @author Grégory Van den Borre
*/
public class AnimationBehavior {
private double fromX;
private double fromY;
private double fromZ;
private double byX;
private double byY;
private double byZ;
private double toX;
private double toY;
private double toZ;
private Duration duration = Duration.ZERO;
public AnimationBehavior() {
super();
}
public final AnimationBehavior setFrom(double from) {
this.fromX = from;
this.fromY = from;
this.fromZ = from;
return this;
}
public final AnimationBehavior setBy(double by) {
this.byX = by;
this.byY = by;
this.byZ = by;
return this;
}
public final AnimationBehavior setTo(double to) {
this.toX = to;
this.toY = to;
this.toZ = to;
return this;
}
public final double getFromX() {
return fromX;
}
public final AnimationBehavior setFromX(double fromX) {
this.fromX = fromX;
return this;
}
public final double getFromY() {
return fromY;
}
public final AnimationBehavior setFromY(double fromY) {
this.fromY = fromY;
return this;
}
public final double getFromZ() {
return fromZ;
}
public final AnimationBehavior setFromZ(double fromZ) {
this.fromZ = fromZ;
return this;
}
public final double getByX() {
return byX;
}
public final AnimationBehavior setByX(double byX) {
this.byX = byX;
return this;
}
public final double getByY() {
return byY;
}
public final AnimationBehavior setByY(double byY) {
this.byY = byY;
return this;
}
public final double getByZ() {
return byZ;
}
public final AnimationBehavior setByZ(double byZ) {
this.byZ = byZ;
return this;
}
public final double getToX() {
return toX;
}
public final AnimationBehavior setToX(double toX) {
this.toX = toX;
return this;
}
public final double getToY() {
return toY;
}
public final AnimationBehavior setToY(double toY) {
this.toY = toY;
return this;
}
public final double getToZ() {
return toZ;
}
public final AnimationBehavior setToZ(double toZ) {
this.toZ = toZ;
return this;
}
public final Duration getDuration() {
return duration;
}
public final AnimationBehavior setDuration(Duration duration) {
this.duration = duration;
return this;
}
}
| true
|
f26b72d789b0a19ce8d71898546b8c4e36ce7e38
|
Java
|
kappaj2/BraintreeTesting
|
/src/main/java/za/co/ajk/braintree/braintree/customers/TestCustomerActivity.java
|
UTF-8
| 6,558
| 2.375
| 2
|
[] |
no_license
|
package za.co.ajk.braintree.braintree.customers;
import java.util.List;
import org.springframework.stereotype.Component;
import com.braintreegateway.Address;
import com.braintreegateway.BraintreeGateway;
import com.braintreegateway.CreditCard;
import com.braintreegateway.Customer;
import com.braintreegateway.CustomerRequest;
import com.braintreegateway.PaymentMethod;
import com.braintreegateway.Result;
import com.braintreegateway.Subscription;
import com.braintreegateway.ValidationError;
import com.braintreegateway.exceptions.UnexpectedException;
@Component
public class TestCustomerActivity {
private BraintreeGateway braintreeGateway;
public TestCustomerActivity(BraintreeGateway braintreeGateway) {
this.braintreeGateway = braintreeGateway;
}
public void testCreateCustomer() {
try {
String validNOnce = "fake-valid-nonce";
String firstName = "Mark";
String lastName = "Jones";
String streetName = "Invalid street address in Capetown";
String postalCode = "1234";
CustomerRequest request = new CustomerRequest()
// .firstName(firstName)
// .lastName(lastName)
// .company("Jones Co.")
// .email("mark.jones@example.com")
// .fax("419-555-1234")
// .phone("614-555-1234")
// .website("http://example.com");
.creditCard() // Option A
.cardholderName("CardHolder name") // Option A
.billingAddress()
.firstName(null)
.lastName(null)
.streetAddress(null)
.postalCode(null)
// .streetAddress(streetName)
// .postalCode(postalCode)
.done() // Done for BillingAddress()
.done() // Done for CreditCard() // Option A
//.done()//
.paymentMethodNonce(validNOnce)
// .expirationDate("01/1211")
/// .cvv("3211")
// .number("41111111111111111")
// .done()
;
Result<Customer> result = braintreeGateway.customer().create(request);
System.out.println("Create customer status : " + result.isSuccess());
if (result.isSuccess()) {
Customer customer = result.getTarget();
String customerId = customer.getId();
List<CreditCard> creditCardList = customer.getCreditCards();
for (CreditCard card:creditCardList) {
System.out.println("Card isDefault : "+card.isDefault());
Address address = card.getBillingAddress();
System.out.println("Card CountryName : " +address.getCountryName());
System.out.println("Card CountryA2 : " +address.getCountryCodeAlpha2());
System.out.println("Card CountryA3 : " +address.getCountryCodeAlpha3());
System.out.println("Card CountryNum : " +address.getCountryCodeNumeric());
System.out.println("Card FirstName : " +address.getFirstName());
System.out.println("Card LAstName : " +address.getLastName());
System.out.println("Card cardholderNAme : " +card.getCardholderName());
}
System.out.println("Size for payment methods is : " + customer.getPaymentMethods().size());
List<? extends PaymentMethod> methods = customer.getPaymentMethods();
for (PaymentMethod method : methods) {
System.out.println(" Payment method token : " + method.getToken());
System.out.println(" Size for subscriptions : " + method.getSubscriptions().size());
List<Subscription> subscriptions = method.getSubscriptions();
for (Subscription sub : subscriptions) {
System.out.println(" Sub ID : " + sub.getId());
System.out.println(" subBalance : " + sub.getBalance());
}
}
System.out.println("Created CustomerId : " + customerId);
//PaymentMethod paymentMethod = braintreeGateway.paymentMethod().find("token");
} else {
System.out.println("Error creating customer : " + result.getMessage());
List<ValidationError> validationErrors = result.getErrors().getAllDeepValidationErrors();
System.out.println("Error list size : " + validationErrors.size());
}
} catch (UnexpectedException unex) {
System.out.println("Unexpected Exception : " + unex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void testUpdateCustomer(String customerId,
String customerName,
String customerLastname) {
CustomerRequest request = new CustomerRequest()
.firstName(customerName)
.lastName(customerLastname);
Result<Customer> updateResult = braintreeGateway.customer().update(customerId, request);
}
public void testGetCustomer(String customerId) {
Customer customer = braintreeGateway.customer().find(customerId);
System.out.println("Customer found : ");
System.out.println("Customer found - id : " + customer.getId());
System.out.println("Customer found - address : " + customer.getAddresses());
System.out.println("Customer found - firstName : " + customer.getFirstName());
System.out.println("Customer found - lastNAme : " + customer.getLastName());
}
}
| true
|
fd6214be760833c090df88942ad6464bd7aa2077
|
Java
|
chaturangalagama/clinic-cutomized-bussines-microservice
|
/util/entity/api-entity/src/main/java/com/ilt/cms/api/entity/common/Address.java
|
UTF-8
| 227
| 1.695313
| 2
|
[] |
no_license
|
package com.ilt.cms.api.entity.common;
import lombok.*;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@ToString
public class Address {
private String address;
private String country;
private String postalCode;
}
| true
|
a5efb73ba02a649120dac7b7d48727d9f897ebf0
|
Java
|
xieliang/spliceengine
|
/db-shared/src/main/java/com/splicemachine/db/iapi/reference/ClassName.java
|
UTF-8
| 7,393
| 1.695313
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
/*
* Apache Derby is a subproject of the Apache DB project, and is licensed under
* the Apache License, Version 2.0 (the "License"); you may not use these files
* 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.
*
* Splice Machine, Inc. has modified this file.
*
* All Splice Machine modifications are Copyright 2012 - 2016 Splice Machine, Inc.,
* and are licensed to you under the License; you may not use this file except in
* compliance with the License.
*
* 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.splicemachine.db.iapi.reference;
/**
List of strings representing class names, which are typically found
for classes with implement the Formatable interface.
These strings are removed from the code to separate them from the
strings which need to be internationalized. It also reduces footprint.
<P>
This class has no methods, all it contains are String's which by default
are public, static and final since they are declared in an interface.
*/
public interface ClassName
{
String STORE_CONGLOMDIR =
"com.splicemachine.db.impl.store.access.ConglomerateDirectory";
String STORE_PCXENA =
"com.splicemachine.db.impl.store.access.PC_XenaVersion";
String DataValueFactory = "com.splicemachine.db.iapi.types.DataValueFactory";
String DataValueDescriptor = "com.splicemachine.db.iapi.types.DataValueDescriptor";
String BooleanDataValue = "com.splicemachine.db.iapi.types.BooleanDataValue";
String BitDataValue = "com.splicemachine.db.iapi.types.BitDataValue";
String StringDataValue = "com.splicemachine.db.iapi.types.StringDataValue";
String DateTimeDataValue = "com.splicemachine.db.iapi.types.DateTimeDataValue";
String NumberDataValue = "com.splicemachine.db.iapi.types.NumberDataValue";
String RefDataValue = "com.splicemachine.db.iapi.types.RefDataValue";
String UserDataValue = "com.splicemachine.db.iapi.types.UserDataValue";
String UserType = "com.splicemachine.db.iapi.types.UserType";
String ConcatableDataValue = "com.splicemachine.db.iapi.types.ConcatableDataValue";
String XMLDataValue = "com.splicemachine.db.iapi.types.XMLDataValue";
String FormatableBitSet = "com.splicemachine.db.iapi.services.io.FormatableBitSet";
String BaseActivation = "com.splicemachine.db.impl.sql.execute.BaseActivation";
String BaseExpressionActivation = "com.splicemachine.db.impl.sql.execute.BaseExpressionActivation";
String CursorActivation = "com.splicemachine.db.impl.sql.execute.CursorActivation";
String Row = "com.splicemachine.db.iapi.sql.Row";
String Qualifier = "com.splicemachine.db.iapi.store.access.Qualifier";
String RunTimeStatistics = "com.splicemachine.db.iapi.sql.execute.RunTimeStatistics";
String Storable = "com.splicemachine.db.iapi.services.io.Storable";
String StandardException = "com.splicemachine.db.iapi.error.StandardException";
String LanguageConnectionContext = "com.splicemachine.db.iapi.sql.conn.LanguageConnectionContext";
String ConstantAction = "com.splicemachine.db.iapi.sql.execute.ConstantAction";
String DataDictionary = "com.splicemachine.db.iapi.sql.dictionary.DataDictionary";
String CursorResultSet = "com.splicemachine.db.iapi.sql.execute.CursorResultSet";
String ExecIndexRow = "com.splicemachine.db.iapi.sql.execute.ExecIndexRow";
String ExecPreparedStatement = "com.splicemachine.db.iapi.sql.execute.ExecPreparedStatement";
String ExecRow = "com.splicemachine.db.iapi.sql.execute.ExecRow";
String Activation = "com.splicemachine.db.iapi.sql.Activation";
String ResultSet = "com.splicemachine.db.iapi.sql.ResultSet";
String FileMonitor = "com.splicemachine.db.impl.services.monitor.FileMonitor";
String GeneratedClass = "com.splicemachine.db.iapi.services.loader.GeneratedClass";
String GeneratedMethod = "com.splicemachine.db.iapi.services.loader.GeneratedMethod";
String GeneratedByteCode = "com.splicemachine.db.iapi.services.loader.GeneratedByteCode";
String Context = "com.splicemachine.db.iapi.services.context.Context";
String NoPutResultSet = "com.splicemachine.db.iapi.sql.execute.NoPutResultSet";
String ResultSetFactory = "com.splicemachine.db.iapi.sql.execute.ResultSetFactory";
String RowFactory = "com.splicemachine.db.iapi.sql.execute.RowFactory";
String RowLocation = "com.splicemachine.db.iapi.types.RowLocation";
String VariableSizeDataValue = "com.splicemachine.db.iapi.types.VariableSizeDataValue";
String ParameterValueSet = "com.splicemachine.db.iapi.sql.ParameterValueSet";
String CurrentDatetime = "com.splicemachine.db.impl.sql.execute.CurrentDatetime";
String MaxMinAggregator = "com.splicemachine.db.impl.sql.execute.MaxMinAggregator";
String SumAggregator = "com.splicemachine.db.impl.sql.execute.SumAggregator";
String CountAggregator = "com.splicemachine.db.impl.sql.execute.CountAggregator";
String AvgAggregator = "com.splicemachine.db.impl.sql.execute.AvgAggregator";
String UserDefinedAggregator = "com.splicemachine.db.impl.sql.execute.UserDefinedAggregator";
String RowNumberFunction = "com.splicemachine.db.impl.sql.execute.RowNumberFunction";
String DenseRankFunction = "com.splicemachine.db.impl.sql.execute.DenseRankFunction";
String RankFunction = "com.splicemachine.db.impl.sql.execute.RankFunction";
String FirstLastValueFunction = "com.splicemachine.db.impl.sql.execute.FirstLastValueFunction";
String LeadLagFunction = "com.splicemachine.db.impl.sql.execute.LeadLagFunction";
// TODO: There's no need to reference spliceengine functions and all the baggage they bring in Derby. See impls of RowNumberFunction, RankFunction and DenseRankFunction
String WindowMaxMinAggregator = "com.splicemachine.derby.impl.sql.execute.operations.window.function.MaxMinAggregator";
String WindowSumAggregator = "com.splicemachine.derby.impl.sql.execute.operations.window.function.SumAggregator";
String WindowAvgAggregator = "com.splicemachine.derby.impl.sql.execute.operations.window.function.AvgAggregator";
String WindowCountAggregator = "com.splicemachine.derby.impl.sql.execute.operations.window.function.CountAggregator";
String ExecutionFactory = "com.splicemachine.db.iapi.sql.execute.ExecutionFactory";
String LanguageFactory ="com.splicemachine.db.iapi.sql.LanguageFactory";
String ParameterValueSetFactory ="com.splicemachine.db.iapi.sql.ParameterValueSetFactory";
String TriggerNewTransitionRows = "com.splicemachine.db.catalog.TriggerNewTransitionRows";
// String TriggerOldTransitionRows = "com.splicemachine.db.catalog.TriggerOldTransitionRows";
String VTICosting = "com.splicemachine.db.vti.VTICosting";
String Authorizer = "com.splicemachine.db.iapi.sql.conn.Authorizer";
String UDTBase = "com.splicemachine.db.shared.common.udt.UDTBase";
}
| true
|
8dd9024649effc528cf259dc63dc248eaf532df3
|
Java
|
pengkunRu/My-App-Portfolio
|
/app/src/main/java/com/example/android/myappportfolio/MainActivity.java
|
UTF-8
| 1,306
| 2.34375
| 2
|
[] |
no_license
|
package com.example.android.myappportfolio;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void actionSpotifyStreamer(View view){
Toast.makeText(this,"This button will launch my Media Streamer app",Toast.LENGTH_SHORT).show();
}
public void actionScoresApp(View view){
Toast.makeText(this,"This button will launch my Score app",Toast.LENGTH_SHORT).show();
}
public void actionLibaryApp(View view){
Toast.makeText(this,"This button will launch my Library app",Toast.LENGTH_SHORT).show();
}
public void actionBuildItBigger(View view){
Toast.makeText(this,"This button will launch my Build It Bigger app",Toast.LENGTH_SHORT).show();
}
public void actionXyzReader(View view){
Toast.makeText(this,"This button will launch my Reader app",Toast.LENGTH_SHORT).show();
}
public void actionMyOwnApp(View view){
Toast.makeText(this,"This button will launch my own app",Toast.LENGTH_SHORT).show();
}
}
| true
|
e420e35fc8719364fea86dedc277b823b59a721f
|
Java
|
arvindrealcoderz/HB916
|
/HBProj08HG-Increment-MultithreadedEnviroment/src/com/nt/test/LoadObjectUsingGetMethodsTest.java
|
UTF-8
| 827
| 2.5625
| 3
|
[] |
no_license
|
package com.nt.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.nt.entity.Product;
import com.nt.util.HibernateUtil;
public class LoadObjectUsingGetMethodsTest {
public static void main(String[] args) {
try (SessionFactory factory=HibernateUtil.getSessionFactory();
Session ses=HibernateUtil.getSession();){
//load object sess.get(-,-)
Transaction tx=null;
try(factory;ses){
tx=ses.beginTransaction();
Product pro=new Product();
//pro.setPid(1);
pro.setPname("Arvind");
pro.setQty(3.3);
pro.setPrice(5000.0);
int id= (int) ses.save(pro);
tx.commit();
System.out.println(id+"=====");
}//try
}catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
c18f4b38e23582915abe4eadce3fab4ef2d8e8c6
|
Java
|
Aliing/WindManager
|
/src/com/ah/be/rest/client/utils/HttpToolkit.java
|
UTF-8
| 13,277
| 2.234375
| 2
|
[] |
no_license
|
package com.ah.be.rest.client.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import com.Ostermiller.util.Base64;
import com.ah.be.common.ConfigUtil;
import com.ah.be.rest.client.contrib.RestSSLSocketFactory;
import com.ah.be.rest.client.models.ResponseModel;
import com.ah.util.Tracer;
public final class HttpToolkit {
private static final Tracer log = new Tracer(HttpToolkit.class.getSimpleName());
private static final String DEFAULT_CHARSET = "UTF-8";
public static ResponseModel doGet(String url, Map<String, String> params, String charset) {
ResponseModel restResponse = null;
if(StringUtils.isNotBlank(url)){
HttpMethod method = new GetMethod();
setMethodParams(method,params);
try {
restResponse = sendRequest(url,method,charset);
} catch (IOException e) {
log.error("HttpToolkit,doGet()",e.getMessage());
}catch (Exception e) {
log.error("HttpToolkit,doGet()",e.getMessage());
} finally {
method.releaseConnection();
}
}
return restResponse;
}
public static HttpClient authenticate(String targetURL, String userName, String password){
URL url = null;
HttpClient client = new HttpClient();
try {
url = new URL(targetURL);
} catch (MalformedURLException e) {
log.error("The target url is not valid ", e);
}
client.getState().setCredentials(
new AuthScope(url.getHost(),url.getPort(), AuthScope.ANY_REALM),
new UsernamePasswordCredentials(userName,password));
return client;
}
public static ResponseModel doGet(String url, Map<String, String> params){
return doGet(url,params,DEFAULT_CHARSET);
}
public static ResponseModel doGet(String url, Map<String, String> params, HttpClient client) {
ResponseModel restResponse = null;
if(StringUtils.isNotBlank(url)){
HttpMethod method = new GetMethod();
setMethodParams(method,params);
try {
restResponse = sendRequest(url,method,client, DEFAULT_CHARSET);
} catch (IOException e) {
log.error("HttpToolkit,doGet()",e.getMessage());
}catch (Exception e) {
log.error("HttpToolkit,doGet()",e.getMessage());
} finally {
method.releaseConnection();
}
}
return restResponse;
}
public static ResponseModel doPostJson(String url, String jsonString, HttpClient client) {
ResponseModel restResponse = null;
if(StringUtils.isNotBlank(url)){
PostMethod method = new PostMethod();
RequestEntity requestEntity = new ByteArrayRequestEntity(jsonString.getBytes(), "application/json");
method.setRequestEntity(requestEntity);
try {
restResponse = sendRequest(url, method, client, DEFAULT_CHARSET);
} catch (Exception e) {
log.error("HttpToolkit,doPostJson()",e.getMessage());
} finally {
method.releaseConnection();
}
}
return restResponse;
}
public static ResponseModel doPost(String url, Map<String, String> params,
String charset) {
ResponseModel restResponse = null;
if(StringUtils.isNotBlank(url)){
HttpMethod method = new PostMethod();
setMethodParams(method,params);
try {
restResponse = sendRequest(url,method,charset);
} catch (Exception e) {
log.error("HttpToolkit,doPost()",e.getMessage());
} finally {
method.releaseConnection();
}
}
return restResponse;
}
/**
* @description short for doPostXML with default charset
* @author huihe
*/
public static ResponseModel doPostXML(String url, String StrParam, HttpClient client){
return doPostXML(url,StrParam,client, DEFAULT_CHARSET);
}
/**
* @description short for doPostXML with default charset
* @author huihe
*/
public static ResponseModel doPostXML4ACMDefaultHead(String url, String StrParam, HttpClient client){
String basic = ConfigUtil.getConfigInfo(ConfigUtil.SECTION_AEROHIVE_MDM,
ConfigUtil.HM_ACM_USER) + ":" +
ConfigUtil.getConfigInfo(ConfigUtil.SECTION_AEROHIVE_MDM,
ConfigUtil.HM_ACM_PASSWORD);
List<Header> headers = new ArrayList<Header>();
headers.add(new Header("Accept","application/xml"));
headers.add(new Header("Authorization", "Basic "+Base64.encode(basic)));
return doPostXMLWithHeaders(url,StrParam,client,headers);
}
/**
* @description Post the XML data to the server
* @param url
* @param strParam
* @param client
* @param charset
* @return
* @author huihe
*/
public static ResponseModel doPostXML(String url, String strParam, HttpClient client, String charset){
ResponseModel restResponse = null;
if(StringUtils.isNotBlank(url)){
PostMethod method = new PostMethod();
try {
if(strParam != null && strParam.length() > 0){
RequestEntity strReqEntity=new StringRequestEntity(strParam,"text/xml","utf-8");
method.setRequestEntity(strReqEntity);
// method.setRequestBody(strParam);
}
restResponse = sendRequest(url,method,client, charset);
} catch (Exception e) {
log.error(e);
} finally {
method.releaseConnection();
}
}
return restResponse;
}
public static ResponseModel doPostXMLWithHeader(String url, String strParam, HttpClient client,Header header){
List<Header> headers = new ArrayList<Header>();
headers.add(header);
return doPostXMLWithHeaders(url,strParam,client,headers);
}
public static ResponseModel doPostXMLWithHeaders(String url, String strParam, HttpClient client,List<Header> headers){
ResponseModel restResponse = null;
if(StringUtils.isNotBlank(url)){
PostMethod method = new PostMethod();
try {
if(strParam != null){
RequestEntity strReqEntity=new StringRequestEntity(strParam,"text/xml","utf-8");
method.setRequestEntity(strReqEntity);
}
if(headers != null){
for(Header header:headers){
method.addRequestHeader(header);
}
}
restResponse = sendRequest(url,method,client, DEFAULT_CHARSET);
} catch (Exception e) {
log.error(e);
} finally {
method.releaseConnection();
}
}
return restResponse;
}
public static ResponseModel doPutXML(String url, String strParam, HttpClient client){
ResponseModel restResponse = null;
if(StringUtils.isNotBlank(url)){
PutMethod method = new PutMethod();
try {
if(strParam != null && strParam.length() > 0){
RequestEntity strReqEntity=new StringRequestEntity(strParam,"text/xml",DEFAULT_CHARSET);
method.setRequestEntity(strReqEntity);
}
restResponse = sendRequest(url,method,client, DEFAULT_CHARSET);
} catch (Exception e) {
log.error(e);
} finally {
method.releaseConnection();
}
}
return restResponse;
}
private static ResponseModel sendRequest(String url,HttpMethod method, HttpClient client, String charset)
throws Exception {
ResponseModel restResponse = null;
if (null != method) {
try {
if(url.startsWith("https://"))
{
String host=url.substring(0,url.indexOf("/",8));
url=url.substring(url.indexOf("/",8));
supportSSL(host,client);
}
method.setPath(url);
int responseCode=client.executeMethod(method);
restResponse = new ResponseModel();
restResponse.setResponseCode(responseCode);
StringBuffer response = new StringBuffer();
BufferedReader reader = null;
if(StringUtils.isBlank(charset)){
charset = DEFAULT_CHARSET;
}
try {
reader = new BufferedReader(new InputStreamReader(
method.getResponseBodyAsStream(), charset));
String line;
while ((line = reader.readLine()) != null) {
response.append(line).append(System.getProperty("line.separator"));
}
} finally {
if (null != reader) {
reader.close();
}
restResponse.setResponseText(response.toString());
}
} finally {
method.releaseConnection();
}
}
return restResponse;
}
public static ResponseModel doPost(String url, Map<String, String> params){
return doPost(url,params,DEFAULT_CHARSET);
}
public static ResponseModel doDelete(String url, Map<String, String> params,
String charset) {
ResponseModel restResponse = null;
if(StringUtils.isNotBlank(url)){
HttpMethod method = new DeleteMethod();
setMethodParams(method,params);
try {
restResponse = sendRequest(url,method,charset);
} catch (Exception e) {
log.error("HttpToolkit,doDelete()",e.getMessage());
} finally {
method.releaseConnection();
}
}
return restResponse;
}
public static ResponseModel doDelete(String url, Map<String, String> params){
return doDelete(url,params,DEFAULT_CHARSET);
}
public static ResponseModel doPut(String url, Map<String, String> params,
String charset) {
ResponseModel restResponse = null;
if(StringUtils.isNotBlank(url)){
HttpMethod method = new PutMethod();
setMethodParams(method,params);
try {
restResponse = sendRequest(url,method,charset);
} catch (Exception e) {
log.error("HttpToolkit,doPut()",e.getMessage());
} finally {
method.releaseConnection();
}
}
return restResponse;
}
public static ResponseModel doPut(String url, Map<String, String> params){
return doPut(url,params,DEFAULT_CHARSET);
}
public static void setMethodParams(HttpMethod method,Map<String,String> map){
if(null != map && !map.isEmpty()){
NameValuePair[] data = new NameValuePair[map.size()];
int i=0;
for (Map.Entry<String, String> entry : map.entrySet()) {
data[i++] = new NameValuePair(entry.getKey(), entry.getValue());
}
method.setQueryString(data);
}
}
private static ResponseModel sendRequest(String url,HttpMethod method, String charset)
throws Exception {
ResponseModel restResponse = null;
if (null != method) {
try {
HttpClient client = new HttpClient();
if(url.startsWith("https://"))
{
String host=url.substring(0,url.indexOf("/",8));
url=url.substring(url.indexOf("/",8));
supportSSL(host,client);
}
method.setPath(url);
int responseCode=client.executeMethod(method);
restResponse = new ResponseModel();
restResponse.setResponseCode(responseCode);
StringBuffer response = new StringBuffer();
BufferedReader reader = null;
if(StringUtils.isBlank(charset)){
charset = DEFAULT_CHARSET;
}
try {
reader = new BufferedReader(new InputStreamReader(
method.getResponseBodyAsStream(), charset));
String line;
while ((line = reader.readLine()) != null) {
response.append(line).append(System.getProperty("line.separator"));
}
} finally {
if (null != reader) {
reader.close();
}
restResponse.setResponseText(response.toString());
}
} finally {
method.releaseConnection();
}
}
return restResponse;
}
public static void supportSSL(String url, HttpClient client) {
if(StringUtils.isBlank(url)) {
return;
}
String siteUrl = StringUtils.lowerCase(url);
if (!(siteUrl.startsWith("https"))) {
return;
}
try {
setSSLProtocol(siteUrl, client);
} catch (Exception e) {
log.error("setProtocol error ", e);
}
// Security.setProperty( "ssl.SocketFactory.provider",
// "com.ah.be.rest.client.contrib.RestSSLSocketFactory");
}
private static void setSSLProtocol(String strUrl, HttpClient client) throws Exception {
URL url = new URL(strUrl);
String host = url.getHost();
int port = url.getPort();
if (port <= 0) {
port = 443;
}
ProtocolSocketFactory factory = new RestSSLSocketFactory();
Protocol authhttps = new Protocol("https", factory, port);
Protocol.registerProtocol("https", authhttps);
// set https protocol
client.getHostConfiguration().setHost(host, port, authhttps);
}
}
| true
|
03da4d7f9d3faa6f4eb696f48ae30b89ce231460
|
Java
|
Aizessa/KSU
|
/IS224/LAB/Lab06/src/Profile.java
|
UTF-8
| 356
| 2.828125
| 3
|
[] |
no_license
|
import java.io.Serializable;
public class Profile implements Serializable {
public String name;
public String bio;
public Profile() {
name = "";
bio = "";
}
public Profile(String name, String bio) {
this.name = name;
this.bio = bio;
}
@Override
public String toString() {
return "Profile [name=" + name + ", bio=" + bio + "]";
}
}
| true
|
8b45144e520c80c93be25ec608a8bd3fcea9f014
|
Java
|
Koligliatis/file_browser
|
/src/ActionCenter.java
|
UTF-8
| 5,601
| 2.6875
| 3
|
[] |
no_license
|
import javax.swing.tree.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.io.File;
// Contains the basic interaction of components
public class ActionCenter {
public Tree tree;
public Panel panel;
public ToolBar toolbar;
public MainFrame frame;
private String currentPath;
private PathHistory history;
private Configuration config;
private boolean writeHistory;
public ActionCenter(Tree tree, Panel panel, ToolBar toolbar, MainFrame frame) {
this.tree = tree;
this.panel = panel;
this.toolbar = toolbar;
this.frame = frame;
history = new PathHistory();
config = new Configuration();
currentPath = "/";
writeHistory = true;
}
// Refresh frame frome tree state
// Get path of selected node and refresh panel
public void refreshFrame() {
tree.setState();
String path = treePathToString(tree.getSelectionPath());
panel.refresh(path);
refreshSearchField();
currentPath = panel.getCurrentPath();
if (writeHistory) {
history.addTail(currentPath + "\n");
}
writeHistory = true;
}
// Finds tree path from regular path
// and fires tree action event with this tree path
public void setSelectionPath(String path) {
TreePath treepath = tree.findTreePath(path);
if (treepath != null) {
tree.setSelectionPath(treepath);
}else {
toolbar.errorPath();
}
}
public void backToPath() {
writeHistory = false;
setSelectionPath(history.getBackLine());
}
public void frontToPath() {
writeHistory = false;
setSelectionPath(history.getFrontLine());
}
// Set search field text base on current path
public void refreshSearchField() {
toolbar.setSearchField(panel.currentPath);
}
// Return current path in string
public String getCurrentPath() {
return panel.currentPath;
}
// Return current tree path
public TreePath getCurrentTreePath() {
return tree.getSelectionPath();
}
// Convert TreePath to string
public String treePathToString(TreePath treepath) {
String newPath = "";
String path = treepath.toString();
path = path.replaceAll("\\]","");
path = path.replaceAll("\\[","");
String tokens [] = path.split("\\, ");
if (tokens[0].equals("root")) {
tokens[0] = "";
}
for (String token : tokens) {
newPath = newPath + token + "/";
}
return newPath;
}
// set layout of action's center panel
// and refresh it
public void setPanelLayout(String layout) {
if (layout.equals("FLOW")) {
panel.buildFlowPanel();
} else if (layout.equals("LIST")) {
panel.buildListPanel();
}
String path = treePathToString(tree.getSelectionPath());
panel.refresh(path);
}
// Find program with extension of file in dictionary
// and run that file with this program
public void runProgram(String name,String extension) {
try {
String path;
Process p;
String program = config.getProgram(extension);
if (program == null) {
JOptionPane.showMessageDialog(frame,"Not found program for this type of file",
"Program not found",JOptionPane.PLAIN_MESSAGE);
} else {
path = program + " " + name;
p = Runtime.getRuntime().exec(path);
p.waitFor();
p.destroy();
}
} catch (IOException e) {
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public void renameFile(String message,File file,String name) {
String dialogMessage;
String textMessage;
boolean returnValue = false;
if (message.equals("ND")) {
dialogMessage = new String("Give a name for the new folder");
textMessage = new String("New Folder");
}else if (message.equals("NF")) {
dialogMessage = new String("Give a name for the new file");
textMessage = new String("New File");
}else if (message.equals("RF")) {
dialogMessage = new String("New name");
textMessage = new String ("Rename File");
}else {
dialogMessage = new String("");
textMessage = new String("");
}
String s = (String)JOptionPane.showInputDialog(
frame,dialogMessage,
textMessage,JOptionPane.PLAIN_MESSAGE,null,
null,name);
if ((s != null) && (s.length() > 0)) {
File newFile = new File(currentPath + s);
file.renameTo(newFile);
}else if (message.equals("ND")){
file.delete();
}else if (message.equals("NF")) {
file.delete();
}
refreshFrame();
}
public void deleteFile(File file) {
Object [] options = {"Delete","Cansel"};
int n = JOptionPane.showOptionDialog(frame,"Are you sure you want to " +
"permanently delete \""+file.getName()+"\"?","Attenstion",
JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,
null,options,options[0]);
if (n == 0) {
file.delete();
}
refreshFrame();
}
public void close() {
history.deleteFile();
}
}
| true
|
48b501de41815ad98ae87284c940c4e42c3f8aeb
|
Java
|
arobld00/shared-costs
|
/src/main/java/com/arobld00/autentia/rest/BalanceResource.java
|
UTF-8
| 1,016
| 2.140625
| 2
|
[] |
no_license
|
package com.arobld00.autentia.rest;
import com.arobld00.autentia.data_services.BalanceService;
import com.arobld00.autentia.rest.dtos.BalanceInputDto;
import com.arobld00.autentia.rest.dtos.DebtOutputDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
//@PreAuthorize("hasRole('USER')")
@RestController
@RequestMapping(BalanceResource.BALANCE)
public class BalanceResource {
public static final String BALANCE = "/balance";
private BalanceService balanceService;
@Autowired
public BalanceResource(BalanceService balanceService) {
this.balanceService = balanceService;
}
/* JSON:
{ "flow": {"Francisco Buyo":"59.15","Alfonso Pérez":"22.55","Raúl González":"-40.85","José María Gutiérrez":"-40.85"} }
*/
@PostMapping
public List<DebtOutputDto> calculateDebt(@RequestBody BalanceInputDto balanceDto) {
return this.balanceService.calculateDebt(balanceDto);
}
}
| true
|
093185f0df8070e088cb6ee9db8925b8108e9d03
|
Java
|
Anas9935/D-Restrau
|
/app/src/main/java/com/example/drestrau/Objects/selectionForChefObject.java
|
UTF-8
| 711
| 2.5625
| 3
|
[] |
no_license
|
package com.example.drestrau.Objects;
public class selectionForChefObject {
private int table;
private String choice;
private String sid;
public selectionForChefObject(){}
public selectionForChefObject(int tab,String ch,String id){
table=tab;
choice=ch;
sid=id;
}
public String getSid() {
return sid;
}
public String getChoice() {
return choice;
}
public int getTable() {
return table;
}
public void setSid(String sid) {
this.sid = sid;
}
public void setChoice(String choice) {
this.choice = choice;
}
public void setTable(int table) {
this.table = table;
}
}
| true
|
f3dceae149266baf5fd87a4478e91da55c2234bd
|
Java
|
opensagres/mongodb-ide
|
/fr.opensagres.nosql.ide.ui/src/fr/opensagres/nosql/ide/ui/internal/actions/servers/ServerRunnerAction.java
|
UTF-8
| 2,560
| 2.328125
| 2
|
[] |
no_license
|
package fr.opensagres.nosql.ide.ui.internal.actions.servers;
import org.eclipse.jface.viewers.ISelectionProvider;
import fr.opensagres.nosql.ide.core.extensions.IServerRunnerType;
import fr.opensagres.nosql.ide.core.model.IServer;
import fr.opensagres.nosql.ide.core.model.ServerState;
import fr.opensagres.nosql.ide.ui.internal.ImageResources;
import fr.opensagres.nosql.ide.ui.internal.actions.AbstractTreeNodeAction;
public class ServerRunnerAction extends AbstractTreeNodeAction {
private final IServerRunnerType serverRunnerType;
private final boolean start;
public ServerRunnerAction(IServerRunnerType serverRunnerType,
boolean start, ISelectionProvider selectionProvider) {
super(selectionProvider, start ? serverRunnerType.getStartName()
: serverRunnerType.getStopName());
this.start = start;
this.serverRunnerType = serverRunnerType;
if (start) {
setImageDescriptor(ImageResources
.getImageDescriptor(ImageResources.IMG_ELCL_START));
setHoverImageDescriptor(ImageResources
.getImageDescriptor(ImageResources.IMG_CLCL_START));
setDisabledImageDescriptor(ImageResources
.getImageDescriptor(ImageResources.IMG_DLCL_START));
} else {
setImageDescriptor(ImageResources
.getImageDescriptor(ImageResources.IMG_ELCL_STOP));
setHoverImageDescriptor(ImageResources
.getImageDescriptor(ImageResources.IMG_CLCL_STOP));
setDisabledImageDescriptor(ImageResources
.getImageDescriptor(ImageResources.IMG_DLCL_STOP));
}
}
@Override
public boolean accept(Object obj) {
if (!(obj instanceof IServer)) {
return false;
}
IServer server = (IServer) obj;
if (!serverRunnerType.getRunner().canSupport(server)) {
return false;
}
if (start) {
return canStartServer(server);
}
return canStopServer(server);
}
private boolean canStartServer(IServer server) {
if (server.getServerState() == ServerState.Connected) {
return false;
}
return true;
}
private boolean canStopServer(IServer server) {
ServerState state = server.getServerState();
if (state == ServerState.Stopped || state == ServerState.Stopping
|| state == ServerState.Disconnected) {
return false;
}
return true;
}
@Override
public void perform(Object obj) {
IServer server = (IServer) obj;
try {
if (start) {
serverRunnerType.getRunner().start(server);
} else {
serverRunnerType.getRunner().stop(server, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
fc97bc906f8e11ca562acdb7a3df27fc77f2c42b
|
Java
|
sivalingamsundararajshanthi/WeatherForecast
|
/app/src/main/java/edu/niu/z1829451/weatherforecast/MainActivity.java
|
UTF-8
| 5,878
| 2
| 2
|
[] |
no_license
|
package edu.niu.z1829451.weatherforecast;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Weather>> {
LocationManager locationManager;
Location lastKnownLocation;
LocationListener locationListener;
private static final int WEATHER_ID = 1;
private RecyclerView mRecyclerView;
private WeatherAdapter mWeatherAdapter;
private TextView todayTemp, todaySummary, todayPlace;
private GpsTracker gpsTracker;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.d("LOCATION", "lat: " + lastKnownLocation.getLatitude() + " long: " + lastKnownLocation.getLongitude());
getSupportLoaderManager().initLoader(WEATHER_ID, null, this);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
todayTemp = findViewById(R.id.temp_today);
todaySummary = findViewById(R.id.sum_today_tv);
todayPlace = findViewById(R.id.place_id);
mRecyclerView = findViewById(R.id.recyclerView_id);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mWeatherAdapter = new WeatherAdapter();
mRecyclerView.setAdapter(mWeatherAdapter);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if(Build.VERSION.SDK_INT<23){
} else {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
Log.d("Granted", "Granted");
gpsTracker = new GpsTracker(this);
// lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lastKnownLocation = gpsTracker.getLocation();
// Log.d("LOCATION", "lat: " + lastKnownLocation.getLatitude() + " long: " + lastKnownLocation.getLongitude());
getSupportLoaderManager().initLoader(WEATHER_ID, null, this);
}
}
}
@NonNull
@Override
public Loader<List<Weather>> onCreateLoader(int i, @Nullable Bundle bundle) {
// return new NetworkLoader(this, 38.9240923, -77.4376809);
return new NetworkLoader(this, lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
}
@Override
public void onLoadFinished(@NonNull Loader<List<Weather>> loader, List<Weather> weathers) {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> address = geocoder.getFromLocation(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude(), 1);
if(address != null && address.size() > 0){
todayPlace.setText(address.get(0).getLocality());
Log.d("Address", address.get(0).toString());
}
} catch (IOException e) {
e.printStackTrace();
}
todayTemp.setText(String.valueOf(weathers.get(0).getTemp()));
todaySummary.setText(weathers.get(0).getSummary());
if(weathers != null){
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
mWeatherAdapter.setWeatherData(weathers);
}
else
Toast.makeText(this, "Failure", Toast.LENGTH_SHORT).show();
}
@Override
public void onLoaderReset(@NonNull Loader<List<Weather>> loader) {
}
}
| true
|
153195187fca70a1ff279b67a8b140a7411ca6da
|
Java
|
liuniandxx/weego_share
|
/src/main/java/com/weego/main/dto/POISpecialDto.java
|
UTF-8
| 280
| 1.90625
| 2
|
[] |
no_license
|
package com.weego.main.dto;
import java.util.List;
public class POISpecialDto {
private List<POISepcialBaseDto> data;
public List<POISepcialBaseDto> getData() {
return data;
}
public void setData(List<POISepcialBaseDto> data) {
this.data = data;
}
}
| true
|
5c4e028cd762912bfd4cc76339badc008b245c28
|
Java
|
abhishek16204/Bhojpuri
|
/app/src/main/java/com/example/utsav/bhojpuri/MyLeaveRecordAdapter.java
|
UTF-8
| 4,030
| 2.0625
| 2
|
[] |
no_license
|
package com.example.utsav.bhojpuri;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerViewAccessibilityDelegate;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MyLeaveRecordAdapter extends RecyclerView.Adapter<MyLeaveRecordAdapter.MyViewHolder> {
Context context;
List<Statuslistt> statuslist=new ArrayList<>();
public MyLeaveRecordAdapter(Context context,List<Statuslistt>statuslist){
this.context=context;
this.statuslist=statuslist;
}
@NonNull
@Override
public MyLeaveRecordAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.my_leave_list,viewGroup,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyLeaveRecordAdapter.MyViewHolder myViewHolder, int i) {
String st="",st1="",st2="",st3="";
if (statuslist.get(i).getStatus().equals("1")){
st="<font color='#FFC107'>...</font>"+"<font color='white'>Pending</font>"+"<font color='#FFC107'>...</font>";
myViewHolder.status.setBackgroundResource(R.drawable.ecclipse2);
}
else if (statuslist.get(i).getStatus().equals("2")){
st="<font color='#4CAF50'>...</font>"+"<font color='white'> Approve </font>"+" <font color='#4CAF50'>...</font>";
myViewHolder.status.setBackgroundResource(R.drawable.ecclipse3);
// myViewHolder.status.setBackgroundColor(ContextCompat.getColor(context,R.color.green));
}
else if (statuslist.get(i).getStatus().equals("3")){
st="<font color='#F44336'>...</font>"+"<font color='white'> Reject </font>"+"<font color='#F44336'>...</font>";
myViewHolder.status.setBackgroundResource(R.drawable.ecclipse1);
}
String s1="<b>"+"Reason : "+"</b>"+statuslist.get(i).getReason();
String s2="<b>"+"Leave type : "+"</b>"+statuslist.get(i).getLeave_type();
String s3="<b>"+"From Date : "+"</b>"+statuslist.get(i).getFromDate();
String s5="<b>"+"Leave Request ID : "+"</b>"+statuslist.get(i).getLeaveRequest_id();
String s6="<b>"+"Created On : "+"</b>"+statuslist.get(i).getCreated_on();
String s7="<b>"+"To Date : "+"</b>"+statuslist.get(i).getToDate();
String s8="<b>"+"Days : "+"</b>"+statuslist.get(i).getDays();
myViewHolder.reason.setText(Html.fromHtml(s1));
myViewHolder.leave_type.setText(Html.fromHtml(s2));
myViewHolder.from_date.setText(Html.fromHtml(s3));
myViewHolder.status.setText(Html.fromHtml(st));
myViewHolder.leave_request_id.setText(Html.fromHtml(s5));
myViewHolder.created_on.setText(Html.fromHtml(s6));
myViewHolder.to_date.setText(Html.fromHtml(s7));
myViewHolder.days.setText(Html.fromHtml(s8));
}
@Override
public int getItemCount() {
return statuslist.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView reason,leave_type,from_date,leave_request_id,created_on,to_date,days,status;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
reason=itemView.findViewById(R.id.reason);
leave_type=itemView.findViewById(R.id.leave_type);
status=itemView.findViewById(R.id.status);
from_date=itemView.findViewById(R.id.from_date);
leave_request_id=itemView.findViewById(R.id.leave_request_id);
created_on=itemView.findViewById(R.id.created_on);
to_date=itemView.findViewById(R.id.to_date);
days=itemView.findViewById(R.id.days);
}
}
}
| true
|
31b63b2dc4d061d48ce3e0f502f064aa7d92c298
|
Java
|
sparfenuk/javaHouse
|
/src/main/java/models/Furniture.java
|
UTF-8
| 4,020
| 2.578125
| 3
|
[] |
no_license
|
package models;
import javafx.concurrent.Task;
import javafx.scene.control.ProgressIndicator;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public abstract class Furniture extends Task<Void> implements Serializable {
private Short electricityLevel;
private Short status;
private Short processClock= 0;
public Integer timer = 0; //seconds
private int interval;
public Furniture() {
electricityLevel = 0;
status = Status.ON;
}
public Furniture(int interval) {
electricityLevel = 0;
status = Status.ON;
this.interval = interval;
}
public Short getProcessClock() {
return processClock;
}
public Short getStatus() {
return status;
}
public void setStatus(Short status) {
this.status = status;
}
public short getElectricityLevel() {
return electricityLevel;
}
public void setElectricityLevel(short electricityLevel) {
this.electricityLevel = electricityLevel;
}
public void setInterval(Integer interval) {
this.interval = interval;
}
public void TimerClock (Short c) {
if (c > 0) {
final Timer writeTime = new Timer();
writeTime.schedule(new TimerTask() {
@Override
public void run(){
if(processClock < 100) {
processClock = (short)(processClock + 5);
System.out.print(processClock + "%" + '\n');
}
}
},interval,c);
}
}
public static boolean Serialize(Furniture furniture){
try {
FileOutputStream fos = new FileOutputStream(furniture.getClass().getName() + ".frn");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(furniture);
fos.close();
oos.close();
return true;
}
catch (Exception e){return false;}
}
public static Furniture DeSerialize(String className){
try {
FileInputStream fis = new FileInputStream(className+ ".frn");
ObjectInputStream oin = new ObjectInputStream(fis);
Furniture furniture = (Furniture) oin.readObject();
oin.close();
fis.close();
return furniture;
}
catch (IOException ioe)
{
ioe.printStackTrace();
return null;
}
catch (ClassNotFoundException c)
{
System.out.println("Class not found");
c.printStackTrace();
return null;
}
}
public static List<Furniture> deSerializeAll()
{
List<Furniture> furnitures = new ArrayList<>();
File dir = new File(".");
File[] listOfFiles = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".frn"); } });
for (File f:listOfFiles
) {
if (f.isFile())
System.out.println(f.getName().replaceFirst("[.][^.]+$", ""));
furnitures.add(Furniture.DeSerialize(f.getName().replaceFirst("[.][^.]+$", "")));
}
return furnitures;
}
@Override
protected Void call() throws Exception {
this.updateProgress(ProgressIndicator.INDETERMINATE_PROGRESS, 1);
this.updateMessage("Running...awa");
for(int i = 0; i < timer; i++)
{
this.updateMessage("Running..." + i);
this.updateProgress((1.0 * i)/timer,1);
Thread.sleep(1000);
}
this.updateMessage("Done");
this.updateProgress(1,1);
return null;
}
@Override
public String toString() {
return "models.Furniture{" +
"electricityLevel=" + electricityLevel +
", status=" + status +
'}';
}
}
| true
|
82591ff87f20acca56a1965df6ad58bd0ae8c4ea
|
Java
|
johny751/StuMgr-Java
|
/guigu_service/src/main/java/com/guigu/service/marketing/IClassesService.java
|
UTF-8
| 2,115
| 2.015625
| 2
|
[] |
no_license
|
package com.guigu.service.marketing;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.guigu.common.marketing.StudentSourceView;
import com.guigu.domain.info.StudentInfo;
import com.guigu.domain.marketing.Classes;
import com.guigu.domain.marketing.Menu;
/**
* 许永康
* @author vip
*
*/
public interface IClassesService {
/**
* 查询s1未满班的班级
* @return
* @throws Exception
*/
List<Menu> queryJoinClass()throws Exception;
/**
* 查询以为报名或预座的生源信息
* @return
* @throws Exception
*/
List<StudentSourceView> queryStudentSource()throws Exception;
/**
* 查询班级信息
* @return
* @throws Exception
*/
Classes queryClass(String td_id)throws Exception;
/**
* 根据id查询生源信息表 -
* @param tss_id
* @return
* @throws Exception
*/
StudentSourceView queryStudentById(String tss_id)throws Exception;
/**
* 添加学生信息表
* @param studentinfo
* @return
* @throws Exception
*/
void saveStudent(StudentInfo studentinfo)throws Exception;
/**
* 修改班级表
* @param rouid
* @return
* @throws Exception
*/
void updetaStudent(String classid)throws Exception;
/**
* 修改生源信息的招生状态
* @param apply
* @param rouid
* @throws Exception
*/
void updateApply(@Param("applyid")String applyid,@Param("rouid")String rouid)throws Exception;
/**
* 根据员工编号查询(T_STATISTICS_SALE)报表编号
*
* @param empID
* @return
*/
String queryStsID(String empID);
/**
* 根据地区或院校名称(T_STATISTICS_SCHOOL)查询报表编号
*
* @param stuSourceArea
* @return
*/
String queryTstID(String stuSourceArea);
/**
* 当生源为报名时修改报名人数及报名率(t_statistics_sale)
*
* @param sts_id
* @throws Exception
*/
void updateSaleEnrollment(String sts_id) throws Exception;
/**
* 当生源为报名时修改报名人数及报名率(t_statistics_school)
*
* @param tst_id
* @throws Exception
*/
void updateSchoolEnrollment(String tst_id) throws Exception;
}
| true
|
0963c713762e2fbaffdb80410831d1139028dc22
|
Java
|
foreverxujiahuan/leetcode
|
/src/main/java/com/leetcode/q9/Main.java
|
UTF-8
| 1,090
| 3.5625
| 4
|
[] |
no_license
|
package com.leetcode.q9;
public class Main {
public static void main(String[] args) {
int x = 0;
boolean res = isPalindrome(x);
System.out.println(res);
}
public static boolean isPalindrome(int x) {
if (x<0) {
return false;
}
return isPalindrome(String.valueOf(x));
}
private static boolean isPalindrome(String s){
int length = s.length();
if (length == 1) {
return true;
}
int index1 = 0;
int index2 = length-1;
if (length%2!=0) {
while (index1!=index2){
if (s.charAt(index1)!=s.charAt(index2)) {
return false;
}
index1 = index1+1;
index2 = index2-1;
}
}else {
while (index1<index2){
if (s.charAt(index1)!=s.charAt(index2)) {
return false;
}
index1 = index1+1;
index2 = index2-1;
}
}
return true;
}
}
| true
|
4c21fd526b4036c77acb4997d6259281d32d2429
|
Java
|
xxx520/nuosi-flow
|
/nuosi-logicflow/src/main/java/com/nuosi/flow/data/limit/DecimalLimit.java
|
UTF-8
| 1,182
| 2.25
| 2
|
[] |
no_license
|
package com.nuosi.flow.data.limit;
import com.nuosi.flow.data.BDataLimit;
import java.math.BigDecimal;
/**
* <p>desc: 小数数据限制和校验 </p>
* <p>date: 2021/4/8 15:30 </p>
*
* @author nuosi fsofs@163.com
* @version v1.0.0
*/
public class DecimalLimit implements BDataLimit {
private int precision = -1;
private int scale = -1;
private BigDecimal maxDecimal = null;
private BigDecimal minDecimal = null;
public int getPrecision() {
return precision;
}
public DecimalLimit setPrecision(int precision) {
this.precision = precision;
return this;
}
public int getScale() {
return scale;
}
public DecimalLimit setScale(int scale) {
this.scale = scale;
return this;
}
public BigDecimal getMaxDecimal() {
return maxDecimal;
}
public DecimalLimit setMaxDecimal(BigDecimal maxDecimal) {
this.maxDecimal = maxDecimal;
return this;
}
public BigDecimal getMinDecimal() {
return minDecimal;
}
public DecimalLimit setMinDecimal(BigDecimal minDecimal) {
this.minDecimal = minDecimal;
return this;
}
}
| true
|
a613ca253475da8b7079d50de8f9829ecaf274bb
|
Java
|
marcschumacher/java-sproc-wrapper
|
/src/test/java/org/zalando/typemapper/namedresult/PrimitiveTestIT.java
|
UTF-8
| 7,045
| 2.265625
| 2
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package org.zalando.typemapper.namedresult;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.zalando.typemapper.AbstractTest;
import org.zalando.typemapper.core.TypeMapper;
import org.zalando.typemapper.core.TypeMapperFactory;
import org.zalando.typemapper.namedresult.results.ClassWithBadPrimitives;
import org.zalando.typemapper.namedresult.results.ClassWithBigDecimal;
import org.zalando.typemapper.namedresult.results.ClassWithEmbed;
import org.zalando.typemapper.namedresult.results.ClassWithEmbedEnumClass;
import org.zalando.typemapper.namedresult.results.ClassWithPrimitives;
import org.zalando.typemapper.namedresult.results.Enumeration;
@RunWith(SpringJUnit4ClassRunner.class)
public class PrimitiveTestIT extends AbstractTest {
@Test
public void testPrimitiveMappings() throws SQLException {
final PreparedStatement ps = connection.prepareStatement("SELECT 1 as i, 2 as l, 'c' as c");
final ResultSet rs = ps.executeQuery();
final TypeMapper<?> mapper = TypeMapperFactory.createTypeMapper(ClassWithPrimitives.class);
int i = 0;
while (rs.next()) {
final ClassWithPrimitives result = (ClassWithPrimitives) mapper.mapRow(rs, i++);
Assert.assertNotNull(result);
Assert.assertEquals(1, result.getI());
Assert.assertEquals(2, result.getL());
Assert.assertEquals('c', result.getC());
}
}
@Test
public void testPrimitiveNotMappedFieldsMappings() throws SQLException {
final PreparedStatement ps = connection.prepareStatement("SELECT 1 as j, 2 as l, 'c' as c");
final ResultSet rs = ps.executeQuery();
final TypeMapper<?> mapper = TypeMapperFactory.createTypeMapper(ClassWithPrimitives.class);
int i = 0;
while (rs.next()) {
final ClassWithPrimitives result = (ClassWithPrimitives) mapper.mapRow(rs, i++);
Assert.assertNotNull(result);
Assert.assertEquals(0, result.getI());
Assert.assertEquals(2, result.getL());
Assert.assertEquals('c', result.getC());
}
}
@Test
public void testPrimitiveBadMappedMappings() throws SQLException {
final PreparedStatement ps = connection.prepareStatement("SELECT 1 as i, 2 as l, 'c' as c");
final ResultSet rs = ps.executeQuery();
final TypeMapper<?> mapper = TypeMapperFactory.createTypeMapper(ClassWithBadPrimitives.class);
int i = 0;
while (rs.next()) {
final ClassWithBadPrimitives result = (ClassWithBadPrimitives) mapper.mapRow(rs, i++);
Assert.assertNotNull(result);
Assert.assertEquals(0, result.getI());
Assert.assertEquals(2, result.getL());
Assert.assertEquals('c', result.getC());
}
}
@Test
public void testPrimitiveMappingsWithEmbed() throws SQLException {
final PreparedStatement ps = connection.prepareStatement("SELECT 1 as i, 2 as l, 'c' as c, 'str' as str");
final ResultSet rs = ps.executeQuery();
final TypeMapper<?> mapper = TypeMapperFactory.createTypeMapper(ClassWithEmbed.class);
int i = 0;
while (rs.next()) {
final ClassWithEmbed result = (ClassWithEmbed) mapper.mapRow(rs, i++);
Assert.assertNotNull(result.getPrimitives());
Assert.assertEquals(1, result.getPrimitives().getI());
Assert.assertEquals(2, result.getPrimitives().getL());
Assert.assertEquals('c', result.getPrimitives().getC());
Assert.assertEquals("str", result.getStr());
}
}
@Test
public void testMappingsWithEmbedEnum() throws SQLException {
final PreparedStatement ps = connection.prepareStatement("SELECT 0 as a, 'VALUE_2' as b, 'str' as str");
final ResultSet rs = ps.executeQuery();
final TypeMapper<?> mapper = TypeMapperFactory.createTypeMapper(ClassWithEmbedEnumClass.class);
int i = 0;
while (rs.next()) {
final ClassWithEmbedEnumClass result = (ClassWithEmbedEnumClass) mapper.mapRow(rs, i++);
Assert.assertNotNull(result.getEmbeddedEnum());
Assert.assertEquals(Enumeration.VALUE_1, result.getEmbeddedEnum().getValue1());
Assert.assertEquals(Enumeration.VALUE_2, result.getEmbeddedEnum().getValue2());
Assert.assertEquals("str", result.getStr());
}
}
@Test
public void testMappingsWithEmbedEnumAndEnumDBTypes() throws SQLException {
final PreparedStatement ps = connection.prepareStatement(
"SELECT 'VALUE_1'::enumeration as a, 'VALUE_2'::enumeration as b, 'str' as str");
final ResultSet rs = ps.executeQuery();
final TypeMapper<?> mapper = TypeMapperFactory.createTypeMapper(ClassWithEmbedEnumClass.class);
int i = 0;
while (rs.next()) {
final ClassWithEmbedEnumClass result = (ClassWithEmbedEnumClass) mapper.mapRow(rs, i++);
Assert.assertNotNull(result.getEmbeddedEnum());
Assert.assertEquals(Enumeration.VALUE_1, result.getEmbeddedEnum().getValue1());
Assert.assertEquals(Enumeration.VALUE_2, result.getEmbeddedEnum().getValue2());
Assert.assertEquals("str", result.getStr());
}
}
@Test
public void testPrimitiveBigDecimalMapper() throws SQLException {
final PreparedStatement ps = connection.prepareStatement("SELECT 1 as i");
final ResultSet rs = ps.executeQuery();
final TypeMapper<?> mapper = TypeMapperFactory.createTypeMapper(ClassWithBigDecimal.class);
int i = 0;
while (rs.next()) {
final ClassWithBigDecimal result = (ClassWithBigDecimal) mapper.mapRow(rs, i++);
Assert.assertEquals(new BigDecimal(1), result.getI());
}
}
@Test
public void testNullString() throws Exception {
final PreparedStatement ps = connection.prepareStatement("SELECT null as str");
final ResultSet rs = ps.executeQuery();
final TypeMapper<?> mapper = TypeMapperFactory.createTypeMapper(ClassWithEmbed.class);
int i = 0;
while (rs.next()) {
final ClassWithEmbed result = (ClassWithEmbed) mapper.mapRow(rs, i++);
Assert.assertNull(result.getStr());
}
}
@Test
public void testEmptyString() throws Exception {
final PreparedStatement ps = connection.prepareStatement("SELECT '' as str");
final ResultSet rs = ps.executeQuery();
final TypeMapper<?> mapper = TypeMapperFactory.createTypeMapper(ClassWithEmbed.class);
int i = 0;
while (rs.next()) {
final ClassWithEmbed result = (ClassWithEmbed) mapper.mapRow(rs, i++);
Assert.assertEquals("", result.getStr());
}
}
}
| true
|
e95e5a04ab4570d5e5f937cb56e9485cbb4b2410
|
Java
|
zls1996/job_analysis
|
/job_analysis/src/main/java/com/jobanalysis/job_analysis/controller/BigDataController.java
|
UTF-8
| 1,644
| 2.078125
| 2
|
[] |
no_license
|
package com.jobanalysis.job_analysis.controller;
import com.jobanalysis.job_analysis.dto.CityJobClassSalaryDto;
import com.jobanalysis.job_analysis.dto.ProfeJob;
import com.jobanalysis.job_analysis.entity.ProfeArea;
import com.jobanalysis.job_analysis.dto.ProfessionDto;
import com.jobanalysis.job_analysis.service.IJobService;
import com.jobanalysis.job_analysis.util.HDFSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
/**
* Created By 朱立松 on 2019/2/19
*/
@RestController
@RequestMapping("/")
public class BigDataController {
@Autowired
private IJobService jobService;
@Autowired
private HDFSUtil hdfsUtil;
@RequestMapping("/test")
public String test() throws IOException {
hdfsUtil.ls("/jobs");
return "ok";
}
/**
* 行业占比分析
* @return
*/
@RequestMapping(value = "/proanaly", method = RequestMethod.GET)
public List<ProfessionDto> professionSort(){
return jobService.professionAnalysis();
}
/**
* 职位区域分析
* @return
*/
@RequestMapping(value = "/professionareaanalysis", method = RequestMethod.GET)
public List<ProfeJob> proAreaAnalysis(){
return jobService.getProfessionJobArea();
}
/**
* 薪资水平分析
* @return
*/
@RequestMapping(value = "/salaryanalysis", method = RequestMethod.POST)
public List<CityJobClassSalaryDto> salaryAnalysis(@RequestBody String[] cities){
return jobService.analysisSalary(cities);
}
}
| true
|
1165e2f5e40ef41d365441479f41e82ae194070a
|
Java
|
joel-nevar/MegaTicTacToe
|
/src/main/java/org/academiadecodigo/felinux/mvc/view/AbstractView.java
|
UTF-8
| 755
| 2.328125
| 2
|
[] |
no_license
|
package org.academiadecodigo.felinux.mvc.view;
import org.academiadecodigo.bootcamp.Prompt;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public abstract class AbstractView implements View {
protected Prompt prompt;
protected PrintWriter writer;
public Prompt getPrompt() {
return prompt;
}
public void setPrompt(Prompt prompt) {
this.prompt = prompt;
}
public PrintWriter getWriter() {
return writer;
}
public void setWriter(PrintWriter writer) {
this.writer = writer;
}
//prompt = new Prompt(socket.getInputStream(), new PrintStream(socket.getOutputStream()));
//writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
}
| true
|
4127a319054988390c850840ab51f272298adeeb
|
Java
|
TadeunASCIImento/conversor-monetario-springboot
|
/src/main/java/br/com/application/models/Item.java
|
UTF-8
| 1,244
| 1.84375
| 2
|
[] |
no_license
|
package br.com.application.models;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@EqualsAndHashCode
@AllArgsConstructor
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Item implements Serializable {
private static final long serialVersionUID = -1257712140364920569L;
@XmlElement(name = "code")
private String code;
@XmlElement(name = "codein")
private String codein;
@XmlElement(name = "name")
private String name;
@XmlElement(name = "high")
private String high;
@XmlElement(name = "low")
private String low;
@XmlElement(name = "varBid")
private String varBid;
@XmlElement(name = "pctChange")
private String pctChange;
@XmlElement(name = "bid")
private String bid;
@XmlElement(name = "ask")
private String ask;
@XmlElement(name = "timestamp")
private String timestamp;
@XmlElement(name = "create_date")
private String createDate;
}
| true
|
c03adf15317d487af1082c09eb368da5a16e4cb8
|
Java
|
developer1Emzac/bgs-sample
|
/src/android/emzac/plugins/SQLiteAndroid.java
|
UTF-8
| 1,736
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.emzac.plugins;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import com.emzac.db.DatabaseHelper;
import com.emzac.networking.ManagerError;
import android.content.Context;
public class SQLiteAndroid extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("update".equals(action)) {
int user = args.getInt(0);
this.update(user, callbackContext);
callbackContext.success();
return true;
} else if ("delete".equals(action)) {
this.delete(args, callbackContext);
callbackContext.success();
return true;
}
return false; // Returning false results in a "MethodNotFound" error.
}
private void update(int user, CallbackContext callbackContext) {
try {
Context context = this.cordova.getActivity().getApplicationContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
boolean foo = dbHelper.update(user);
if ( foo ) {
callbackContext.success();
} else {
ManagerError.newLogMessage(
"SQLiteAndroid.update","No guardo");
callbackContext.error("Ocurrio un error.");
}
} catch ( Exception e) {
ManagerError.newLogMessage(
"SQLiteAndroid.update",e.getMessage());
callbackContext.error("Ocurrio un error.");
}
}
private void delete(JSONArray dataCalendar, CallbackContext callbackContext) {
/*try {
JSONObject obj = dataCalendar.getJSONObject(0);
callbackContext.success();
} catch ( Exception e) {
callbackContext.error("Error al abrir el calendario.");
}*/
}
}
| true
|
08a20f95f0ca6ce8d605ab4255443f139fd0b79c
|
Java
|
STEELERz47/7-20-17
|
/src/org/usfirst/frc/team6359/robot/commands/MoveWithJoystick.java
|
UTF-8
| 1,102
| 2.765625
| 3
|
[] |
no_license
|
package org.usfirst.frc.team6359.robot.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc.team6359.robot.OI;
import org.usfirst.frc.team6359.robot.Robot;
/**
*
*/
public class MoveWithJoystick extends Command {
public MoveWithJoystick() {
// Use requires() here to declare subsystem dependencies
requires(Robot.driveTrain);
}
// Called just before this Command runs the first time
@Override
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
@Override
protected void execute() {
double xIn, yIn;
xIn = OI.driveStick.getRawAxis(0);
yIn = OI.driveStick.getRawAxis(1);
Robot.driveTrain.DriveArcade(xIn, yIn);
}
// Make this return true when this Command no longer needs to run execute()
@Override
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
@Override
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
@Override
protected void interrupted() {
}
}
| true
|
3d6fa31f43f9cdf87c73920657752a40abeea68d
|
Java
|
moinstall/sample-android-portum-sdk
|
/sdk/src/main/java/com/portum/android/sdk/internal/model/AdResponseStatus.java
|
UTF-8
| 370
| 2.203125
| 2
|
[] |
no_license
|
package com.portum.android.sdk.internal.model;
/**
* Created by camobap on 1/22/17.
*/
public enum AdResponseStatus {
SUCCESS("ok"),
NOAD("noad"),
BAD_REQUEST("bad_request"),
UNKNOWN("unknown");
private String mValue;
AdResponseStatus(String value) {
mValue = value;
}
public String value() {
return mValue;
}
}
| true
|
2883d8ffeebc72d67797a83c6523ceae8aee79c9
|
Java
|
tangdexi112/AndroidFastDevelop
|
/Algorithms/src/main/java/com/jiangdg/algorithms/array/Array.java
|
UTF-8
| 4,226
| 4.125
| 4
|
[] |
no_license
|
package com.jiangdg.algorithms.array;
/** 无序数组
* author : jiangdg
* date : 2020/1/18 10:47
* desc : 无序数组是一种顺序存储结构,存储的数据是无序的,第一个元素从下标0开始。
* 特点:优点是插入快,但是指定位置插入也较慢;缺点是查找、删除较慢、大小固定。
*
* version: 1.0
*/
public class Array {
private int[] array; // 内部数组
private int length; // 数组中元素的个数
private int maxSize; // 数组长度
public Array(int maxSize) {
this.maxSize = maxSize;
this.array = new int[maxSize];
this.length = 0;
}
/** 判断某个元素是否存在
*
* @param data 待判断的元素
* @return 元素下标,-1表示不存在
*/
private int contain(int data) {
if(isEmpty()) {
throw new IllegalStateException("array is empty.");
}
for(int i=0; i<length; i++) {
if(array[i] == data) {
return i;
}
}
return -1;
}
/** 插入一个元素
*
* @param data 待插入的元素
*/
private void insert(int data) {
if(isFull()) {
throw new IllegalStateException("array is full.");
}
array[length++] = data;
}
/** 向某个位置插入一个元素
*
* @param index 指定位置下标
* @param data 待插入的元素
*/
private void insert(int index, int data) {
if(isFull()) {
throw new IllegalStateException("array is full.");
}
if(index < 0 || index > size()) {
throw new IllegalArgumentException("index is wrong");
}
// 找到第index位置处
// 将后面的元素向后移动一位
for(int i=length-1; i>0; i--) {
if(i == index) {
array[i] = data;
length++;
break;
}
array[i+1] = array[i];
}
}
/** 删除元素
*
* @param data 待删除的元素
* @return 被删除的元素
*/
private int delete(int data) {
if(isEmpty()) {
throw new IllegalStateException("array is empty.");
}
// 判断data是否存在数组中
int index = contain(data);
if(index == -1) {
return -1;
}
// 将数组长度减1
// 再将index后面的元素依次向前移动一位
length--;
for (int i= index; i<length; i++) {
array[i] = array[i+1];
}
return index;
}
/** 根据下标获取某个元素
*
* @param index 要查找的元素下标
* @return 返回的元素
*/
private int get(int index) {
if(isEmpty()) {
throw new IllegalStateException("array is empty.");
}
if(index < 0 || index > size()) {
throw new IllegalArgumentException("index is wrongg.");
}
return array[index];
}
private boolean isFull() {
return length == maxSize;
}
private boolean isEmpty() {
return length == 0;
}
private int size() {
return length;
}
public static void main(String[] args) {
Array array = new Array(6);
array.insert(7);
array.insert(-1);
array.insert(5);
array.insert(-99);
array.insert(2);
array.insert(34);
printArray(array);
int containIndex = array.contain(-99);
System.out.println("contain index = "+ containIndex);
int data = array.get(3);
System.out.println("get index of data= "+ data);
int deleteIndex = array.delete(-99);
System.out.println("delete index = "+ deleteIndex);
printArray(array);
array.insert(2, 666);
System.out.println("now array'size = "+ array.size());
printArray(array);
}
private static void printArray(Array a) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<a.size();i++) {
sb.append(a.get(i));
sb.append(",");
}
System.out.println(sb.toString());
}
}
| true
|
53ee157b1674d73722d6840f1bcb6e206eb1a122
|
Java
|
Trench-Wars/twcore
|
/src/twcore/bots/multibot/spaceball/spaceball.java
|
UTF-8
| 28,847
| 2.296875
| 2
|
[] |
no_license
|
package twcore.bots.multibot.spaceball;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.TimerTask;
import twcore.bots.MultiModule;
import twcore.core.EventRequester;
import twcore.core.util.ModuleEventRequester;
import twcore.core.events.ArenaJoined;
import twcore.core.events.FrequencyShipChange;
import twcore.core.events.Message;
import twcore.core.events.PlayerDeath;
import twcore.core.events.PlayerEntered;
import twcore.core.events.PlayerLeft;
import twcore.core.events.PlayerPosition;
import twcore.core.events.WeaponFired;
import twcore.core.game.Player;
import twcore.core.game.Ship;
import twcore.core.util.Tools;
/**
Hosts a game of SpaceBall. Objectives:
Prevent the SpaceBall (bot) from reaching your planet's
athmosphere by hitting it with bullets and cannonballs.
Don't cross your planet's boundaries or your engines
will malfunction!
*/
public class spaceball extends MultiModule {
private Ship oShip;
int PLANET_1_BORDER = 7776;
int PLANET_2_BORDER = 8608;
int Y_BORDER_1 = 6864;
int Y_BORDER_2 = 9536;
double BULLET_SPEED = 5000.0;
double BOMB_SPEED = 8000.0;
LinkedList<Projectile> fired_projectiles = new LinkedList<Projectile>();
LinkedList<Cannon> team1_cannons = new LinkedList<Cannon>();
LinkedList<Cannon> team2_cannons = new LinkedList<Cannon>();
HashMap<String, SBPlayer> players = new HashMap<String, SBPlayer>();
TimerTask updateState;
TimerTask killLosers;
TimerTask tenSeconds;
TimerTask fiveSeconds;
int eventState = 0; // 0 = nothing, 1 = starting, 2 = playing, 3 = cleaning up
int botX = 8200;
int botY = 8200;
int lBotX = 8200;
int lBotY = 8200;
int lastMove = 0;
int botVX = 0;
int botVY = 0;
int botMass = 2200;
int inertia = 100;
int winner;
public void init() {
oShip = m_botAction.getShip();
String thisArena = m_botAction.getArenaName();
try {
m_botAction.joinArena(thisArena, (short)6000, (short)6000);
} catch(Exception e) {
m_botAction.joinArena(thisArena);
}
}
/** Request events that this bot requires to receive. */
public void requestEvents(ModuleEventRequester req) {
req.request(this, EventRequester.ARENA_JOINED);
req.request(this, EventRequester.PLAYER_ENTERED);
req.request(this, EventRequester.PLAYER_POSITION);
req.request(this, EventRequester.PLAYER_LEFT);
req.request(this, EventRequester.PLAYER_DEATH);
req.request(this, EventRequester.WEAPON_FIRED);
req.request(this, EventRequester.FREQUENCY_SHIP_CHANGE);
}
public boolean isUnloadable() {
return eventState == 0;
}
/**
This method is called when the module is unloaded
*/
public void cancel() {
m_botAction.cancelTasks();
}
public String[] getModHelpMessage() {
String[] bleh = {
"+------------------------------------------------------------+",
"| SpaceBallBot v.0.97 - author Sika |",
"+------------------------------------------------------------+",
"| SpaceBall objectives: |",
"| Prevent the SpaceBall (bot) from reaching your planet's |",
"| athmosphere by hitting it with bullets and cannonballs. |",
"| Don't cross your planet's boundaries or your engines |",
"| will malfunction!! |",
"+------------------------------------------------------------+",
"| Commands: |",
"| !help OR !about OR !rules - Brings up this message |",
"| !return OR !lagout OR !play - Get in the game |",
"+------------------------------------------------------------+",
"| Host Commands: |",
"| !start - Starts/stops the event |",
"| !intertia <x> - Sets inertia factor to x% |",
"| This determines how much energy is transfered of the |",
"| projectile at maximum distance. (0~100%, def: 100%) |",
"| !die - Kills the bot |",
"+------------------------------------------------------------+"
};
return bleh;
}
public void handleEvent(Message event) {
String name = event.getMessager() != null ? event.getMessager() : m_botAction.getPlayerName(event.getPlayerID());
if (name == null) name = "-anonymous-";
String message = event.getMessage();
if (message.equalsIgnoreCase("!play") || message.equalsIgnoreCase("!return") || message.equalsIgnoreCase("!lagout")) {
if (eventState != 0) {
Player p = m_botAction.getPlayer(name);
if (p != null && p.isShip(0)) {
SBPlayer sbP = players.get(name);
if (sbP != null && sbP.isLagged()) {
m_botAction.setShip(name, 1);
m_botAction.setFreq(name, sbP.getTeam());
sbP.setLagged(false);
} else {
m_botAction.setShip(name, 1);
}
}
}
}
if (message.equalsIgnoreCase("!help") || message.equalsIgnoreCase("!about") || message.equalsIgnoreCase("!rules")) {
if (!name.equals("-anonymous-")) {
handleHelp(name);
}
}
if (!m_botAction.getOperatorList().isER(name)) {
return;
}
if (event.getMessageType() == Message.PRIVATE_MESSAGE && message.equalsIgnoreCase("!die")) {
try {
Thread.sleep(50);
}
catch (Exception e) {};
m_botAction.die("!die by " + name);
}
if (message.startsWith("!start")) {
if (eventState == 2) {
finishGame();
} else if (eventState == 0) {
setupGame();
}
}
if (message.startsWith("!speed ") && message.length() > 7) {
try {
BULLET_SPEED = Integer.parseInt(event.getMessage().substring(7));
} catch(NumberFormatException e) {
m_botAction.sendSmartPrivateMessage(name, "Invalid speed!");
}
}
if (message.startsWith("!inertia ") && message.length() > 9) {
try {
inertia = Integer.parseInt(event.getMessage().substring(9));
if(inertia < 0)
inertia = 0;
else if(inertia > 100)
inertia = 100;
m_botAction.sendSmartPrivateMessage(name, "Inertia factor set to: " + inertia);
} catch (NumberFormatException e) {
m_botAction.sendSmartPrivateMessage(name, "Invalid inertia!");
}
}
if (message.startsWith("!mass ") && message.length() > 6) {
try {
botMass = Integer.parseInt(event.getMessage().substring(6));
} catch(NumberFormatException e) {
m_botAction.sendSmartPrivateMessage(name, "Invalid mass!");
}
}
}
/**
This method handles the PlayerEntered event and welcomes the players
if there is a game in progress.
@param event is the PlayerEntered event to handle
*/
public void handleEvent(PlayerEntered event) {
if (eventState != 0) {
String status = "Welcome to Spaceball! Use !help for instructions";
if (eventState == 2) {
status += " and !play to get in";
}
m_botAction.sendPrivateMessage(event.getPlayerID(), status);
}
}
/**
This method handles the PlayerLeft event and updates players lagstatus
if they are in the event.
@param event is the PlayerLeft event to handle
*/
public void handleEvent(PlayerLeft event) {
if (eventState == 0) {
return;
}
SBPlayer p = players.get(m_botAction.getPlayerName(event.getPlayerID()));
if (p != null && !p.isLagged()) {
p.setLagged(true);
}
}
/**
This method handles the PlayerDeath event and updates players kill/death stats.
@param event is the PlayerDeath event to handle
*/
public void handleEvent(PlayerDeath event) {
if (eventState == 0) {
return;
}
SBPlayer killer = players.get(m_botAction.getPlayerName(event.getKillerID()));
SBPlayer killee = players.get(m_botAction.getPlayerName(event.getKilleeID()));
if (killer != null) {
killer.incrementKills();
}
if (killee != null) {
killee.incrementDeaths();
}
}
/**
This method handles the FrequencyShipChange event and if players change from a ship
to spectator mode, it instructs them how to get back in.
@param event is the FrequencyShipChange event to handle
*/
public void handleEvent(FrequencyShipChange event) {
if (eventState == 0) {
return;
}
Player p2 = m_botAction.getPlayer(event.getPlayerID());
SBPlayer p = players.get(p2.getPlayerName());
if (p != null && event.getShipType() == 0) {
p.setLagged(true);
m_botAction.sendPrivateMessage(p2.getPlayerName(), "Use !return to get back in");
}
}
/**
This method handles the PlayerPosition event. If the player isn't in the
players HashMap, it registers him.
It also checks if the player has crossed the planetary borders and handles
cannons.
@param event is the PlayerPosition event to handle
*/
public void handleEvent(PlayerPosition event) {
if (eventState != 2 && eventState != 3) {
return;
}
SBPlayer p = players.get(m_botAction.getPlayerName(event.getPlayerID()));
if (p == null) {
Player p2 = m_botAction.getPlayer(event.getPlayerID());
if (p2 == null) {
return;
}
players.put(p2.getPlayerName(), new SBPlayer(p2.getPlayerName(), p2.getFrequency()));
return;
}
if (p.isCannon()) {
if (!p.getCannon().isInArea(event.getXLocation(), event.getYLocation())) {
p.getCannon().deAttach();
}
} else {
if (((p.getTeam() == 0 && event.getXLocation() > PLANET_1_BORDER) || (p.getTeam() == 1 && event.getXLocation() < PLANET_2_BORDER)) && p.timeFromEShutDown() > 10) {
p.setLastEShutDown();
m_botAction.sendUnfilteredPrivateMessage(event.getPlayerID(), "*prize #14");
m_botAction.sendPrivateMessage(event.getPlayerID(), "Do not cross the planetary boundaries!");
} else {
ListIterator<Cannon> it;
if (p.getTeam() == 0) {
it = team1_cannons.listIterator();
} else {
it = team2_cannons.listIterator();
}
while (it.hasNext()) {
Cannon c = (Cannon)it.next();
if (!c.inUse() && c.isInArea(event.getXLocation(), event.getYLocation())) {
c.attach(p);
}
}
}
}
}
/**
This method handles the WeaponFired event. If the projectile is a bomb or bullet
it calculates the velocities and adds the projectile to fired_projectiles list.
@param event is the WeaponFired event to handle
*/
public void handleEvent(WeaponFired event) {
if (eventState != 2) {
return;
}
SBPlayer p = players.get(m_botAction.getPlayerName(event.getPlayerID()));
if (p == null) {
// m_botAction.spec(m_botAction.getPlayerName(event.getPlayerID()));
// m_botAction.spec(m_botAction.getPlayerName(event.getPlayerID()));
return;
}
double pSpeed;
if (event.isType(1)) {
p.incrementBulletsFired();
pSpeed = BULLET_SPEED;
} else if (event.isType(3)) {
p.incrementBombsFired();
pSpeed = BOMB_SPEED;
} else {
return;
}
double bearing = Math.PI * 2 * (double)event.getRotation() / 40.0;
/* double bVX = event.getXVelocity() + (short)(pSpeed * Math.sin(bearing));
double bVY = event.getYVelocity() - (short)(pSpeed * Math.cos(bearing));*/
// m_botAction.sendArenaMessage("Weapon phyred! " + p + " X:" + event.getXLocation() + " Y:" + event.getYLocation() + " VX:" + event.getXVelocity() + " BVX:" + bVX + " VY:" + event.getYVelocity() + " BVY:" + bVY);
fired_projectiles.add(new Projectile(p, event.getXLocation() + (short)(10.0 * Math.sin(bearing)), event.getYLocation() - (short)(10.0 * Math.cos(bearing)), event.getXVelocity() + (short)(pSpeed * Math.sin(bearing)), event.getYVelocity() - (short)(pSpeed * Math.cos(bearing)), event.getWeaponType(), event.getWeaponLevel()));
}
/* set ReliableKills 1 (*relkills 1) to make sure your bot receives every packet */
public void handleEvent(ArenaJoined event) {
m_botAction.setReliableKills(1);
oShip = m_botAction.getShip();
}
/**
This method handles spamming players with the help/rules.
@param name is the messager
*/
public void handleHelp(String name) {
String[] out = {
"+------------------------------------------------------------+",
"| SpaceBallBot v.0.97 - author Sika |",
"+------------------------------------------------------------+",
"| SpaceBall objectives: |",
"| Prevent the SpaceBall (bot) from reaching your planet's |",
"| athmosphere by hitting it with bullets and cannonballs. |",
"| Don't cross your planet's boundaries or your engines |",
"| will malfunction!! |",
"+------------------------------------------------------------+",
"| Commands: |",
"| !help OR !about OR !rules - Brings up this message |",
"| !return OR !lagout OR !play - Get in the game |",
"+------------------------------------------------------------+"
};
m_botAction.privateMessageSpam(name, out);
if (m_botAction.getOperatorList().isER(name)) {
String[] out2 = {
"| Host Commands: |",
"| !start - Starts/stops the event |",
"| !intertia <x> - Sets inertia factor to x% |",
"| This determines how much energy is transfered of the |",
"| projectile at maximum distance. (0~100%, def: 100%) |",
"| !die - Kills the bot |",
"+------------------------------------------------------------+"
};
m_botAction.privateMessageSpam(name, out2);
}
}
/**
This method setups the game.
*/
public void setupGame() {
eventState = 1;
m_botAction.toggleLocked();
m_botAction.setDoors(255);
m_botAction.createNumberOfTeams(2);
m_botAction.warpAllRandomly();
m_botAction.sendArenaMessage("Get ready! Starting in 10 seconds..", 2);
team1_cannons.add(new Cannon(7216, 7840, m_botAction));
team1_cannons.add(new Cannon(7200, 8016, m_botAction));
team1_cannons.add(new Cannon(7200, 8368, m_botAction));
team1_cannons.add(new Cannon(7216, 8544, m_botAction));
team2_cannons.add(new Cannon(9168, 7840, m_botAction));
team2_cannons.add(new Cannon(9184, 8016, m_botAction));
team2_cannons.add(new Cannon(9184, 8368, m_botAction));
team2_cannons.add(new Cannon(9168, 8544, m_botAction));
oShip.setShip(7);
oShip.setFreq(1337);
oShip.move(botX, botY);
tenSeconds = new TimerTask() {
public void run() {
startGame();
}
};
m_botAction.scheduleTask(tenSeconds, 10000);
}
/**
This method starts the game.
*/
public void startGame() {
Iterator<Player> i = m_botAction.getPlayingPlayerIterator();
while (i.hasNext()) {
Player p = (Player) i.next();
if (!p.getPlayerName().equalsIgnoreCase(m_botAction.getBotName())) {
m_botAction.setShip(p.getPlayerName(), 1);
players.put(p.getPlayerName(), new SBPlayer(p.getPlayerName(), p.getFrequency()));
}
}
eventState = 2;
m_botAction.setDoors(0);
m_botAction.sendArenaMessage("Go go go! Aim for your lives!", 104);
updateState = new TimerTask() {
public void run() {
updateState();
}
};
m_botAction.scheduleTaskAtFixedRate(updateState, 1000, 100);
}
/**
This method finishes the game.
*/
public void finishGame() {
if (updateState != null)
m_botAction.cancelTask(updateState);
botX = 8200;
botY = 8200;
lBotX = 8200;
lBotY = 8200;
lastMove = 0;
botVX = 0;
botVY = 0;
oShip.move(botX, botY);
oShip.setShip(8);
displayScores();
players.clear();
team1_cannons.clear();
team1_cannons.clear();
m_botAction.toggleLocked();
eventState = 0;
}
/**
This method displays the end game stats .. quite messy :O
*/
public void displayScores() {
Comparator<String> a = new Comparator<String>() {
public int compare(String oa, String ob) {
SBPlayer pa = players.get(oa), pb = players.get(ob);
if (pb.getTotalHits() > pa.getTotalHits()) {
return 1;
} else {
return 0;
}
};
};
String[] sorted_p = players.keySet().toArray(new String[players.size()]);
Arrays.sort(sorted_p, a);
m_botAction.sendArenaMessage(",----------------+ Planet " + winner + " has survived +----------------.");
m_botAction.sendArenaMessage("| PLANET 1 PLANET 2 |");
m_botAction.sendArenaMessage("+---------------+-----------+ +---------------+-----------+");
m_botAction.sendArenaMessage("| Name | Hits Acc% | | Name | Hits Acc% |");
m_botAction.sendArenaMessage("+---------------+-----------+ +---------------+-----------+");
ArrayList<String> p_1out = new ArrayList<String>();
ArrayList<String> p_2out = new ArrayList<String>();
SBPlayer mostHits = null;
SBPlayer bestAcc = null;
SBPlayer mostKills = null;
SBPlayer mostDeaths = null;
for (int i = 0; i < sorted_p.length; i++) {
SBPlayer p = players.get(sorted_p[i]);
if (mostHits == null || p.getTotalHits() > mostHits.getTotalHits()) {
mostHits = p;
}
if (bestAcc == null || p.getAccuracy() > bestAcc.getAccuracy()) {
bestAcc = p;
}
if (mostKills == null || p.getKills() > mostKills.getKills()) {
mostKills = p;
}
if (mostDeaths == null || p.getDeaths() > mostDeaths.getDeaths()) {
mostDeaths = p;
}
if (p.getTeam() == 0) {
p_1out.add("| " + Tools.formatString(p.getName(), 14) + " " + rightenString(Integer.toString(p.getTotalHits()), 4) + " " + rightenString(p.getAccuracy() + "%", 4));
} else {
p_2out.add(Tools.formatString(p.getName(), 14) + " " + rightenString(Integer.toString(p.getTotalHits()), 4) + " " + rightenString(p.getAccuracy() + "%", 4) + " |");
}
}
String out1[] = p_1out.toArray(new String[p_1out.size()]);
String out2[] = p_2out.toArray(new String[p_2out.size()]);
int s;
if (out1.length > 5 || out2.length > 5) {
s = 5;
} else if (out1.length > out2.length) {
s = out1.length;
} else {
s = out2.length;
}
for (int i = 0; i < s; i++) {
String out;
if (i > (out1.length - 1)) {
out = "| ";
} else {
out = out1[i];
}
out += " ";
if (i > (out2.length - 1)) {
out += " |";
} else {
out += out2[i];
}
m_botAction.sendArenaMessage(out);
}
m_botAction.sendArenaMessage("+---------------------------+ +---------------------------+");
if (mostHits != null) {
m_botAction.sendArenaMessage("- Most Hits: " + mostHits.getName() + " (" + mostHits.getTotalHits() + ")");
}
if (bestAcc != null) {
m_botAction.sendArenaMessage("- Best Accuracy: " + bestAcc.getName() + " (" + bestAcc.getAccuracy() + "%)");
}
if (mostKills != null) {
m_botAction.sendArenaMessage("- Most Kills: " + mostKills.getName() + " (" + mostKills.getKills() + ")");
}
if (mostDeaths != null) {
m_botAction.sendArenaMessage("- Most Deaths: " + mostDeaths.getName() + " (" + mostDeaths.getDeaths() + ")");
}
}
public String rightenString(String fragment, int length) {
int curLength = fragment.length();
int startPos = length - curLength;
String result = "";
for (int i = 0; i < startPos; i++) result = result + " ";
result = result + fragment;
for (int j = result.length(); j < length; j++) result = result + " ";
return result;
}
/**
This method is called when the bot has crossed either of the planet's border.
It does the gay bursting..
*/
public void gameOver() {
eventState = 3;
m_botAction.cancelTask(updateState);
killLosers = new TimerTask() {
int c = 0;
int c2 = 0;
int[] x = { 763, 496, 496, 1152, 1152, 1152, 1488, 1488 };
int[] y = { 8192, 6944, 9480, 7728, 8192, 8656, 8000, 8300 };
public void run() {
int pX;
if (winner == 1) {
pX = 8192 + x[c];
} else {
pX = 8192 - x[c];
}
oShip.move(pX, y[c]);
oShip.fire(7);
// oShip.fire(7);
if (c == 7) {
c = 0;
if (c2 == 0) {
c = 0;
c2 = 0;
announceWinner();
} else {
c2++;
}
} else {
c++;
}
}
};
m_botAction.scheduleTaskAtFixedRate(killLosers, 1000, 500);
}
/**
This method announces the winner and stalls the bot for 5 seconds
so the bursts wont disappear instantly.
*/
public void announceWinner() {
m_botAction.cancelTask(killLosers);
if (winner == 1) {
m_botAction.sendArenaMessage("Planet 1 has survived!!", 5);
} else {
m_botAction.sendArenaMessage("Planet 2 has survived!!", 5);
}
fiveSeconds = new TimerTask() {
public void run() {
finishGame();
}
};
m_botAction.scheduleTask(fiveSeconds, 5000);
}
/**
This method updates the bot location and detects collisions with
walls/projectiles.
*/
public void updateState() {
// m_botAction.sendArenaMessage("BOTLOC: " + botX + " . " + botY + " VX: " + botVX + " VY: " + botVY + " AGE: " + getAge());
checkCollision();
int botX = (int)getBotX();
int botY = (int)getBotY();
if (botVX == 0 && botVY == 0) {
oShip.move(botX, botY);
} else {
int dir = (int) (Math.random() * 40);
oShip.move(dir, botX, botY, botVX, botVY, 0, 1500, 1337);
}
ListIterator<Projectile> it = fired_projectiles.listIterator();
while (it.hasNext()) {
Projectile b = (Projectile) it.next();
// m_botAction.sendArenaMessage("TRACKING: " + b.getXLocation() + " . " + b.getYLocation() + " fired by: " + b.getOwner() + " age:" + b.getAge() + " d:" + b.getDistance(botX, botY));
if (b.isHitting(botX, botY)) {
if (b.getType() == 1) {
b.getOwner().incrementBulletsHit();
} else {
b.getOwner().incrementBombsHit();
}
m_botAction.sendUnfilteredPrivateMessage(b.getOwner().getName(), "*objon " + b.getOwner().getTeam());
// m_botAction.sendArenaMessage("HIT!!! " + b.getOwner().getName() + " ns!");
noteHit(b, botX, botY);
it.remove();
} else if (b.getAge() > 5000) {
it.remove();
}
}
}
/**
This method is called to detect collisions with walls/planet borders.
If there is a collision with a wall, the Y velocity is converted to the
opposite number and multiplied by 0.9 to slow down the bot a bit ..
*/
public void checkCollision() {
if (getBotX() < PLANET_1_BORDER) {
winner = 2;
gameOver();
} else if (getBotX() > PLANET_2_BORDER) {
winner = 1;
gameOver();
}
if ((getBotY() > Y_BORDER_2 && botVY > 0) || (getBotY() < Y_BORDER_1 && botVY < 0)) {
lBotX = (int)getBotX();
lBotY = (int)getBotY();
lastMove = (int)(System.currentTimeMillis());
botVY = (int)(botVY * (-1) * 0.9);
}
}
/**
This method calculates the new velocities after a collision with a projectile.
@param b is the Projectile
@param bX is the current bot x location
@param bY is the current bot y location
*/
public void noteHit(Projectile b, int bX, int bY) {
lastMove = (int)(System.currentTimeMillis());
lBotX = bX;
lBotY = bY;
// Distance compensation.
// Original formula: factor = (1 - d / dmax) ( 1 - inertia / 100)
// Remaining inertia factor = 1 - factor.
// Correction value, optimized for low amount of divisions: (100 * d + inertia * dmax - inertia * d) / (100 * dmax)
double factor = ( 100.0 * (double) b.getAge() + (double) inertia * (5000.0 - (double) b.getAge()) ) / (100.0 * 5000.0);
double nXV = (botVX * botMass + b.getXVelocity() * b.getMass() * factor) / (botMass + b.getMass());
double nYV = (botVY * botMass + b.getYVelocity() * b.getMass() * factor) / (botMass + b.getMass());
botVX = (int)nXV;
botVY = (int)nYV;
}
/**
This method calculates the bot x location.
@return bX is the new bot x location
*/
public double getBotX() {
double bX = lBotX + (botVX * getAge() / 10000.0);
return bX;
}
/**
This method calculates the bot y location.
@return bY is the new bot y location
*/
public double getBotY() {
double bY = lBotY + (botVY * getAge() / 10000.0);
return bY;
}
/**
This method calculates the time from last collision with a wall/projectile.
@return is the age
*/
public double getAge() {
return (int)(System.currentTimeMillis()) - lastMove;
}
}
| true
|
4827edc265caca8feb4d622903399a7b729c7e6f
|
Java
|
ubiquityhosting/rancher_cattle
|
/code/iaas/lb-logic/src/main/java/io/cattle/iaas/lb/api/service/impl/LoadBalancerApiServiceImpl.java
|
UTF-8
| 3,528
| 1.789063
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
package io.cattle.iaas.lb.api.service.impl;
import static io.cattle.platform.core.model.tables.LoadBalancerHostMapTable.LOAD_BALANCER_HOST_MAP;
import io.cattle.iaas.lb.api.service.LoadBalancerApiService;
import io.cattle.platform.core.addon.LoadBalancerTargetInput;
import io.cattle.platform.core.constants.LoadBalancerConstants;
import io.cattle.platform.core.dao.GenericMapDao;
import io.cattle.platform.core.dao.GenericResourceDao;
import io.cattle.platform.core.dao.LoadBalancerDao;
import io.cattle.platform.core.dao.LoadBalancerTargetDao;
import io.cattle.platform.core.model.Host;
import io.cattle.platform.core.model.LoadBalancer;
import io.cattle.platform.core.model.LoadBalancerConfig;
import io.cattle.platform.core.model.LoadBalancerConfigListenerMap;
import io.cattle.platform.core.model.LoadBalancerHostMap;
import io.cattle.platform.core.model.LoadBalancerListener;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import javax.inject.Inject;
public class LoadBalancerApiServiceImpl implements LoadBalancerApiService {
@Inject
GenericMapDao mapDao;
@Inject
ObjectManager objectManager;
@Inject
ObjectProcessManager objectProcessManager;
@Inject
GenericResourceDao resourceDao;
@Inject
LoadBalancerTargetDao lbTargetDao;
@Inject
LoadBalancerDao lbDao;
@Override
public void addHostToLoadBalancer(final LoadBalancer lb, final long hostId) {
LoadBalancerHostMap lbHostMap = mapDao.findNonRemoved(LoadBalancerHostMap.class, LoadBalancer.class,
lb.getId(), Host.class, hostId);
if (lbHostMap == null) {
resourceDao.createAndSchedule(LoadBalancerHostMap.class,
LOAD_BALANCER_HOST_MAP.LOAD_BALANCER_ID, lb.getId(),
LOAD_BALANCER_HOST_MAP.HOST_ID, hostId,
LOAD_BALANCER_HOST_MAP.ACCOUNT_ID, lb.getAccountId());
}
}
@Override
public void removeHostFromLoadBalancer(LoadBalancer lb, long hostId) {
LoadBalancerHostMap lbHostMap = mapDao.findToRemove(LoadBalancerHostMap.class, LoadBalancer.class, lb.getId(),
Host.class, hostId);
if (lbHostMap != null) {
objectProcessManager.scheduleProcessInstance(LoadBalancerConstants.PROCESS_LB_HOST_MAP_REMOVE,
lbHostMap, null);
}
}
@Override
public void removeListenerFromConfig(LoadBalancerConfig config, long listenerId) {
LoadBalancerConfigListenerMap lbConfigListenerMap = mapDao.findToRemove(LoadBalancerConfigListenerMap.class,
LoadBalancerConfig.class, config.getId(),
LoadBalancerListener.class, listenerId);
if (lbConfigListenerMap != null) {
objectProcessManager.scheduleProcessInstance(
LoadBalancerConstants.PROCESS_LB_CONFIG_LISTENER_MAP_REMOVE,
lbConfigListenerMap, null);
}
}
@Override
public void addTargetToLoadBalancer(LoadBalancer lb, LoadBalancerTargetInput targetInput) {
lbTargetDao.createLoadBalancerTarget(lb, targetInput);
}
@Override
public void removeTargetFromLoadBalancer(LoadBalancer lb, LoadBalancerTargetInput toRemove) {
lbTargetDao.removeLoadBalancerTarget(lb, toRemove);
}
@Override
public void addListenerToConfig(final LoadBalancerConfig config, final long listenerId) {
lbDao.addListenerToConfig(config, listenerId);
}
}
| true
|
2afa46a50216942bda5e8dd11a9a971a803256cc
|
Java
|
odielag/Java_book_started_2-10-2016
|
/src/chapter_6/Exercise_6_32__ChanceOfWinningAtCraps.java
|
UTF-8
| 1,922
| 4.21875
| 4
|
[] |
no_license
|
package chapter_6;
/**
* <h1>(Game: chance of winning at craps)</h1> Revise Exercise 6.30 to run it
* 10,000 times and display the number of winning games.
*
* @author William ODieLag Pennington
* @version 1.0
* @since 2016-5-26
*
*/
public class Exercise_6_32__ChanceOfWinningAtCraps
{
/** main method for testing and initializing */
public static void main(String[] args)
{
int win = 0;
int loss = 0;
for (int i = 0; i < 10000; i++)
{
if (craps())
win++;
else
loss++;
}
System.out.printf("Wins: %d\nLosses: %d", win, loss);
}
/** craps method for random generation, tally and print */
public static boolean craps()
{
/*
* creating two dice and randomizing an integer from/including 1
* to/including 6. evaluate if it won(natural), lost(craps) or set a
* point(other). If it set a point roll until it gets that point (win)
* or gets a sum of 7 (loss).
*/
int dice1 = (int) (6 * Math.random() + 1);
int dice2 = (int) (6 * Math.random() + 1);
int sum1 = dice1 + dice2;
int sum2 = -1; // sum2 in a more global range for else below.
System.out.printf("You rolled %d + %d = %d\n", dice1, dice2, sum1);
// craps if
if (sum1 == 2 || sum1 == 3 || sum1 == 12)
{
System.out.printf("You lose\n");
return false;
}
// natural if
else if (sum1 == 7 || sum1 == 11)
{
System.out.printf("You win\n");
return true;
} else
{
while (sum1 != sum2 && sum2 != 7)
{
System.out.printf("point is %d\n", sum1);
dice1 = (int) (6 * Math.random() + 1);
dice2 = (int) (6 * Math.random() + 1);
sum2 = dice1 + dice2;
System.out.printf("You rolled %d + %d = %d\n", dice1, dice2, sum2);
if (sum1 == sum2)
{
System.out.printf("You win\n");
return true;
} else if (sum2 == 7)
{
System.out.printf("You lose\n");
return false;
}
}
return false; // just to eliminate a method error.
}
}
}
| true
|
d7d60d6844fa150a6ab99b93d12991033de2caea
|
Java
|
WANGXin1205/school
|
/src/main/java/com/work/school/mysql/timetable/service/dto/RollbackDTO.java
|
UTF-8
| 3,577
| 2.1875
| 2
|
[] |
no_license
|
package com.work.school.mysql.timetable.service.dto;
import com.work.school.mysql.common.service.dto.GradeClassNumWorkDayTimeDTO;
import java.io.Serializable;
import java.util.HashMap;
public class RollbackDTO implements Serializable {
/**
* 序列
*/
private Integer order;
/**
* 获取科目使用的Map
*/
private HashMap<Integer, HashMap<Integer, Boolean>> orderSubjectIdCanUseMap;
/**
* 排序关系
*/
private HashMap<Integer, GradeClassNumWorkDayTimeDTO> orderGradeClassNumWorkDayTimeMap;
/**
* 年级班级下对应课程次数的map
*/
private HashMap<Integer, HashMap<Integer, HashMap<Integer, Integer>>> gradeClassNumSubjectFrequencyMap;
/**
* 初始化特殊教室使用情况 order subjectId workDay time count
*/
private HashMap<Integer, HashMap<Integer, HashMap<Integer, HashMap<Integer, Integer>>>> orderClassRoomUsedCountMap;
/**
* 课程表map
*/
private HashMap<Integer, HashMap<Integer, HashMap<Integer, HashMap<Integer, Integer>>>> timeTableMap;
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public HashMap<Integer, HashMap<Integer, Boolean>> getOrderSubjectIdCanUseMap() {
return orderSubjectIdCanUseMap;
}
public void setOrderSubjectIdCanUseMap(HashMap<Integer, HashMap<Integer, Boolean>> orderSubjectIdCanUseMap) {
this.orderSubjectIdCanUseMap = orderSubjectIdCanUseMap;
}
public HashMap<Integer, GradeClassNumWorkDayTimeDTO> getOrderGradeClassNumWorkDayTimeMap() {
return orderGradeClassNumWorkDayTimeMap;
}
public void setOrderGradeClassNumWorkDayTimeMap(HashMap<Integer, GradeClassNumWorkDayTimeDTO> orderGradeClassNumWorkDayTimeMap) {
this.orderGradeClassNumWorkDayTimeMap = orderGradeClassNumWorkDayTimeMap;
}
public HashMap<Integer, HashMap<Integer, HashMap<Integer, Integer>>> getGradeClassNumSubjectFrequencyMap() {
return gradeClassNumSubjectFrequencyMap;
}
public void setGradeClassNumSubjectFrequencyMap(HashMap<Integer, HashMap<Integer, HashMap<Integer, Integer>>> gradeClassNumSubjectFrequencyMap) {
this.gradeClassNumSubjectFrequencyMap = gradeClassNumSubjectFrequencyMap;
}
public HashMap<Integer, HashMap<Integer, HashMap<Integer, HashMap<Integer, Integer>>>> getOrderClassRoomUsedCountMap() {
return orderClassRoomUsedCountMap;
}
public void setOrderClassRoomUsedCountMap(HashMap<Integer, HashMap<Integer, HashMap<Integer, HashMap<Integer, Integer>>>> orderClassRoomUsedCountMap) {
this.orderClassRoomUsedCountMap = orderClassRoomUsedCountMap;
}
public HashMap<Integer, HashMap<Integer, HashMap<Integer, HashMap<Integer, Integer>>>> getTimeTableMap() {
return timeTableMap;
}
public void setTimeTableMap(HashMap<Integer, HashMap<Integer, HashMap<Integer, HashMap<Integer, Integer>>>> timeTableMap) {
this.timeTableMap = timeTableMap;
}
@Override
public String toString() {
return "RollbackDTO{" +
"order=" + order +
", orderSubjectIdCanUseMap=" + orderSubjectIdCanUseMap +
", orderGradeClassNumWorkDayTimeMap=" + orderGradeClassNumWorkDayTimeMap +
", gradeClassNumSubjectFrequencyMap=" + gradeClassNumSubjectFrequencyMap +
", orderClassRoomUsedCountMap=" + orderClassRoomUsedCountMap +
", timeTableMap=" + timeTableMap +
'}';
}
}
| true
|
057a7709d3f00ae79070324fab35c564b31e474d
|
Java
|
kevenhu/kmall
|
/src/main/java/com/keven/kmall/service/impl/UserServiceImpl.java
|
UTF-8
| 847
| 2.296875
| 2
|
[] |
no_license
|
package com.keven.kmall.service.impl;
import com.keven.kmall.dao.UserDao;
import com.keven.kmall.entity.User;
import com.keven.kmall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by Keven on 2017/7/6.
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public User findUserById(int id) {
return userDao.findUserById(id);
}
public int save(User user) throws Exception{
int result = userDao.save(user);
if (result==1) {
return 1;
}else
throw new Exception("注册失败");
}
public User loginWithAccount(String account, String password) {
return userDao.loginWithAccount(account,password);
}
}
| true
|
d64368c8a1c70335d1fee4d77a89afbd1de925d2
|
Java
|
yurinalin/AlphaLab
|
/src/main/java/br/edu/ifmt/cba/alphalab/dao/mock/emprestimo/MockEmprestimoDAO.java
|
UTF-8
| 2,347
| 2.234375
| 2
|
[
"MIT"
] |
permissive
|
package br.edu.ifmt.cba.alphalab.dao.mock.emprestimo;
import br.edu.ifmt.cba.alphalab.dao.IEmprestimoDAO;
import br.edu.ifmt.cba.alphalab.dao.mock.equipamentos.MockEquipamentoDAO;
import br.edu.ifmt.cba.alphalab.dao.mock.servidor.MockServidorDAO;
import br.edu.ifmt.cba.alphalab.entity.equipamentos.EmprestimoEntity;
import br.edu.ifmt.cba.alphalab.entity.equipamentos.EquipamentoEntity;
import br.edu.ifmt.cba.alphalab.entity.pessoa.ServidorEntity;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MockEmprestimoDAO implements IEmprestimoDAO {
private static ArrayList<EmprestimoEntity> listaEmprestimo = new ArrayList();
private static MockEmprestimoDAO singleton = null;
private static final EmprestimoEntity Emprestimo = new EmprestimoEntity();
private static final String formatoData = "dd/MM/yyyy";
static{
Emprestimo.setId(1L);
try {
Emprestimo.setDataSolicitacao( new SimpleDateFormat(formatoData).parse("10/05/2017"));
} catch (ParseException ex) {
//Emprestimo.setRecursos();
Emprestimo.setAprovador((ServidorEntity) MockServidorDAO.getInstance().getById(1L));
}
}
public MockEmprestimoDAO(){ }
public MockEmprestimoDAO getInstance(){
if (singleton == null)
singleton = new MockEmprestimoDAO();
return singleton;
}
@Override
public void save(EmprestimoEntity entity) {
if (listaEmprestimo.indexOf(entity) < 0)
listaEmprestimo.add(entity);
}
@Override
public void delete(EmprestimoEntity entity) {
listaEmprestimo.remove(entity);
}
@Override
public EmprestimoEntity getById(Long id) {
for (EmprestimoEntity vo : listaEmprestimo)
if (vo.getId().equals(id))
return vo;
return null;
}
@Override
public EmprestimoEntity getByNome(String nome) {
if (listaEmprestimo.indexOf(nome) < 0)
return null;
else
return listaEmprestimo.get(listaEmprestimo.indexOf(nome));
}
public List<EmprestimoEntity> buscarTodos() {
return listaEmprestimo;
}
}
| true
|
55a96a2948d46d96c75a6adef6162d668aa2421e
|
Java
|
helloworld107/CitySelect
|
/citypicker/src/main/java/com/zaaach/citypicker/CityPickerActivity.java
|
UTF-8
| 7,508
| 1.992188
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.zaaach.citypicker;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.zaaach.citypicker.adapter.CityListAdapter;
import com.zaaach.citypicker.adapter.ResultListAdapter;
import com.zaaach.citypicker.db.DBManager;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.utils.StringUtils;
import com.zaaach.citypicker.utils.ToastUtils;
import com.zaaach.citypicker.view.SideLetterBar;
import java.util.List;
/**
* author zaaach on 2016/1/26.
*/
public class CityPickerActivity extends AppCompatActivity implements View.OnClickListener {
public static final int REQUEST_CODE_PICK_CITY = 2333;
public static final String KEY_PICKED_CITY = "picked_city";
private ListView mListView;
private ListView mResultListView;
private SideLetterBar mLetterBar;
private EditText searchBox;
private ImageView clearBtn;
private ImageView backBtn;
private ViewGroup emptyView;
private CityListAdapter mCityAdapter;
private ResultListAdapter mResultAdapter;
private List<City> mAllCities;
private DBManager dbManager;
private AMapLocationClient mLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_list);
initData();
initView();
initLocation();
}
private void initLocation() {
mLocationClient = new AMapLocationClient(this);
AMapLocationClientOption option = new AMapLocationClientOption();
option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
option.setOnceLocation(true);
mLocationClient.setLocationOption(option);
mLocationClient.setLocationListener(new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (aMapLocation != null) {
if (aMapLocation.getErrorCode() == 0) {
String city = aMapLocation.getCity();
String district = aMapLocation.getDistrict();
Log.e("onLocationChanged", "city: " + city);
Log.e("onLocationChanged", "district: " + district);
String location = StringUtils.extractLocation(city, district);
mCityAdapter.updateLocateState(LocateState.SUCCESS, location);
} else {
//定位失败
mCityAdapter.updateLocateState(LocateState.FAILED, null);
}
}
}
});
mLocationClient.startLocation();
}
private void initData() {
dbManager = new DBManager(this);
dbManager.copyDBFile();
mAllCities = dbManager.getAllCities();
mCityAdapter = new CityListAdapter(this, mAllCities);
mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
@Override
public void onCityClick(String name) {
back(name);
}
@Override
public void onLocateClick() {
Log.e("onLocateClick", "重新定位...");
mCityAdapter.updateLocateState(LocateState.LOCATING, null);
mLocationClient.startLocation();
}
});
mResultAdapter = new ResultListAdapter(this, null);
}
private void initView() {
mListView = (ListView) findViewById(R.id.listview_all_city);
mListView.setAdapter(mCityAdapter);
TextView overlay = (TextView) findViewById(R.id.tv_letter_overlay);
mLetterBar = (SideLetterBar) findViewById(R.id.side_letter_bar);
mLetterBar.setOverlay(overlay);
mLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
@Override
public void onLetterChanged(String letter) {
int position = mCityAdapter.getLetterPosition(letter);
mListView.setSelection(position);
}
});
searchBox = (EditText) findViewById(R.id.et_search);
searchBox.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 s) {
String keyword = s.toString();
if (TextUtils.isEmpty(keyword)) {
clearBtn.setVisibility(View.GONE);
emptyView.setVisibility(View.GONE);
mResultListView.setVisibility(View.GONE);
} else {
clearBtn.setVisibility(View.VISIBLE);
mResultListView.setVisibility(View.VISIBLE);
List<City> result = dbManager.searchCity(keyword);
if (result == null || result.size() == 0) {
emptyView.setVisibility(View.VISIBLE);
} else {
emptyView.setVisibility(View.GONE);
mResultAdapter.changeData(result);
}
}
}
});
emptyView = (ViewGroup) findViewById(R.id.empty_view);
mResultListView = (ListView) findViewById(R.id.listview_search_result);
mResultListView.setAdapter(mResultAdapter);
mResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
back(mResultAdapter.getItem(position).getName());
}
});
clearBtn = (ImageView) findViewById(R.id.iv_search_clear);
backBtn = (ImageView) findViewById(R.id.back);
clearBtn.setOnClickListener(this);
backBtn.setOnClickListener(this);
}
private void back(String city){
ToastUtils.showToast(this, "点击的城市:" + city);
// Intent data = new Intent();
// data.putExtra(KEY_PICKED_CITY, city);
// setResult(RESULT_OK, data);
// finish();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.iv_search_clear:
searchBox.setText("");
clearBtn.setVisibility(View.GONE);
emptyView.setVisibility(View.GONE);
mResultListView.setVisibility(View.GONE);
break;
case R.id.back:
finish();
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mLocationClient.stopLocation();
}
}
| true
|
cd1c31aa6f2aa205c4442509ef3504f23914a15a
|
Java
|
FabioGermano/MAD_Lab4
|
/app/src/main/java/it/polito/mad_lab4/restaurant/reviews/ReviewsListAdapter.java
|
UTF-8
| 3,081
| 2.421875
| 2
|
[] |
no_license
|
package it.polito.mad_lab4.restaurant.reviews;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import it.polito.mad_lab4.R;
import it.polito.mad_lab4.common.Helper;
import it.polito.mad_lab4.newData.restaurant.Dish;
import it.polito.mad_lab4.newData.restaurant.Review;
/**
* Created by f.germano on 03/05/2016.
*/
public class ReviewsListAdapter extends ArrayAdapter<Review> {
private final ArrayList<Review> reviews;
// View lookup cache
private static class ViewHolder {
public ImageView offDetUserPhoto;
public TextView offDetDate;
public RatingBar offDetRatingBar;
public TextView offDetReview;
public TextView offDetUserName;
}
private ArrayList<Dish> dishes;
public ReviewsListAdapter(Context context, ArrayList<Review> reviews){
super(context, 0, reviews);
this.reviews = reviews;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Check if an existing view is being reused, otherwise inflate the view
final ViewHolder viewHolder; // view lookup cache stored in tag
Review review = this.reviews.get(position);
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.review_view_detail, parent, false);
viewHolder.offDetUserPhoto = (ImageView)convertView.findViewById(R.id.offDetUserPhoto);
viewHolder.offDetDate = (TextView)convertView.findViewById(R.id.offDetDate);
viewHolder.offDetRatingBar = (RatingBar)convertView.findViewById(R.id.offDetRatingBar);
viewHolder.offDetReview = (TextView)convertView.findViewById(R.id.offDetReview);
viewHolder.offDetUserName = (TextView)convertView.findViewById(R.id.offDetUserName);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.offDetDate.setText(review.getDate());
Glide.with(getContext()).load(review.getLogoLink()).into(viewHolder.offDetUserPhoto);
viewHolder.offDetRatingBar.setRating(review.getRank());
viewHolder.offDetReview.setText(review.getComment());
viewHolder.offDetUserName.setText(review.getUserName());
viewHolder.offDetDate.setText(review.getDate());
Helper.setRatingBarColor(getContext(),
viewHolder.offDetRatingBar,
review.getRank());
// Return the completed view to render on screen
return convertView;
}
}
| true
|
779fd09c4426dcd8139ba34f3993fbf694c3f60b
|
Java
|
BDS-CoPilot/blackduck-alert
|
/src/test/java/com/blackducksoftware/integration/hub/alert/accumulator/RealTimeListenerTest.java
|
UTF-8
| 3,464
| 1.921875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.blackducksoftware.integration.hub.alert.accumulator;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Test;
import org.mockito.Mockito;
import com.blackducksoftware.integration.hub.alert.OutputLogger;
import com.blackducksoftware.integration.hub.alert.channel.ChannelTemplateManager;
import com.blackducksoftware.integration.hub.alert.digest.filter.NotificationEventManager;
import com.blackducksoftware.integration.hub.alert.digest.model.ProjectDataFactory;
import com.blackducksoftware.integration.hub.alert.event.RealTimeEvent;
import com.blackducksoftware.integration.hub.alert.hub.model.NotificationModel;
import com.blackducksoftware.integration.hub.alert.mock.entity.MockNotificationEntity;
import com.google.gson.Gson;
public class RealTimeListenerTest {
@Test
public void testReceiveMessage() {
final Gson gson = new Gson();
final MockNotificationEntity notificationEntity = new MockNotificationEntity();
final NotificationModel model = new NotificationModel(notificationEntity.createEntity(), Collections.emptyList());
final ChannelTemplateManager channelTemplateManager = Mockito.mock(ChannelTemplateManager.class);
final ProjectDataFactory projectDataFactory = Mockito.mock(ProjectDataFactory.class);
final NotificationEventManager eventManager = Mockito.mock(NotificationEventManager.class);
final RealTimeListener realTimeListener = new RealTimeListener(gson, channelTemplateManager, projectDataFactory, eventManager);
final RealTimeEvent realTimeEvent = new RealTimeEvent(Arrays.asList(model));
final String realTimeEventString = gson.toJson(realTimeEvent);
realTimeListener.receiveMessage(realTimeEventString);
Mockito.doNothing().when(channelTemplateManager).sendEvents(Mockito.any());
Mockito.verify(channelTemplateManager).sendEvents(Mockito.any());
}
@SuppressWarnings("unchecked")
@Test
public void testReceiveMessageException() throws IOException, Exception {
try (OutputLogger outputLogger = new OutputLogger()) {
final Gson gson = new Gson();
final MockNotificationEntity notificationEntity = new MockNotificationEntity();
final NotificationModel model = new NotificationModel(notificationEntity.createEntity(), Collections.emptyList());
final ChannelTemplateManager channelTemplateManager = Mockito.mock(ChannelTemplateManager.class);
final ProjectDataFactory projectDataFactory = Mockito.mock(ProjectDataFactory.class);
final NotificationEventManager eventManager = Mockito.mock(NotificationEventManager.class);
Mockito.doNothing().when(channelTemplateManager).sendEvents(Mockito.any());
Mockito.doThrow(new NullPointerException("null error")).when(projectDataFactory).createProjectDataCollection(Mockito.anyCollection(), Mockito.any());
final RealTimeListener realTimeListener = new RealTimeListener(gson, channelTemplateManager, projectDataFactory, eventManager);
final RealTimeEvent realTimeEvent = new RealTimeEvent(Arrays.asList(model));
final String realTimeEventString = gson.toJson(realTimeEvent);
realTimeListener.receiveMessage(realTimeEventString);
assertTrue(outputLogger.isLineContainingText("null"));
}
}
}
| true
|
350983312dc64874ab12329c653cf5e7033347ba
|
Java
|
alu0100767803/PAI
|
/src/es/etsii/ull/PAI/Duplicados/Duplicados.java
|
WINDOWS-1250
| 2,565
| 3.484375
| 3
|
[] |
no_license
|
package es.etsii.ull.PAI.Duplicados;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.io.*;
import java.util.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
/**
* @author Jorge
* E-mail: alu0100767803@ull.edu.es
* Fecha: 08/03/2016
* Asignatura: Programacin de Aplicaciones Interactivas
* Version: 1
* Comentario: Clase que muestra por pantalla las palabras no duplicadas
*/
public class Duplicados extends JFrame {
private Map<String, Integer> mapa; // Mapa que va a contener las palabras del texto
// y las veces que se repite
public Duplicados(String fichero) throws IOException, FileNotFoundException{
mapa = new TreeMap<String, Integer>();
setLayout (new FlowLayout(FlowLayout.LEFT, 10, 20));
add(new JLabel("Fichero a analizar"));
add(new JTextField(8));
add(new JButton("Analizar"));
BufferedReader reader = new BufferedReader(new FileReader(fichero));
String linea;
while((linea = reader.readLine()) != null){
StringTokenizer st = new StringTokenizer(linea," ");
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (encontrarCadena(token.toLowerCase()))
borrarClave(token);
else
setClaveMapa(token.toLowerCase(), 1);
}
}
}
/**
* Devuelve el valor del keyset del TreeMap
* @return
*/
public Set<String> getKeySet() {
return mapa.keySet();
}
/**
* Introduce una clave y su valor en el TreeMap
* @param clave
* @param valor
*/
public void setClaveMapa(String clave, Integer valor) {
mapa.put(clave, valor);
}
/**
* Borra una clave del TreeMap
* @param clave
*/
public void borrarClave(String clave){
mapa.remove(clave);
}
/**
* Devuelve si la cadena que le pasamos esta ya en el TreeMap
* @param token
* @return
*/
public boolean encontrarCadena(String token) {
if (mapa.containsKey(token.toLowerCase()))
return true;
else
return false;
}
/**
* Muestra el TreeMap de forma invertida
*/
public void mostrar() {
Stack<String> palabra = new Stack<String>(); // pila para sacar los elementos del TreeMap de forma inversa
Iterator<String> iterador = getKeySet().iterator();
System.out.println("Caedenas No Duplicadas");
while(iterador.hasNext()){
Object cadena = iterador.next();
palabra.push((String) cadena);
}
iterador = palabra.iterator();
while(iterador.hasNext()){
System.out.println(palabra.pop());
}
}
}
| true
|
a197f0b403d65240763835aaaa8c4e62203ac585
|
Java
|
gautamhans1/YTFetcher
|
/app/src/main/java/com/grarak/ytfetcher/views/recyclerview/settings/ButtonItem.java
|
UTF-8
| 1,632
| 2.34375
| 2
|
[
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause",
"MIT"
] |
permissive
|
package com.grarak.ytfetcher.views.recyclerview.settings;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.grarak.ytfetcher.R;
import com.grarak.ytfetcher.views.recyclerview.RecyclerViewItem;
public class ButtonItem extends RecyclerViewItem {
private CharSequence text;
private int textColor;
private int backgroundColor;
private View.OnClickListener onClickListener;
private RecyclerView.ViewHolder viewHolder;
public ButtonItem(View.OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
@Override
protected int getLayoutXml() {
return R.layout.item_button;
}
@Override
protected void bindViewHolder(RecyclerView.ViewHolder viewHolder) {
this.viewHolder = viewHolder;
setup();
}
public void setText(CharSequence text) {
this.text = text;
setup();
}
public void setTextColor(int color) {
textColor = color;
setup();
}
public void setBackgroundColor(int color) {
backgroundColor = color;
setup();
}
private void setup() {
if (viewHolder != null) {
TextView textView = viewHolder.itemView.findViewById(R.id.text);
textView.setText(text);
if (textColor != 0) {
textView.setTextColor(textColor);
}
if (backgroundColor != 0) {
textView.setBackgroundColor(backgroundColor);
}
viewHolder.itemView.setOnClickListener(onClickListener);
}
}
}
| true
|
406e2357c7514c87a86dcbc29421fae9847aff93
|
Java
|
Quantum56/AP-Computer-Science
|
/Workspace/Exercise7_4/src/SportTrack.java
|
UTF-8
| 12,258
| 3
| 3
|
[] |
no_license
|
import java.util.ArrayList;
/**
* @author ZackB
*
*/
public class SportTrack {
public SportTrack() {
// TODO Auto-generated constructor stub
}
public static class Football extends SportTrack {
private ArrayList<String> names = new ArrayList<String>();
private ArrayList<String> divisions = new ArrayList<String>();
private ArrayList<Integer> winsArr = new ArrayList<Integer>();
private ArrayList<Integer> lossesArr = new ArrayList<Integer>();
private ArrayList<Integer> pointsScoredArr = new ArrayList<Integer>();
private ArrayList<Integer> pointsScoredOnArr = new ArrayList<Integer>();
private ArrayList<Double> winLossPctArr = new ArrayList<Double>();
private ArrayList<Integer> pointDiffArr = new ArrayList<Integer>();
private ArrayList<Integer> gamesPlayedArr = new ArrayList<Integer>();
private ArrayList<Double> winMarginArr = new ArrayList<Double>(); // defined as ( pointDiff / gamesPlayed )
public Football(String teamName, String division, int wins, int losses, int pointsScored, int pointsScoredOn) {
names.add(teamName);
divisions.add(division);
winsArr.add(wins);
lossesArr.add(losses);
pointsScoredArr.add(pointsScored);
pointsScoredOnArr.add(pointsScoredOn);
winLossPctArr.add((double) wins / losses);
pointDiffArr.add(pointsScored - pointsScoredOn);
gamesPlayedArr.add(wins + losses);
winMarginArr.add((double) pointDiffArr.get(names.indexOf(teamName) / gamesPlayedArr.get(names.indexOf(teamName))));
}
public String getDivision(String teamName) {
return divisions.get(names.indexOf(teamName));
}
public int getWins(String teamName) {
return winsArr.get(names.indexOf(teamName));
}
public int getLosses(String teamName) {
return winsArr.get(names.indexOf(teamName));
}
public int getPointsScored(String teamName) {
return pointsScoredArr.get(names.indexOf(teamName));
}
public int getPointsScoredOn(String teamName) {
return pointsScoredOnArr.get(names.indexOf(teamName));
}
public double getWinLossPct(String teamName) {
return winLossPctArr.get(names.indexOf(teamName));
}
public int getPointDiff(String teamName) {
return pointDiffArr.get(names.indexOf(teamName));
}
public int getGamesPlayed(String teamName) {
return gamesPlayedArr.get(names.indexOf(teamName));
}
public double getWinMargin(String teamName) {
return winMarginArr.get(names.indexOf(teamName));
}
public String toString(String teamName) {
String team;
team = "Team: " + teamName + "\n Division: " + getDivision(teamName) + " Wins: " + getWins(teamName)
+ " Losses: " + getLosses(teamName) + " Points Scored: " + getPointsScored(teamName)
+ " Points Scored On: " + getPointsScoredOn(teamName) + " Wins/Losses Percent: "
+ getWinLossPct(teamName) + " Points Differential: " + getPointDiff(teamName) + " Games Played: "
+ getGamesPlayed(teamName) + " Win Margin: " + getWinMargin(teamName);
return team;
}
}
public static class Baseball extends SportTrack {
private ArrayList<String> names = new ArrayList<String>();
private ArrayList<Integer> winsArr = new ArrayList<Integer>();
private ArrayList<Integer> lossesArr = new ArrayList<Integer>();
private ArrayList<Integer> runsArr = new ArrayList<Integer>();
private ArrayList<Integer> homeRunsArr = new ArrayList<Integer>();
private ArrayList<Double> winLossPctArr = new ArrayList<Double>();
private ArrayList<Integer> hitsArr = new ArrayList<Integer>();
private ArrayList<Integer> gamesPlayedArr = new ArrayList<Integer>();
private ArrayList<Integer> rbiArr = new ArrayList<Integer>();
private ArrayList<Integer> totalRunsArr = new ArrayList<Integer>();
private ArrayList<Integer> basesStolenArr = new ArrayList<Integer>();
public Baseball(String teamName, int wins, int losses, int scoringRuns, int homeRuns, int hits, int rbi, int stolenBases, int totalRuns) {
names.add(teamName);
winsArr.add(wins);
lossesArr.add(losses);
runsArr.add(scoringRuns);
homeRunsArr.add(homeRuns);
hitsArr.add(hits);
winLossPctArr.add((double) wins / losses);
gamesPlayedArr.add(wins + losses);
rbiArr.add(rbi);
totalRunsArr.add(totalRuns);
basesStolenArr.add(stolenBases);
}
public int getWins(String teamName) {
return winsArr.get(names.indexOf(teamName));
}
public int getLosses(String teamName) {
return lossesArr.get(names.indexOf(teamName));
}
public int getScoringRuns(String teamName) {
return runsArr.get(names.indexOf(teamName));
}
public int getHomeRuns(String teamName) {
return homeRunsArr.get(names.indexOf(teamName));
}
public double getWinLossPct(String teamName) {
return winLossPctArr.get(names.indexOf(teamName));
}
public int getTotalHits(String teamName) {
return hitsArr.get(names.indexOf(teamName));
}
public int getGamesPlayed(String teamName) {
return gamesPlayedArr.get(names.indexOf(teamName));
}
public int getRbi(String teamName) {
return rbiArr.get(names.indexOf(teamName));
}
public int getTotalRuns(String teamName) {
return totalRunsArr.get(names.indexOf(teamName));
}
public int getBasesStolen(String teamName) {
return basesStolenArr.get(names.indexOf(teamName));
}
public String toString(String teamName) {
String team;
team = "Team: " + teamName + "\n Wins: " + getWins(teamName) + " Losses: " + getLosses(teamName)
+ " Points Scored: " + getScoringRuns(teamName) + " Home Runs: " + getHomeRuns(teamName)
+ " Wins/Losses Percent: " + getWinLossPct(teamName) + " Total Hits: " + getTotalHits(teamName)
+ " Games Played: " + getGamesPlayed(teamName) + " Runs Batted In: " + getRbi(teamName)
+ " Total Runs: " + getTotalRuns(teamName) + " Bases Stolen: " + getBasesStolen(teamName);
return team;
}
}
public static class Hockey extends SportTrack {
private ArrayList<String> names = new ArrayList<String>();
private ArrayList<String> divisions = new ArrayList<String>();
private ArrayList<String> subDivisions = new ArrayList<String>();
private ArrayList<Integer> winsArr = new ArrayList<Integer>();
private ArrayList<Integer> lossesArr = new ArrayList<Integer>();
private ArrayList<Integer> pointsScoredArr = new ArrayList<Integer>();
private ArrayList<Integer> pointsScoredOnArr = new ArrayList<Integer>();
private ArrayList<Double> winLossPctArr = new ArrayList<Double>();
private ArrayList<Integer> pointDiffArr = new ArrayList<Integer>();
private ArrayList<Integer> gamesPlayedArr = new ArrayList<Integer>();
private ArrayList<Double> winMarginArr = new ArrayList<Double>(); // defined as ( pointDiff / gamesPlayed )
public Hockey(String teamName, String division, String subDivision, int wins, int losses, int pointsScored, int pointsScoredOn) {
names.add(teamName);
divisions.add(division);
subDivisions.add(subDivision);
winsArr.add(wins);
lossesArr.add(losses);
pointsScoredArr.add(pointsScored);
pointsScoredOnArr.add(pointsScoredOn);
winLossPctArr.add((double) wins / losses);
pointDiffArr.add(pointsScored - pointsScoredOn);
gamesPlayedArr.add(wins + losses);
winMarginArr.add((double) pointDiffArr.get(names.indexOf(teamName) / gamesPlayedArr.get(names.indexOf(teamName))));
}
public String getDivision(String teamName) {
return divisions.get(names.indexOf(teamName));
}
public String getSubDivision(String teamName) {
return subDivisions.get(names.indexOf(teamName));
}
public int getWins(String teamName) {
return winsArr.get(names.indexOf(teamName));
}
public int getLosses(String teamName) {
return winsArr.get(names.indexOf(teamName));
}
public int getPointsScored(String teamName) {
return pointsScoredArr.get(names.indexOf(teamName));
}
public int getPointsScoredOn(String teamName) {
return pointsScoredOnArr.get(names.indexOf(teamName));
}
public double getWinLossPct(String teamName) {
return winLossPctArr.get(names.indexOf(teamName));
}
public int getPointDiff(String teamName) {
return pointDiffArr.get(names.indexOf(teamName));
}
public int getGamesPlayed(String teamName) {
return gamesPlayedArr.get(names.indexOf(teamName));
}
public double getWinMargin(String teamName) {
return winMarginArr.get(names.indexOf(teamName));
}
public String toString(String teamName) {
String team;
team = "Team: " + teamName + "\n Division: " + getDivision(teamName) + " Sub-Division: " + getSubDivision(teamName)
+ " Wins: " + getWins(teamName) + " Losses: " + getLosses(teamName) + " Points Scored: "
+ getPointsScored(teamName) + " Points Scored On: " + getPointsScoredOn(teamName) + " Wins/Losses Percent: "
+ getWinLossPct(teamName) + " Points Differential: " + getPointDiff(teamName) + " Games Played: "
+ getGamesPlayed(teamName) + " Win Margin: " + getWinMargin(teamName);
return team;
}
}
public static class Soccer extends SportTrack {
private ArrayList<String> names = new ArrayList<String>();
private ArrayList<String> divisions = new ArrayList<String>();
private ArrayList<String> subDivisions = new ArrayList<String>();
private ArrayList<Integer> winsArr = new ArrayList<Integer>();
private ArrayList<Integer> lossesArr = new ArrayList<Integer>();
private ArrayList<Integer> pointsScoredArr = new ArrayList<Integer>();
private ArrayList<Integer> pointsScoredOnArr = new ArrayList<Integer>();
private ArrayList<Double> winLossPctArr = new ArrayList<Double>();
private ArrayList<Integer> pointDiffArr = new ArrayList<Integer>();
private ArrayList<Integer> gamesPlayedArr = new ArrayList<Integer>();
private ArrayList<Double> winMarginArr = new ArrayList<Double>(); // defined as ( pointDiff / gamesPlayed )
public Soccer(String teamName, String division, String subDivision, int wins, int losses, int pointsScored, int pointsScoredOn) {
names.add(teamName);
divisions.add(division);
subDivisions.add(subDivision);
winsArr.add(wins);
lossesArr.add(losses);
pointsScoredArr.add(pointsScored);
pointsScoredOnArr.add(pointsScoredOn);
winLossPctArr.add((double) wins / losses);
pointDiffArr.add(pointsScored - pointsScoredOn);
gamesPlayedArr.add(wins + losses);
winMarginArr.add((double) pointDiffArr.get(names.indexOf(teamName) / gamesPlayedArr.get(names.indexOf(teamName))));
}
public String getDivision(String teamName) {
return divisions.get(names.indexOf(teamName));
}
public String getSubDivision(String teamName) {
return subDivisions.get(names.indexOf(teamName));
}
public int getWins(String teamName) {
return winsArr.get(names.indexOf(teamName));
}
public int getLosses(String teamName) {
return winsArr.get(names.indexOf(teamName));
}
public int getPointsScored(String teamName) {
return pointsScoredArr.get(names.indexOf(teamName));
}
public int getPointsScoredOn(String teamName) {
return pointsScoredOnArr.get(names.indexOf(teamName));
}
public double getWinLossPct(String teamName) {
return winLossPctArr.get(names.indexOf(teamName));
}
public int getPointDiff(String teamName) {
return pointDiffArr.get(names.indexOf(teamName));
}
public int getGamesPlayed(String teamName) {
return gamesPlayedArr.get(names.indexOf(teamName));
}
public double getWinMargin(String teamName) {
return winMarginArr.get(names.indexOf(teamName));
}
public String toString(String teamName) {
String team;
team = "Team: " + teamName + "\n Division: " + getDivision(teamName) + " Wins: "
+ getWins(teamName) + " Losses: " + getLosses(teamName) + " Points Scored: "
+ getPointsScored(teamName) + " Points Scored On: " + getPointsScoredOn(teamName) + " Wins/Losses Percent: "
+ getWinLossPct(teamName) + " Points Differential: " + getPointDiff(teamName) + " Games Played: "
+ getGamesPlayed(teamName) + " Win Margin: " + getWinMargin(teamName);
return team;
}
}
}
| true
|
78880d3657cb58ea074f0b627daa3a4ac95178a1
|
Java
|
mrinalinigarre/Web-Server
|
/responses/DeleteResponse.java
|
UTF-8
| 1,089
| 2.671875
| 3
|
[] |
no_license
|
package responses;
import server.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DeleteResponse extends Response {
public DeleteResponse( Resource resource, int statusCode ) throws IOException {
super( resource );
reasonPhrase = "Delete";
this.statusCode = statusCode;
}
@Override
public void read() throws IOException {
String newBody = statusCode + " " + reasonPhrase;
body = newBody.getBytes();
if( headers.containsKey( "Content-Length" ) ) {
headers.replace( "Content-Length", String.valueOf( body.length ) );
}else {
headers.put( "Content-Length", String.valueOf( body.length ) );
}
}
public static boolean deleteFile( String fileName ) throws IOException {
try {
Path file = Paths.get( stripSlash( fileName ) );
Files.delete( file );
}catch( Exception e ) {
e.printStackTrace();
}
return true;
}
private static String stripSlash( String fileName ) {
return fileName.replace( "//", "/" );
}
}
| true
|
5c84f80060d64c9fd9f18f1c7319edfe18aa1d4a
|
Java
|
lilianmin1991/parent
|
/babasport-common/src/main/java/cn/itcast/common/utils/RequestUtils.java
|
UTF-8
| 1,134
| 2.71875
| 3
|
[] |
no_license
|
package cn.itcast.common.utils;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 请求Request工具类
* @author lx
*
*/
public class RequestUtils {
//获取Cookie中的CSESSIONID
public static String getCSESSIONID(HttpServletResponse response,HttpServletRequest request){
//1:从Request中取Cookie
Cookie[] cookies = request.getCookies();
if(null != cookies && cookies.length > 0){
for (Cookie cookie : cookies) {
//2:从Cookie中取CSESSIONID
if("CSESSIONID".equals(cookie.getName())){
//4:如果有 直接使用此CSESSIONID
return cookie.getValue();
}
}
}
//3:如果第一次 没有 创建CSESSIONID
String csessionid = UUID.randomUUID().toString().replaceAll("-", "");
//5:放到Cookie 写回浏览器
Cookie cookie = new Cookie("CSESSIONID",csessionid);
//设置路径 /
cookie.setPath("/");
//存活时间 -1 0 >0 60*60*24*7
cookie.setMaxAge(-1);
//写回浏览器
response.addCookie(cookie);
//返回CSESSIONID
return csessionid;
}
}
| true
|
eb02c9b7edcde1d772b900cdf7161bfdc1a1fd4f
|
Java
|
gywnd6209/LAONIDE
|
/src/main/java/kr/or/ddit/issueEndboard/service/IIssueEndboardService.java
|
UTF-8
| 596
| 1.710938
| 2
|
[] |
no_license
|
package kr.or.ddit.issueEndboard.service;
import java.util.List;
import java.util.Map;
import kr.or.ddit.vo.IssueEndVO;
public interface IIssueEndboardService {
public IssueEndVO issueEndboardInfo(Map<String, String> params) throws Exception;
public List<IssueEndVO> issueEndboardList(Map<String, String> params) throws Exception;
public String insertIssueEndBoardInfo(IssueEndVO issueEndboardInfo) throws Exception;
public void updateIssueEndBoardInfo(IssueEndVO issueEndboardInfo) throws Exception;
public void deleteIssueEndBoardInfo(Map<String, String> params) throws Exception;
}
| true
|
c068d2f55a9e1d807090539082bf515da70f1355
|
Java
|
hacking-android/frameworks
|
/devices/google/Pixel 2/29/QPP6.190730.005/src/framework/android/net/wifi/p2p/WifiP2pProvDiscEvent.java
|
UTF-8
| 2,910
| 2.09375
| 2
|
[] |
no_license
|
/*
* Decompiled with CFR 0.145.
*/
package android.net.wifi.p2p;
import android.annotation.UnsupportedAppUsage;
import android.net.wifi.p2p.WifiP2pDevice;
public class WifiP2pProvDiscEvent {
public static final int ENTER_PIN = 3;
public static final int PBC_REQ = 1;
public static final int PBC_RSP = 2;
public static final int SHOW_PIN = 4;
private static final String TAG = "WifiP2pProvDiscEvent";
@UnsupportedAppUsage
public WifiP2pDevice device;
@UnsupportedAppUsage
public int event;
@UnsupportedAppUsage
public String pin;
@UnsupportedAppUsage
public WifiP2pProvDiscEvent() {
this.device = new WifiP2pDevice();
}
public WifiP2pProvDiscEvent(String string2) throws IllegalArgumentException {
Object object;
block4 : {
block9 : {
block6 : {
block8 : {
block7 : {
block5 : {
object = string2.split(" ");
if (((String[])object).length < 2) break block4;
if (!object[0].endsWith("PBC-REQ")) break block5;
this.event = 1;
break block6;
}
if (!((String)object[0]).endsWith("PBC-RESP")) break block7;
this.event = 2;
break block6;
}
if (!((String)object[0]).endsWith("ENTER-PIN")) break block8;
this.event = 3;
break block6;
}
if (!((String)object[0]).endsWith("SHOW-PIN")) break block9;
this.event = 4;
}
this.device = new WifiP2pDevice();
this.device.deviceAddress = object[1];
if (this.event == 4) {
this.pin = object[2];
}
return;
}
object = new StringBuilder();
((StringBuilder)object).append("Malformed event ");
((StringBuilder)object).append(string2);
throw new IllegalArgumentException(((StringBuilder)object).toString());
}
object = new StringBuilder();
((StringBuilder)object).append("Malformed event ");
((StringBuilder)object).append(string2);
throw new IllegalArgumentException(((StringBuilder)object).toString());
}
public String toString() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(this.device);
stringBuffer.append("\n event: ");
stringBuffer.append(this.event);
stringBuffer.append("\n pin: ");
stringBuffer.append(this.pin);
return stringBuffer.toString();
}
}
| true
|
cf50f62a70a70832035f5c39d9cd7cf4c345e8ba
|
Java
|
javierdenis/PUCP
|
/RedSemaforica/src/redsemaforica/Interseccion.java
|
UTF-8
| 3,640
| 2.71875
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package redsemaforica;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author javier
*/
public class Interseccion implements Runnable {
//La duracion del primer color sera = c1+c3;
//La duracion del segundo color sera = c2;
//La duracion total del ciclo sera = c1+c2+c3+2*IGP(3segundos)
private String name;
private boolean b; // PRIMER COLOR: La interseccion inicia en verde = 1 orojo =0 para la vía principal
private int c1;
private int c2;
private int c3;
private int contador;
private int q_EO, q_OE, q_NS, q_SN;
private int vm_EO, vm_OE, vm_NS, vm_SN;
public Interseccion(String name, boolean estado, int c1, int c2, int c3) {
this.name = name;
this.b = estado;
this.c1 = c1;
this.c2 = c2;
this.c3 = c3;
this.q_EO = this.q_OE = this.q_NS = this.q_SN = 100;
this.vm_EO = this.vm_OE = this.vm_NS = this.vm_SN = 20;
}
@Override
public void run() {
while (true) {
contador = b ? c2 : c1;
while (contador >= 0) {
contador--;
ActualizarFlujos();
try {
Thread.sleep(1000); //duerme un segundo
} catch (InterruptedException ex) {
Logger.getLogger(Interseccion.class.getName()).log(Level.SEVERE, null, ex);
}
}
b = !b;
}
}
public void ActualizarFlujos() {
Random r = new Random();
int max = 10;
int min = 0;
int nAutos = r.nextInt((max - min) + 1) + min;
q_EO = q_OE = q_NS = q_SN =q_EO+nAutos;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isB() {
return b;
}
public void setB(boolean b) {
this.b = b;
}
public int getC1() {
return c1;
}
public void setC1(int c1) {
this.c1 = c1;
}
public int getC2() {
return c2;
}
public void setC2(int c2) {
this.c2 = c2;
}
public int getContador() {
return contador;
}
public void setContador(int contador) {
this.contador = contador;
}
public int getC3() {
return c3;
}
public void setC3(int c3) {
this.c3 = c3;
}
public int getQ_EO() {
return q_EO;
}
public void setQ_EO(int q_EO) {
this.q_EO = q_EO;
}
public int getQ_OE() {
return q_OE;
}
public void setQ_OE(int q_OE) {
this.q_OE = q_OE;
}
public int getQ_NS() {
return q_NS;
}
public void setQ_NS(int q_NS) {
this.q_NS = q_NS;
}
public int getQ_SN() {
return q_SN;
}
public void setQ_SN(int q_SN) {
this.q_SN = q_SN;
}
public int getVm_EO() {
return vm_EO;
}
public void setVm_EO(int vm_EO) {
this.vm_EO = vm_EO;
}
public int getVm_OE() {
return vm_OE;
}
public void setVm_OE(int vm_OE) {
this.vm_OE = vm_OE;
}
public int getVm_NS() {
return vm_NS;
}
public void setVm_NS(int vm_NS) {
this.vm_NS = vm_NS;
}
public int getVm_SN() {
return vm_SN;
}
public void setVm_SN(int vm_SN) {
this.vm_SN = vm_SN;
}
}
| true
|
055c4585ac43730a3cb2ccec0ae746222e830dfa
|
Java
|
sharkee89/medication-platform
|
/src/java/session/otpremnica/SBOtpremnica.java
|
UTF-8
| 2,000
| 2.25
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package session.otpremnica;
import domen.Otpremnica;
import static domen.Stavkaotpremnice_.otpremnica;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author Stefan
*/
@Stateless
public class SBOtpremnica implements SBOtpremnicaLocal{
@PersistenceContext (unitName = "ZZZLekovi_1PU")
private EntityManager em;
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
@Override
public EntityManager vratiEM() {
return em;
}
@Override
public Otpremnica vratiOtpremnicaPoID(Integer id) {
return em.find(Otpremnica.class, id);
}
@Override
public void sacuvajOtpremnicu(Otpremnica otp) {
Otpremnica otpDB = em.find(Otpremnica.class, otp.getOtpremnicaID());
if(otpDB==null){
em.persist(otp);
}else{
em.merge(otp);
}
}
public void remove(Otpremnica otp){
em.remove(otp);
}
@Override
public void izbrisiOtpremnicu(Otpremnica otp){
otp = em.getReference(Otpremnica.class, otp.getOtpremnicaID());
em.remove(otp);
}
@Override
public List<Otpremnica> vratiSveOtpremnice() {
return em.createQuery("SELECT o FROM Otpremnica o").getResultList();
}
@Override
public void izdajOtpremnicu(Otpremnica otp) {
em.persist(otp);
}
@Override
public int vratiRB() {
if(!vratiSveOtpremnice().isEmpty()){
return vratiSveOtpremnice().get(vratiSveOtpremnice().size()-1).getOtpremnicaID()+1;
}else{
return 1;
}
}
}
| true
|
8199fa9d0c44a18877378c55d3b5df6c68bfd54f
|
Java
|
OLgaKuzznetsova/Bot
|
/BotLogic.java
|
UTF-8
| 2,223
| 3.15625
| 3
|
[] |
no_license
|
package com.company;
import java.util.Random;
import java.util.Scanner;
public class BotLogic {
private int[] states = new int[]{-1, 0, 0};
//private String userInput;
private Data data = new Data();
private String[] words = data.getWords();
private String[] definition = data.getDefinitions();
private int counter = 0;
public String handleUserInput(int chatId, String userInput) {
if (states[0] == -1) {
states[0] = 0;
return data.getMainMenu();
}
if (userInput.equalsIgnoreCase("Определения")) {
states[0] = 1;
return data.getMenu1();
}
//if (userInput.equalsIgnoreCase("Тест")) {
//states[0] = 2;
//return data.getMenu2();
//}
if (userInput.equalsIgnoreCase("Меню")) {
states[0] = 0;
return data.getMenu();
}
if (states[0] == 1)
return optionOne(userInput);
//if (states[0] == 2)
//return optionTwo(userInput);
return "Данные введены неверно";
}
public String optionOne(String userInput) {
for (int i = 0; i < words.length; i++) {
if (userInput.equalsIgnoreCase(words[i])) {
return words[i] + "-" + definition[i];
}
}
return "Нет такого определения.";
}
/*public String optionTwo(String userInput) {
String answer = "";
if (states[1] == 0) {
states[1] = 1;
answer = words[counter];
return definition[counter] + "\n";
}
if (states[1] == 1) {
states[1] = 0;
if (words.length - 1 == counter) {
counter = 0;
} else {
counter++;
}
if (userInput.equalsIgnoreCase(answer)) {
return "Правильный ответ";
} else {
return ("Неправильный ответ! Правильный ответ - " + answer);
}
}
return "";
}*/
}
| true
|
f60e577853cd4a2548c57351ee5f5437829856a3
|
Java
|
dafrito/Riviera
|
/src/script/parsing/tokens/RiffToken.java
|
UTF-8
| 359
| 1.828125
| 2
|
[] |
no_license
|
/**
*
*/
package script.parsing.tokens;
import parsing.Token;
import script.parsing.ScriptElement;
/**
* A RiffScript {@link Token}. This is used to ease the transition from
* {@link ScriptElement} since this class's visitor type can be found at
* runtime.
*
* @author Aaron Faanes
*
*/
public interface RiffToken extends Token<RiffTokenVisitor> {
}
| true
|
f8e57ca9b673a35a792ed4be2714247685dde956
|
Java
|
shanqiu1206/Sentinel
|
/sentinel-core/src/main/java/com/alibaba/csp/sentinel/property/PropertyListener.java
|
UTF-8
| 183
| 1.640625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.alibaba.csp.sentinel.property;
/**
* @author jialiang.linjl
*/
public interface PropertyListener<T> {
void configUpdate(T value);
void configLoad(T value);
}
| true
|
77f01df94e8e28adc57db655ddfbaf38d8884b7a
|
Java
|
SAP/scimono
|
/scimono-server/src/main/java/com/sap/scimono/callback/bulk/BulkRequestCallback.java
|
UTF-8
| 501
| 1.96875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.sap.scimono.callback.bulk;
import com.sap.scimono.entity.bulk.BulkBody;
import com.sap.scimono.entity.bulk.RequestOperation;
import com.sap.scimono.entity.bulk.ResponseOperation;
public interface BulkRequestCallback {
/**
* Handles a collection of user and group operations as described as described in SCIM 2.0 Bulk Operations.
*
* @param bulkRequest
* @return bulkResponse
*/
BulkBody<ResponseOperation> handleBulkRequest(BulkBody<RequestOperation> bulkRequest);
}
| true
|
66fc6019fe6ce7ba6818e376c2fe047319536744
|
Java
|
wenweibo/Snail
|
/app/src/main/java/com/cqkj/snail/system/callbackevent/RefreshEvent.java
|
UTF-8
| 391
| 2.140625
| 2
|
[] |
no_license
|
package com.cqkj.snail.system.callbackevent;
/**
* 刷新广播实体
* @author 闻维波
* @since 2019/08/26 09:55
*/
public class RefreshEvent {
// 0:刷新买车页面
int flag;
public RefreshEvent(int flag) {
this.flag = flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public int getFlag() {
return flag;
}
}
| true
|
f563a74cd3b994324b9dc7bd2534d3ccd0d51ab4
|
Java
|
Letractively/jcatapult
|
/modules/jcatapult-user-module/tags/1.0-RC10/src/java/main/org/jcatapult/module/user/service/DefaultUserHandler.java
|
UTF-8
| 11,884
| 1.875
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2001-2007, JCatapult.org, All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
*/
package org.jcatapult.module.user.service;
import java.util.ArrayList;
import java.util.Arrays;
import static java.util.Arrays.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jcatapult.module.user.domain.Address;
import org.jcatapult.module.user.domain.AuditableCreditCard;
import org.jcatapult.module.user.domain.DefaultRole;
import org.jcatapult.module.user.domain.DefaultUser;
import org.jcatapult.module.user.domain.PhoneNumber;
import org.jcatapult.module.user.domain.Role;
import org.jcatapult.module.user.domain.UserProperty;
import org.jcatapult.persistence.domain.Identifiable;
import org.jcatapult.persistence.service.PersistenceService;
import com.google.inject.Inject;
import net.java.error.ErrorList;
import net.java.error.PropertyError;
import net.java.lang.StringTools;
import net.java.validate.EmailValidator;
import net.java.validate.RequiredValidator;
import net.java.validate.Validator;
/**
* <p>
* This implements the UserHandler for the Jcatapult default domain
* classes. These classes are {@link DefaultUser} and {@link DefaultRole}.
* </p>
*
* @author Brian Pontarelli
*/
@SuppressWarnings("unchecked")
public class DefaultUserHandler<T extends DefaultUser, U extends DefaultRole> implements UserHandler<T, U> {
private final UserConfiguration configuration;
private final PersistenceService persistenceService;
@Inject
public DefaultUserHandler(UserConfiguration configuration, PersistenceService persistenceService) {
this.configuration = configuration;
this.persistenceService = persistenceService;
}
/**
* {@inheritDoc}
*/
public T createUser() {
return (T) new DefaultUser();
}
/**
* {@inheritDoc}
*/
public Class<T> getUserType() {
return (Class<T>) DefaultUser.class;
}
/**
* {@inheritDoc}
*/
public Class<U> getRoleType() {
return (Class<U>) DefaultRole.class;
}
/**
* {@inheritDoc}
*/
public Map<String, Integer[]> getDefaultAssociations() {
return new HashMap<String, Integer[]>();
}
/**
* {@inheritDoc}
*/
public Set<Role> getDefaultRoles() {
DefaultRole role = persistenceService.queryFirst(getRoleType(),
"select r from " + getRoleType().getSimpleName() + " r where r.name = ?1", "user");
if (role == null) {
return new HashSet<Role>();
}
return new HashSet<Role>(asList(role));
}
/**
* {@inheritDoc}
*/
public void associate(T user, Map<String, Integer[]> associations) {
Integer[] roleIds = associations.get("roles");
if (roleIds != null && roleIds.length > 0) {
List<U> roles = persistenceService.queryAll(getRoleType(),
"select r from " + getRoleType().getSimpleName() + " r where r.id in (?1)",
Arrays.asList(roleIds));
user.getRoles().addAll(roles);
}
}
/**
* {@inheritDoc}
*/
public ErrorList validate(T user, Map<String, Integer[]> associations, boolean existing, String password, String passwordConfirm) {
boolean nameRequired = configuration.getDomainFlags().get(DefaultUserConfiguration.NAME_REQUIRED_FLAG);
boolean businessRequired = configuration.getDomainFlags().get(DefaultUserConfiguration.BUSINESS_REQUIRED_FLAG);
boolean homeAddressRequired = configuration.getDomainFlags().get(DefaultUserConfiguration.HOME_ADDRESS_REQUIRED_FLAG);
boolean workAddressRequired = configuration.getDomainFlags().get(DefaultUserConfiguration.WORK_ADDRESS_REQUIRED_FLAG);
boolean homePhoneRequired = configuration.getDomainFlags().get(DefaultUserConfiguration.HOME_PHONE_REQUIRED_FLAG);
boolean workPhoneRequired = configuration.getDomainFlags().get(DefaultUserConfiguration.WORK_PHONE_REQUIRED_FLAG);
boolean cellPhoneRequired = configuration.getDomainFlags().get(DefaultUserConfiguration.CELL_PHONE_REQUIRED_FLAG);
ErrorList errors = new ErrorList();
// User properties
if (!validate(new RequiredValidator(), user, "login", "required", errors)) {
validate(new EmailValidator(), user, "login", "email", errors);
}
if (!existing || !StringTools.isTrimmedEmpty(password)) {
if (StringTools.isTrimmedEmpty(password)) {
errors.addError("password", "password.required");
} else if (password.length() < 5) {
errors.addError("password", "password.length");
}
}
if (!StringTools.isTrimmedEmpty(password) && !password.equals(passwordConfirm)) {
errors.addError("passwordConfirm", "passwordConfirm.match");
}
if (nameRequired) {
validate(new RequiredValidator(), user, "name.firstName", "required", errors);
validate(new RequiredValidator(), user, "name.lastName", "required", errors);
}
if (businessRequired) {
validate(new RequiredValidator(), user, "companyName", "required", errors);
}
// Contact info, check the addresses
if (user.getAddresses() != null) {
Map<String, Address> addresses = user.getAddresses();
for (String type : addresses.keySet()) {
Address address = addresses.get(type);
if (Address.isContainsData(address) || (homeAddressRequired && type.equals("home")) ||
(workAddressRequired && type.equals("work"))) {
validate(new RequiredValidator(), user, "addresses['" + type + "'].street", "required", errors);
validate(new RequiredValidator(), user, "addresses['" + type + "'].city", "required", errors);
validate(new RequiredValidator(), user, "addresses['" + type + "'].country", "required", errors);
if (address.getCountry() != null && address.getCountry().equals("US")) {
validate(new RequiredValidator(), user, "addresses['" + type + "'].state", "required", errors);
validate(new RequiredValidator(), user, "addresses['" + type + "'].postalCode", "required", errors);
}
}
}
}
// Credit cards
List<AuditableCreditCard> creditCards = user.getCreditCards();
for (int i = 0; i < creditCards.size(); i++) {
AuditableCreditCard creditCard = creditCards.get(i);
if (creditCard.getExpirationDate() != null || creditCard.getExpirationMonth() != null ||
!StringTools.isEmpty(creditCard.getFirstName()) || !StringTools.isEmpty(creditCard.getLastName()) ||
!StringTools.isEmpty(creditCard.getNumber()) || !StringTools.isEmpty(creditCard.getSvn()) ||
Address.isContainsData(creditCard.getAddress())) {
validate(new RequiredValidator(), user, "creditCard[" + i + "].firstName", "required", errors);
validate(new RequiredValidator(), user, "creditCard[" + i + "].lastName", "required", errors);
validate(new RequiredValidator(), user, "creditCard[" + i + "].expirationMonth", "required", errors);
validate(new RequiredValidator(), user, "creditCard[" + i + "].expirationYear", "required", errors);
validate(new RequiredValidator(), user, "creditCard[" + i + "].number", "required", errors);
validate(new RequiredValidator(), user, "creditCard[" + i + "].address.street", "required", errors);
validate(new RequiredValidator(), user, "creditCard[" + i + "].address.city", "required", errors);
validate(new RequiredValidator(), user, "creditCard[" + i + "].address.country", "required", errors);
if (creditCard.getAddress().getCountry() != null && creditCard.getAddress().getCountry().equals("US")) {
validate(new RequiredValidator(), user, "creditCard[" + i + "].address.state", "required", errors);
validate(new RequiredValidator(), user, "creditCard[" + i + "].address.postalCode", "required", errors);
}
}
}
// Check required phone numbers
if (homePhoneRequired) {
validate(new RequiredValidator(), user, "phoneNumbers['home'].number", "required", errors);
}
if (workPhoneRequired) {
validate(new RequiredValidator(), user, "phoneNumbers['work'].number", "required", errors);
}
if (cellPhoneRequired) {
validate(new RequiredValidator(), user, "phoneNumbers['cell'].number", "required", errors);
}
return errors;
}
private boolean validate(Validator validator, DefaultUser user, String property, String key,
ErrorList errors, String... params) {
Map<String, String> parameters = new HashMap<String, String>();
for (int i = 0; i < params.length; i = i + 2) {
String name = params[i];
String value = params[i + 1];
parameters.put(name, value);
}
Wrapper wrapper = new Wrapper(user);
PropertyError error = validator.fetchAndValidate("user." + property, wrapper,
"user." + property + "." + key,
null, null, parameters);
if (error != null) {
errors.addError(error);
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public void prepare(T user) {
// Prepare UserProperty's
if (user.getProperties() != null) {
Map<String, UserProperty> props = user.getProperties().getMap();
for (String name : props.keySet()) {
props.get(name).setUser(user);
}
}
// Setup any types for addresses and phone numbers
if (user.getAddresses() != null) {
Map<String, Address> addresses = user.getAddresses();
for (String type : addresses.keySet()) {
addresses.get(type).setType(type);
}
}
if (user.getPhoneNumbers() != null) {
Map<String, PhoneNumber> phoneNumbers = user.getPhoneNumbers();
for (String type : phoneNumbers.keySet()) {
phoneNumbers.get(type).setType(type);
}
}
}
/**
* Gets the roles only.
*
* @param user The user to get the roles from.
* @return The Map that contains the role association IDs.
*/
public Map<String, Integer[]> getAssociationIds(T user) {
Map<String, Integer[]> values = new HashMap<String, Integer[]>();
List<Integer> rolesIds = new ArrayList<Integer>();
for (Identifiable ident : user.getRoles()) {
rolesIds.add(ident.getId());
}
values.put("roles", rolesIds.toArray(new Integer[rolesIds.size()]));
return values;
}
public class Wrapper {
private final DefaultUser user;
private Wrapper(DefaultUser user) {
this.user = user;
}
public DefaultUser getUser() {
return user;
}
}
}
| true
|
fd92d19705c32c22cc2dde18b90224b6e31ba035
|
Java
|
gaojianyang/Uchat_Refactoring
|
/data/src/main/java/com/personal/xiri/data/repository/datasource/CloudSkinDataStore.java
|
UTF-8
| 1,045
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.personal.xiri.data.repository.datasource;
import com.personal.xiri.data.entity.SkinEntity;
import com.personal.xiri.data.net.ResponseErrorFunc;
import com.personal.xiri.data.net.SkinApi;
import com.personal.xiri.domin.Response;
import java.util.List;
import io.reactivex.Flowable;
import io.reactivex.Observable;
/**
* Created by Gaojianyang on 18/9/9.
* github https://github.com/gaojianyang
*/
public class CloudSkinDataStore implements SkinDataStore {
private SkinApi skinApi;
public CloudSkinDataStore(SkinApi skinApi) {
this.skinApi = skinApi;
}
@Override
public Observable<SkinEntity> getSkinById(long id) {
return null;
}
@Override
public Observable<List<SkinEntity>> getUserSkinsById(String identifier) {
return null;
}
@Override
public Observable<List<SkinEntity>> getRecentSkins() {
return skinApi.getRecentSkins().map(new ResponseErrorFunc<>());
}
@Override
public void createOrUpdateSkin(SkinEntity skinEntity) {
}
}
| true
|
93e11731d5f9687bc0a4849797a6d51b4087a2cc
|
Java
|
Goncharov01/MVVMRetrofitRecycler
|
/app/src/main/java/com/example/mvvmretrofitrecycler/RecyclerAdapter.java
|
UTF-8
| 2,485
| 2.515625
| 3
|
[] |
no_license
|
package com.example.mvvmretrofitrecycler;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private Context context;
private List<TaskModel> taskModels = new ArrayList<>();
public RecyclerAdapter(List<TaskModel> taskModels,Context context) {
this.taskModels = taskModels;
this.context = context;
}
class RecyclerViewHolder extends RecyclerView.ViewHolder{
private TextView nameView;
private TextView idView;
private TextView ageView;
public RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
nameView = itemView.findViewById(R.id.taskName);
idView = itemView.findViewById(R.id.taskId);
ageView = itemView.findViewById(R.id.taskAge);
}
}
@NonNull
@Override
// возвращает объект ViewHolder, который будет хранить данные по одному объекту
public RecyclerAdapter.RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context)
.inflate(R.layout.task_list_item,parent,false);
return new RecyclerViewHolder(view);
}
//выполняет привязку объекта ViewHolder к объекту TaskModel
@Override
public void onBindViewHolder(@NonNull RecyclerAdapter.RecyclerViewHolder holder, int position) {
if (taskModels.size() != 0){
TaskModel taskModel = this.taskModels.get(position);
holder.nameView.setText(taskModel.getName());
holder.idView.setText(taskModel.getId().toString());
holder.ageView.setText(taskModel.getAge().toString());
}
}
@Override
public int getItemCount() {
return taskModels.size();
}
public void onChange(List<TaskModel> taskModels ){
this.taskModels.clear();
this.taskModels.addAll(taskModels);
notifyDataSetChanged();
}
}
| true
|
c557fe238e7f678a12a03ba82b604da83efccec9
|
Java
|
yhaile/TokenAnalyzer
|
/src/java112/analyzer/BigWordAnalyzer.java
|
UTF-8
| 2,911
| 3.921875
| 4
|
[] |
no_license
|
package java112.analyzer;
import java.io.*;
import java.util.*;
/**
*This is the BigWordAnalyzer class that implements the interface: analyzer.
*It builds a list of big word that are in the inputed file.
*/
public class BigWordAnalyzer implements Analyzer {
private Properties properties;
private Set<String> bigWords;
private int minimumWordLength;
String totalString = "";
/**Class constructor*/
public BigWordAnalyzer() {
bigWords = new TreeSet();
}
/**Class constructor with one properties paramater
*@param properties
*/
public BigWordAnalyzer(Properties properties) {
this();
this.properties = properties;
}
/**
*This method is passed an individual token and adds it to the TreeSet if it
*is larger or equal to the minimumWordLength.
*@param token
*/
public void processToken(String token) {
minimumWordLength = Integer.parseInt(this.properties.getProperty("bigwords.minimum.length"));
if (token.length() >= minimumWordLength) {
bigWords.add(token);
}
}
/**
*This method loops through the bigWords TreeSet
*and outputs each word to a line.
*@param out
*/
public void bigWordsLoop(PrintWriter out) {
for (Iterator iterator = bigWords.iterator(); iterator.hasNext();) {
out.println(iterator.next());
}
}
/**
*This method writes output to the big_words text file.
*@param inputFilePath
*@exception FileNotFoundException
*@exception Exception
*/
public void writeOutputFile(String inputFilePath) {
String outputFilePath = properties.getProperty("output.dir");
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(outputFilePath + properties.getProperty("output.file.bigwords"))));
bigWordsLoop(out);
} catch (java.io.IOException fnfe) {
System.out.println("Failed to read input file");
fnfe.printStackTrace();
} catch (Exception exception) {
System.out.println("General Error");
exception.printStackTrace();
} finally {
out.close();
}
}
/**
*This method writes output to the big words dialog box.
*@param inputFilePath
*@param totalString
*/
public String outputDialogBoxes(String inputFilePath) {
totalString += "\n\nBIG WORDS ANALYZER:\n===================\nThis analyzer finds words over 14 characters long.\n";
for (Iterator iterator = bigWords.iterator(); iterator.hasNext();) {
totalString += "\n" + iterator.next();
}
return totalString;
}
/**
*This is the get method for the bigWords set.
*
*/
public Set<String> getBigWords() {
return bigWords;
}
}
| true
|
a2228b584c4339ce44a03696d8b25aee7a38b454
|
Java
|
zhenzhanlong/demo
|
/mybatisJavaCodeGenerate/src/main/java/imitate/mybatis/code/generation/CodeStartup.java
|
UTF-8
| 1,208
| 1.929688
| 2
|
[] |
no_license
|
package imitate.mybatis.code.generation;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import imitate.mybatis.code.generation.data.base.biz.ITableBiz;
@Configuration
@ComponentScan
@ImportResource({ "classpath:code.xml" })
@EnableAutoConfiguration(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class })
public class CodeStartup {
public static void main(String[] args) {//
ConfigurableApplicationContext application = new SpringApplicationBuilder(CodeStartup.class)
.web(WebApplicationType.NONE).run(args);
ITableBiz tableBizImpl = (ITableBiz) application.getBean("tableBizImpl");
tableBizImpl.createFiles();
}
}
| true
|
e4ed7aa454f4254ebd1cfa1b6d6547aa53610469
|
Java
|
scmod/classFormat
|
/src/main/java/cc/funny/structure/SourceFileAttribute.java
|
UTF-8
| 298
| 1.953125
| 2
|
[] |
no_license
|
package cc.funny.structure;
public class SourceFileAttribute extends AttributeInfo {
private int sourcefile_index;// u2
public int getSourcefile_index() {
return sourcefile_index;
}
public void setSourcefile_index(int sourcefile_index) {
this.sourcefile_index = sourcefile_index;
}
}
| true
|
f19ba6165f48ae62986fbcecca1d83705361b840
|
Java
|
lcc214321/finix
|
/finix-core/src/main/java/com/finix/framework/transport/NonServletEndpoint.java
|
UTF-8
| 3,907
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.finix.framework.transport;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentMap;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.finix.framework.exception.FinixFrameworkException;
import com.finix.framework.rpc.Provider;
import com.finix.framework.rpc.URL;
/**
* 空的ServletEndpoint,用于客户端调用构造协议
*/
public class NonServletEndpoint extends AbstractServletEndpoint {
private static final String MESSAGE = "NonServletEndpoint can not invoke method.";
public NonServletEndpoint() {
super(null);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public ConcurrentMap<String, Provider> getProviders() {
return super.getProviders();
}
@Override
public void init() {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public URL export(Provider provider, URL serviceUrl) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
protected URL doExport(Provider provider, URL serviceUrl) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
protected long getLastModified(HttpServletRequest req) {
return super.getLastModified(req);
}
@Override
protected void doHead(HttpServletRequest req, HttpServletResponse resp) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public void service(ServletRequest req, ServletResponse res) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public void destroy() {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public String getInitParameter(String name) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public Enumeration<String> getInitParameterNames() {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public ServletConfig getServletConfig() {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public ServletContext getServletContext() {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public String getServletInfo() {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public void init(ServletConfig config) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public void log(String msg) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public void log(String message, Throwable t) {
throw new FinixFrameworkException(MESSAGE);
}
@Override
public String getServletName() {
throw new FinixFrameworkException(MESSAGE);
}
}
| true
|
ee21656d6acf5fb89a215d0c4fa388df58f7d53b
|
Java
|
KostyaSha/acceptance-test-harness
|
/src/main/java/org/jenkinsci/test/acceptance/plugins/findbugs/FindBugsAction.java
|
UTF-8
| 568
| 1.90625
| 2
|
[] |
no_license
|
package org.jenkinsci.test.acceptance.plugins.findbugs;
import org.jenkinsci.test.acceptance.plugins.analysis_core.AnalysisAction;
import org.jenkinsci.test.acceptance.po.Build;
import org.jenkinsci.test.acceptance.po.Job;
/**
* Page object for FindBugs action.
*
* @author Fabian Trampusch
*/
public class FindBugsAction extends AnalysisAction {
private static final String PLUGIN = "findbugs";
public FindBugsAction(final Build parent) {
super(parent, PLUGIN);
}
public FindBugsAction(final Job parent) {
super(parent, PLUGIN);
}
}
| true
|
8f250d11f0e4b395213789c6ec8102598191a437
|
Java
|
Nineodes19/happy-end
|
/javaweb服务器/Server/src/laboratory/TCPServer.java
|
UTF-8
| 2,999
| 3.109375
| 3
|
[] |
no_license
|
package laboratory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
/**
* @program:Server
* @author:Nine_odes
* @description:
* @create:2020-10-15 13:24
**/
public class TCPServer {
public static void main(String[] args) {
try(ServerSocket serverSocket = new ServerSocket(8888)){
//TCP状态 listen
Socket socket = serverSocket.accept();
//TCP状态 established
InputStream inputStream = socket.getInputStream();
//windows 终端的代码格式是gbk
Scanner scanner = new Scanner(inputStream,"gbk");
String cmdLine = scanner.next();
//list
//get<hostname>
String[] group = cmdLine.split(" ");
String command = cmdLine;
if(group.length >1){
command = group[0];
}
System.out.println(command);
Writer writer =new OutputStreamWriter(socket.getOutputStream(),"gbk");
if(command.equals("list")){
//
List<String> hostnameList = new ArrayList<>();
hostnameList.add("windows-1");
hostnameList.add("linux-1");
StringBuilder response = new StringBuilder();
for(String hostname : hostnameList){
response.append(hostname);
response.append("\r\n");
}
writer.write(response.toString());
writer.flush();
socket.close();
}else if(command.equals("get")){
//因为要不停的给对方推消息,会影响当前线程的工作
//所以创建新的线程去执行
Thread thread = new Thread(()->{
try{
//没秒给对方发送
while(true){
writer.write("你好\r\n");
writer.flush();
TimeUnit.SECONDS.sleep(1);
}
}catch (IOException | InterruptedException e){
e.printStackTrace();
//发生了IOException,代表一定是对方出错了或者关闭链接了
//代表的意思就是对方退订了,不需要继续查看信息了,则我们关闭链接
try{
socket.close();
}catch (IOException e1){
e1.printStackTrace();
}
}
});
thread.start();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
| true
|
5996f723e5c22e78abfe9142c4b1db7ff45e642c
|
Java
|
iuraiura879/RothTouchlineAndroid
|
/app/src/main/java/com/roth/touchline/NewUserFragment.java
|
UTF-8
| 814
| 2.125
| 2
|
[] |
no_license
|
package com.roth.touchline;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Spinner;
public class NewUserFragment extends Fragment {
//final static String defaultTextForSpinner = "Choose language";
//final static String[] arrayForSpinner = {"EN", "DK", "DE", "FR", "ES", "NO", "SE", "FI", "PL", "PT", "NL"};
//int chosenLanguage = -1;
public NewUserFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Setup UI
View view = inflater.inflate(R.layout.fragment_new_user, container, false);
return view;
}
}
| true
|
f5bf676bb922c476a3b4e7c3a872768f97cdad70
|
Java
|
Danielciro1396/Software3
|
/ResearchScraper/src/main/java/co/edu/uniquindio/software3/proyecto/CvLacScraper/CvLac.java
|
UTF-8
| 25,504
| 2.46875
| 2
|
[] |
no_license
|
package co.edu.uniquindio.software3.proyecto.CvLacScraper;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import co.edu.uniquindio.software3.proyecto.ResearchScraper.ArrayThread;
import co.edu.uniquindio.software3.proyecto.ResearchScraper.Constantes;
import co.edu.uniquindio.software3.proyecto.ResearchScraper.DataSource;
public class CvLac {
// Lista en la que se guardan las direcciones url de cada investigador
public ArrayList<String> urlSet;
// Lista sincronizada en la que se guardan todos los investidagores junto a
// su respectiva informacion
public List<Investigador> investigadores = Collections.synchronizedList(new ArrayList<Investigador>());
/**
* Este metodo se encarga de hacer el llamado al metodo que lee un archivo plano
* y carga el dataSet de url's, ademas, crea y lanza un pool de hilos para
* mejorar el tiempo de ejecucion del programa
*/
public void scrapData() {
long startTime = System.currentTimeMillis();
long stopTime = 0;
long elapsedTime = 0;
leerDataSet();
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < urlSet.size(); i++) {
Runnable worker = new ArrayThread(urlSet.get(i), i, 0, this, null);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
}
try {
Connection connection = DataSource.getInstance().getConnection();
Statement statement = connection.createStatement();
for (int i = 0; i < investigadores.size(); i++) {
Investigador investigador = investigadores.get(i);
String query = Constantes.INSERT_INVES + "(" + investigador.getId() + ", '"
+ investigador.getNombre().toUpperCase() + "', '" + investigador.getCategoria().toUpperCase()
+ "' , '" + investigador.getFormacion().toUpperCase() + "')";
statement.executeQuery(query);
if (investigador.getArticulos() != null) {
ArrayList<Articulo> listaArticulos = investigador.getArticulos();
for (int j = 0; j < listaArticulos.size(); j++) {
Articulo a = listaArticulos.get(j);
if (a.isEsEspecializada()) {
String queryArticulos = Constantes.INSERT_ART + "('" + a.getAutores() + "','"
+ a.getTitulo() + "','" + a.getNomRevista() + "','" + a.getLugar() + "','"
+ a.getAnio() + "', 'SI'," + investigador.getId() + ")";
statement.executeQuery(queryArticulos);
} else {
String queryArticulos = Constantes.INSERT_ART + "('" + a.getAutores() + "','"
+ a.getTitulo() + "','" + a.getNomRevista() + "','" + a.getLugar() + "','"
+ a.getAnio() + "', 'NO'," + investigador.getId() + ")";
statement.executeQuery(queryArticulos);
}
}
}
if (investigador.getEventos() != null) {
ArrayList<EventoCientifico> listaEventos = investigador.getEventos();
for (int j = 0; j < listaEventos.size(); j++) {
EventoCientifico e = listaEventos.get(j);
String queryEventos = Constantes.INSERT_EVT + "('" + e.getNombre() + "','" + e.getTipo() + "','"
+ e.getAmbito() + "','" + e.getLugar() + "','" + e.getFecha() + "','" + e.getRol()
+ "'," + investigador.getId() + ")";
statement.executeQuery(queryEventos);
}
}
if (investigador.getLibros() != null) {
ArrayList<Libro> listaLibros = investigador.getLibros();
for (int j = 0; j < listaLibros.size(); j++) {
Libro l = listaLibros.get(j);
String queryLibros = Constantes.INSERT_LIB + "('" + l.getTitulo() + "','" + l.getAutores()
+ "','" + l.getLugar() + "','" + l.getAnio() + "','" + l.getEditorial() + "',"
+ investigador.getId() + ")";
statement.executeQuery(queryLibros);
}
}
if (investigador.getProyectos() != null) {
ArrayList<Proyecto> listaProyecto = investigador.getProyectos();
for (int j = 0; j < listaProyecto.size(); j++) {
Proyecto p = listaProyecto.get(j);
String queryProyectos = Constantes.INSERT_PROY + "('" + p.getNombre() + "','" + p.getTipo()
+ "','" + p.getFecha() + "'," + investigador.getId() + ")";
statement.executeQuery(queryProyectos);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.err.println(elapsedTime);
}
/**
* Método provisto por JSoup para comprobar el Status code de la respuesta que
* recibo al hacer la petición Codigos: 200 OK 300 Multiple Choices 301 Moved
* Permanently 305 Use Proxy 400 Bad Request 403 Forbidden 404 Not Found 500
* Internal Server Error 502 Bad Gateway 503 Service Unavailable
*
* @param url,
* el enlace de la página web a analizar.
* @return Status Code, el código que identifica el estado de la página.
*/
public int getStatusConnectionCode(String url) {
Response response = null;
try {
response = Jsoup.connect(url).userAgent("Mozilla/5.0").timeout(100000).ignoreHttpErrors(true).execute();
} catch (IOException ex) {
System.out.println("Excepción al obtener el Status Code: " + ex.getMessage());
}
return response.statusCode();
}
/**
* Método que retorna un objeto de la clase Document con el contenido del HTML
* de la web para poder ser parseado posteriormente con JSoup
*
* @param url,
* el enlace de la página web a analizar.
* @return Documento con el HTML de la página en cuestión.
*/
public Document getHtmlDocument(String url) {
Document doc = null;
try {
doc = Jsoup.connect(url).userAgent("Mozilla/5.0").timeout(100000).get();
} catch (IOException ex) {
System.out.println("Excepción al obtener el HTML de la página" + ex.getMessage());
}
return doc;
}
/**
* Metodo que realiza la extraccion de la estructura de una pagina web, separa
* en las diferentas categorias la estructura de la pagina web y hacer el
* llamado al metodo que asigna los datos a cada investigador
*
* @param url,
* direccion url de un investigador
*/
public void extraer(String url) {
if (getStatusConnectionCode(url) == 200) {
// Lista en la que se guarda la informacion personal de cada
// invsestigador
ArrayList<String> elemInfoPersonal = new ArrayList<>();
// Lista en la que se guardan la formacion academica de cada
// invsestigador
ArrayList<String> elemFormacionAcam = new ArrayList<>();
// Lista en la que se guardan los eventos en los que ha participado
// de cada
// invsestigador
ArrayList<String> elemEventos = new ArrayList<>();
// Lista en la que se guardan los articulos que ha escrito de cada
// invsestigador
ArrayList<String> elemArticulos = new ArrayList<>();
// Lista en la que se guardan los libros que ha escrito de cada
// invsestigador
ArrayList<String> elemLibros = new ArrayList<>();
// Lista en la que se guardan los informes de investigación que ha
// escrito
// de cada invsestigador
ArrayList<String> elemInformes = new ArrayList<>();
// Lista en la que se guardan los proyectos en los que ha
// participado de
// cada invsestigador
ArrayList<String> elemProyectos = new ArrayList<>();
// Lista en la que se guardan las publicaciones en revistas no
// especializadas que ha realizado de cada invsestigador
ArrayList<String> elemPublicacionesN = new ArrayList<>();
// Obtengo el HTML de la web en un objeto Document
Document document = getHtmlDocument(url);
// Busca todas las coincidencias que estan dentro de
Elements entradas = document.select("tbody>tr>td>table>tbody");
for (Element elem : entradas) {
if (elem.text().contains("Nombre en citaciones")) {
elemInfoPersonal.add(elem.toString());
}
if (elem.text().contains("Formación Académica")) {
elemFormacionAcam.add(elem.toString());
}
if (elem.text().contains("Eventos científicos")) {
elemEventos.add(elem.toString());
}
if (elem.text().contains("Artículos")) {
elemArticulos.add(elem.toString());
}
if (elem.text().contains("Libros")) {
elemLibros.add(elem.toString());
}
if (elem.text().contains("Informes de investigación")) {
elemInformes.add(elem.toString());
}
if (elem.text().contains("Proyectos")) {
elemProyectos.add(elem.toString());
}
if (elem.text().contains("Textos en publicaciones no científicas")) {
elemPublicacionesN.add(elem.toString());
}
}
// Obtenemos el id del investigador a partir de la URL
String id = url.substring(87);
extraerDatos(limpiar(elemInfoPersonal), limpiar(elemFormacionAcam), limpiar(elemEventos),
limpiar(elemArticulos), limpiar(elemLibros), limpiar(elemInformes), limpiar(elemProyectos),
limpiar(elemPublicacionesN), id);
} else {
System.out.println("El Status Code no es OK es: " + getStatusConnectionCode(url));
}
}
/**
* Este metodo asigna cada uno de los elementos encontrados al investigador
* respectivo y lo añade a la lista de investigadores
*
* @param datosPersonales,
* lista con los datos personales de cada investigador
* @param formacion,
* lista con la formacion academica de cada investigador
* @param eventos,
* lista con los eventos en los que participo cada investigador
* @param articulos,
* lista con los articulos escritos por cada investigador
* @param libros,
* lista con los libros escritos por cada investigador
* @param informes,
* lista con los informes de investigacion realizados por cada
* investigador
* @param proyectos,
* lista con los proyectos realizados por cada investigador
* @param publicacionesN,
* lista con las publicaciones en revistas no especializadas
* realizadas por cada investigador
* @param id,
* identificador unico de cada investigador
*/
public void extraerDatos(ArrayList<String> datosPersonales, ArrayList<String> formacion, ArrayList<String> eventos,
ArrayList<String> articulos, ArrayList<String> libros, ArrayList<String> informes,
ArrayList<String> proyectos, ArrayList<String> publicacionesN, String id) {
Investigador investigador = new Investigador();
// Si no posee datos personales, el perfil es privado.
if (datosPersonales.size() == 0) {
investigador.setNombre("PERFIL PRIVADO");
investigador.setId(Integer.parseInt(id));
investigador.setCategoria("N/D");
investigador.setFormacion("N/D");
ArrayList<EventoCientifico> eventos1 = new ArrayList<>();
ArrayList<Articulo> articulos1 = new ArrayList<>();
ArrayList<Libro> libros1 = new ArrayList<>();
ArrayList<Proyecto> proyectos1 = new ArrayList<>();
investigador.setArticulos(articulos1);
investigador.setEventos(eventos1);
investigador.setProyectos(proyectos1);
investigador.setLibros(libros1);
investigadores.add(investigador);
} else {
try {
for (int i = 0; i < datosPersonales.size(); i++) {
if (datosPersonales.get(i).contains("CATEGORÍA")) {
String registro = datosPersonales.get(i + 1);
char[] aux = registro.toCharArray();
String categoria = "";
for (int j = 0; j < aux.length; j++) {
if (aux[j] == '(') {
categoria = registro.substring(0, j - 1);
investigador.setCategoria(categoria);
break;
}
}
}
if (datosPersonales.get(i).equalsIgnoreCase("NOMBRE")) {
investigador.setNombre(datosPersonales.get(i + 1));
}
}
investigador.setId(Integer.parseInt(id));
if (investigador.getCategoria() == null) {
investigador.setCategoria("N/D");
}
extraerFormacionAcademica(formacion, investigador);
if (investigador.getFormacion() == null) {
investigador.setFormacion("N/D");
}
extraerEventos(eventos, investigador);
extraerArticulos(articulos, investigador);
extraerLibros(libros, investigador);
extraerProyectos(proyectos, investigador);
investigadores.add(investigador);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Metodo que extrae y asigna la formacion academica de cada investigador
*
* @param elementos,
* Lista donde esta toda la informacion de la formacion academica del
* investigador
* @param investigador,
* investigador al que se le a asignar la informacion
*/
public void extraerFormacionAcademica(ArrayList<String> elementos, Investigador investigador) {
for (int i = 0; i < elementos.size(); i++) {
if (elementos.get(i).equalsIgnoreCase("Formación Académica")) {
investigador.setFormacion(elementos.get(i + 1));
}
}
}
/**
* Este metodo filtra la informacion y la segmenta en su respectiva categoria
* para poder agregarla ordenadamente a las listas de cada uno de los
* investigadores
*
* @param elementos,
* Lista donde estan todos los eventos en los que ha participado el
* investigador
* @param investigador,
* investigador al que se le a asignar la informacion
*/
public void extraerEventos(ArrayList<String> elementos, Investigador investigador) {
String nombre = "";
String tipo = "";
String ambito = "";
String fecha = "";
String lugar = "";
String rol = "";
String aux = "";
String aux2 = "";
aux = StringUtils.stripAccents(investigador.getNombre());
ArrayList<EventoCientifico> eventoAux = new ArrayList<>();
for (int i = 0; i < elementos.size(); i++) {
EventoCientifico eventos = new EventoCientifico();
if (elementos.get(i).contains("NOMBRE DEL EVENTO:")) {
nombre = elementos.get(i + 1);
}
if (elementos.get(i).contains("TIPO DE EVENTO:")) {
tipo = elementos.get(i + 1);
}
if (elementos.get(i).contains("ÁMBITO:")) {
if (elementos.get(i + 1).contains("REALIZADO EL")) {
ambito = "N/D";
} else {
ambito = elementos.get(i + 1);
}
}
if (elementos.get(i).contains("REALIZADO EL:")) {
String cadena = elementos.get(i);
fecha = cadena.substring(13, 17);
if (fecha.contains(",")) {
fecha = "N/D";
}
char[] auxiliar = cadena.toCharArray();
int posI = 0;
int posF = 0;
for (int j = 0; j < auxiliar.length; j++) {
if (auxiliar[j] == 'E' && auxiliar[j + 1] == 'N' && auxiliar[j + 2] == ' ') {
posI = j + 3;
for (int k = posI; k < auxiliar.length; k++) {
if (auxiliar[k] == '-') {
posF = k;
if (cadena.substring(posI, posF).equals(" ")) {
lugar = "N/D";
} else {
lugar = cadena.substring(posI, posF);
}
j = auxiliar.length;
break;
}
}
}
}
}
aux2 = StringUtils.stripAccents(elementos.get(i));
if (aux2.equalsIgnoreCase(aux) && elementos.get(i + 1).contains("ROL EN EL EVENTO:")) {
if (StringUtils.isNumeric(elementos.get(i + 2))) {
rol = "N/D";
} else {
rol = elementos.get(i + 2);
}
eventos.setNombre(nombre);
eventos.setTipo(tipo);
eventos.setAmbito(ambito);
eventos.setFecha(fecha);
eventos.setLugar(lugar);
eventos.setRol(rol);
eventoAux.add(eventos);
investigador.setEventos(eventoAux);
}
}
}
/**
* Este metodo filtra la informacion y la segmenta en su respectiva categoria
* para poder agregarla ordenadamente a las listas de cada uno de los
* investigadores
*
* @param elementos,
* Lista donde estan todos los articulos en los que ha participado el
* investigador
* @param investigador,
* investigador al que se le a asignar la informacion
*/
public void extraerArticulos(ArrayList<String> elementos, Investigador investigador) {
boolean esEspecializada = false;
String autores = "";
String titulo = "";
String lugar = "";
String nomRevista = "";
String anio = "";
String aux = "";
String aux2 = "";
aux = StringUtils.stripAccents(investigador.getNombre());
ArrayList<Articulo> articuloAux = new ArrayList<>();
for (int i = 0; i < elementos.size(); i++) {
Articulo articulo = new Articulo();
if (elementos.get(i).contains("PUBLICADO EN REVISTA ESPECIALIZADA")) {
esEspecializada = true;
}
aux2 = StringUtils.stripAccents(elementos.get(i));
if (aux2.toUpperCase().contains(aux.toUpperCase())) {
String cadena = elementos.get(i);
char[] auxiliar = cadena.toCharArray();
int posI = 0;
int posF = 0;
for (int j = 0; j < auxiliar.length; j++) {
if (auxiliar[j] != ' ') {
if (auxiliar[j] == '"') {
posI = j + 1;
for (int k = posI + 1; k < auxiliar.length; k++) {
if (auxiliar[k] == '"') {
posF = k;
titulo = cadena.substring(posI, posF);
j = k;
break;
}
}
} else if (auxiliar[j] == ':' && j + 1 < auxiliar.length) {
posI = j + 1;
lugar = cadena.substring(posI + 1);
} else {
posI = j;
for (int k = posI; k < auxiliar.length; k++) {
if (auxiliar[k] == '"') {
posF = k - 2;
autores = cadena.substring(posI, posF);
j = k - 1;
break;
}
}
}
}
}
nomRevista = elementos.get(i + 1);
}
// if (elementos.get(i).contains("ED:")) {
// nomRevista += " Editorial: " + elementos.get(i + 1);
// }
if (elementos.get(i).contains("FASC.")) {
String cadena = elementos.get(i + 1);
char[] auxiliar = cadena.toCharArray();
int posI = 0;
int posF = 0;
for (int j = 0; j < auxiliar.length; j++) {
if (auxiliar[j] == ',') {
posI = j + 1;
for (int k = posI; k < auxiliar.length; k++) {
if (auxiliar[k] == ',') {
posF = k;
anio = cadena.substring(posI, posF);
j = k;
break;
}
}
}
}
articulo.setEsEspecializada(esEspecializada);
articulo.setTitulo(titulo);
articulo.setAnio(anio);
articulo.setAutores(autores);
articulo.setLugar(lugar);
articulo.setNomRevista(nomRevista);
articuloAux.add(articulo);
investigador.setArticulos(articuloAux);
// insertarArticulos(articulo, investigador.getId());
esEspecializada = false;
}
}
}
/**
* Este metodo filtra la informacion y la segmenta en su respectiva categoria
* para poder agregarla ordenadamente a las listas de cada uno de los
* investigadores
*
* @param elementos,
* Lista donde estan todos los libros en los que ha participado el
* investigador
* @param investigador,
* investigador al que se le a asignar la informacion
*/
public void extraerLibros(ArrayList<String> elementos, Investigador investigador) {
String autores = "";
String titulo = "";
String lugar = "";
String anio = "";
String editorial = "";
String aux = "";
String aux2 = "";
aux = StringUtils.stripAccents(investigador.getNombre());
ArrayList<Libro> libroAux = new ArrayList<>();
for (int i = 0; i < elementos.size(); i++) {
Libro libro = new Libro();
aux2 = StringUtils.stripAccents(elementos.get(i));
if (aux2.toUpperCase().contains(aux.toUpperCase())) {
String cadena = elementos.get(i);
char[] auxiliar = cadena.toCharArray();
for (int j = 0; j < auxiliar.length; j++) {
int posI = 0;
int posF = 0;
if (auxiliar[j] != ' ') {
if (auxiliar[j] == '"') {
posI = j + 1;
for (int k = posI + 1; k < auxiliar.length; k++) {
if (auxiliar[k] == '"') {
posF = k;
titulo = cadena.substring(posI, posF);
j = k + 1;
break;
}
}
} else if (auxiliar[j] == 'E' && auxiliar[j + 1] == 'N' && auxiliar[j + 2] == ':') {
posI = j + 4;
for (int l = posI; l < auxiliar.length; l++) {
if (auxiliar[l] == '1' || auxiliar[l] == '2') {
posF = l - 1;
lugar = cadena.substring(posI, posF);
j = l - 1;
break;
}
}
} else if ((auxiliar[j] == '1' || auxiliar[j] == '2')) {
posI = j;
for (int m = posI; m < auxiliar.length; m++) {
if (auxiliar[m] == 'E' && auxiliar[m + 1] == 'D' && auxiliar[m + 2] == ':') {
posF = m - 2;
anio = cadena.substring(posI, posF);
j = m - 1;
break;
}
}
} else if (auxiliar[j] == 'E' && auxiliar[j + 1] == 'D' && auxiliar[j + 2] == ':') {
posI = j + 3;
posF = cadena.length();
if (posI == posF) {
editorial = "N/D";
} else {
editorial = cadena.substring(posI, posF);
}
j = posF;
}
else {
posI = j;
for (int k = posI; k < auxiliar.length; k++) {
if (auxiliar[k] == '"') {
posF = k - 2;
autores = cadena.substring(posI, posF);
j = k - 1;
break;
}
}
}
}
}
libro.setAnio(anio);
libro.setAutores(autores);
libro.setEditorial(editorial);
libro.setLugar(lugar);
libro.setTitulo(titulo);
libroAux.add(libro);
investigador.setLibros(libroAux);
}
}
}
/**
* Este metodo filtra la informacion y la segmenta en su respectiva categoria
* para poder agregarla ordenadamente a las listas de cada uno de los
* investigadores
*
* @param elementos,
* Lista donde estan todos los proyectos en los que ha participado el
* investigador
* @param investigador,
* investigador al que se le a asignar la informacion
*/
public void extraerProyectos(ArrayList<String> elementos, Investigador investigador) {
int posI;
int posF;
String tipo = "";
String nombre = "";
String fecha = "";
ArrayList<Proyecto> proyectoAux = new ArrayList<>();
for (int i = 0; i < elementos.size(); i++) {
Proyecto proyecto = new Proyecto();
if (elementos.get(i).contains("TIPO DE PROYECTO:")) {
tipo = elementos.get(i + 1);
nombre = elementos.get(i + 2);
}
if (elementos.get(i).contains("INICIO:")) {
String cadena = elementos.get(i + 1);
char[] aux = cadena.toCharArray();
for (int j = 0; j < aux.length; j++) {
if (aux[j] == '2') {
posI = j;
posF = j + 4;
fecha = cadena.substring(posI, posF);
j = posF;
}
}
proyecto.setTipo(tipo);
proyecto.setNombre(nombre);
proyecto.setFecha(fecha);
proyectoAux.add(proyecto);
investigador.setProyectos(proyectoAux);
}
}
}
/**
* Metodo que elimina las etiquetas y caracteres especiales en la lista que
* tiene la estructura de la pagina web del cvlac de cada investigador
*
* @param elementos,
* lista que contiene la estructura textual de la pagina web
* @return Lista con la estructura de la pagina web sin las etiquetas y los
* caracteres especiales
*/
public ArrayList<String> limpiar(ArrayList<String> elementos) {
String temporal = "";
ArrayList<String> elementosLimpio = new ArrayList<>();
ArrayList<String> aux = new ArrayList<>();
ArrayList<String> aux2 = new ArrayList<>();
for (int i = 0; i < elementos.size(); i++) {
temporal = elementos.get(i).replaceAll("\n", "");
temporal = temporal.replaceAll(" ", " ");
temporal = temporal.replaceAll(" ", " ");
temporal = temporal.replaceAll("&", "&");
temporal = temporal.replaceAll("'", "");
}
char[] auxiliar = temporal.toCharArray();
int posI = 0;
int posF = 0;
for (int j = 0; j < auxiliar.length; j++) {
if (auxiliar[j] == '>') {
posI = j;
for (int i = j; i < auxiliar.length; i++) {
if (auxiliar[i] == '<') {
posF = i;
elementosLimpio.add(temporal.substring(posI, posF));
j = i;
break;
}
}
}
}
for (int i = 0; i < elementosLimpio.size(); i++) {
temporal = "";
temporal = elementosLimpio.get(i).replaceAll(">", " ");
aux.add(temporal);
}
for (int i = 0; i < aux.size(); i++) {
if (!aux.get(i).equalsIgnoreCase(" ")) {
temporal = "";
temporal = aux.get(i).substring(1);
aux2.add(temporal.trim());
}
}
aux.clear();
for (int i = 0; i < aux2.size(); i++) {
temporal = aux2.get(i);
if (!temporal.equalsIgnoreCase("")) {
aux.add(temporal.trim().toUpperCase());
}
}
elementosLimpio = aux;
// for (int i = 0; i < elementosLimpio.size(); i++) {
// System.out.println(elementosLimpio.get(i));
// }
return elementosLimpio;
}
/**
* Metodo que lee un archivo de texto y carga la lista con las url's de los
* investigadores
*/
public void leerDataSet() {
try {
urlSet = new ArrayList<String>();
String cadena;
FileReader f = new FileReader("src//main//java//datasets//DatasetCvLac.txt");
BufferedReader b = new BufferedReader(f);
while ((cadena = b.readLine()) != null) {
String url = "http://scienti.colciencias.gov.co:8081/cvlac/visualizador/generarCurriculoCv.do?cod_rh="
+ cadena;
urlSet.add(url);
}
b.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public List<Investigador> getInvestigadores() {
return investigadores;
}
}
| true
|
2bd6be62fc5703d4dd6b7d71c419898ce02ac1c7
|
Java
|
reaper1617/WorldWideLogisticsNew
|
/main/java/com/gerasimchuk/exceptions/driverexceptions/TooManyHoursWorkedForOrderException.java
|
UTF-8
| 642
| 2.84375
| 3
|
[] |
no_license
|
package com.gerasimchuk.exceptions.driverexceptions;
/**
* Too many hours worked for order Exception Class
*
* @author Reaper
* @version 1.0
*/
public class TooManyHoursWorkedForOrderException extends DriverException {
/**
* Instantiates a new Too many hours worked for order exception.
*/
public TooManyHoursWorkedForOrderException() {
super("Driver hours worked value is too big to execute order");
}
/**
* Instantiates a new Too many hours worked for order exception.
*
* @param s the s
*/
public TooManyHoursWorkedForOrderException(String s) {
super(s);
}
}
| true
|
1092e63ea320ad1b839d7d1fd5f4cd520e0a1773
|
Java
|
suwa-sh/rag
|
/src/rag-batch/src/test/java/jp/co/presa/ExampleItemReaderTests.java
|
UTF-8
| 422
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package jp.co.presa;
import junit.framework.TestCase;
import me.suwash.rag.ExampleItemReader;
public class ExampleItemReaderTests extends TestCase {
private ExampleItemReader reader = new ExampleItemReader();
public void testReadOnce() throws Exception {
assertEquals("Hello world!", reader.read());
}
public void testReadTwice() throws Exception {
reader.read();
assertEquals(null, reader.read());
}
}
| true
|
e5952b1b2464966080b5d633a1f868064c04c6f3
|
Java
|
EddyIonescu/SpaceWave
|
/src/Animate.java
|
UTF-8
| 290
| 2.25
| 2
|
[] |
no_license
|
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Animate implements ActionListener {
public void actionPerformed(ActionEvent e) {
Main.game.step();
Main.timer = new Timer(1000/Main.fps, new Animate());
}
}
| true
|
59ced1dbd245c6c1e7979aa30427c8d5185e82b0
|
Java
|
ukibs/FoodChain
|
/core/src/com/mygdx/game/RestaurantCode/ClientRestaurant.java
|
UTF-8
| 3,973
| 2.640625
| 3
|
[] |
no_license
|
package com.mygdx.game.RestaurantCode;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.mygdx.game.*;
/**
* Created by USUARIO on 07/05/2018.
*/
public class ClientRestaurant extends GameObject {
public Texture face;
float elapsedTime;
Restaurant restaurantLevel;
public int currentOrder;
public int numberOrders;
public int totalOrders;
ClientState clientState;
BitmapFont font;
public enum ClientState{
Ordering,
Eating,
Going
}
public ClientRestaurant(Restaurant restaurant, Vector2 position){
active = false;
this.dimension = Constants.dimension(1, 3.5f);
this.restaurantLevel = restaurant;
this.position = position;
font = new BitmapFont();
face = com.mygdx.game.Singletons.Assets.getInstance().clients[MathUtils.random(0,3)];
}
public void init(int numOrders)
{
clientState = ClientState.Ordering;
active = true;
numberOrders = numOrders;
totalOrders = numberOrders;
currentOrder = MathUtils.random(0, 3);
}
@Override
public void render(SpriteBatch batch) {
if(!active)
return;
//
batch.draw(com.mygdx.game.Singletons.Assets.getInstance().think, position.x, position.y+Constants.HEIGHT_RATIO*2.8f, dimension.x, dimension.y/2f);
//
batch.draw(face, position.x, position.y, dimension.x, dimension.y);
switch (clientState)
{
case Ordering:
batch.draw(com.mygdx.game.Singletons.Assets.getInstance().food[currentOrder], position.x+Constants.WIDTH_RATIO*0.35f, position.y+Constants.HEIGHT_RATIO*3.5f, dimension.x/3, dimension.y/5f);
break;
case Eating:
break;
case Going:
batch.draw(com.mygdx.game.Singletons.Assets.getInstance().food[4], position.x+Constants.WIDTH_RATIO*0.35f, position.y+Constants.HEIGHT_RATIO*3.3f, dimension.x/3, dimension.y/3.3f);
break;
}
}
@Override
public void update(float elpasedTime) {
if(!active)
return;
//
this.elapsedTime += elpasedTime;
switch (clientState)
{
case Ordering:
if(elapsedTime > 7)
{
goOut();
}
break;
case Eating:
if(elapsedTime > 3)
{
elapsedTime = 0;
if(numberOrders == 0)
{
clientState = ClientState.Going;
}
else clientState = ClientState.Ordering;
}
break;
case Going:
if(elapsedTime > 2)
{
goOut();
}
}
}
//
public void takeOrder()
{
if(numberOrders > 1) {
currentOrder = MathUtils.random(0, 3);
numberOrders--;
clientState = ClientState.Eating;
}
else if(numberOrders == 1)
{
numberOrders--;
currentOrder = 4;
clientState = ClientState.Eating;
}
else
{
active = false;
com.mygdx.game.Singletons.SoundManager.getInstance().play(com.mygdx.game.Singletons.SoundManager.getFruit);
}
}
private int getOrdersDone()
{
return totalOrders - numberOrders;
}
private void goOut()
{
restaurantLevel.wastedFood(getOrdersDone());
active = false;
elapsedTime = 0;
com.mygdx.game.Singletons.SoundManager.getInstance().play(com.mygdx.game.Singletons.SoundManager.angry);
}
}
| true
|
e8054c69ef83f7ca4775400cdd5fdbbf185b67e1
|
Java
|
liujie0813/TChat
|
/chat-server/src/main/java/com/timberliu/chat/server/dao/mysql/entity/AuthAccessTokenEntity.java
|
UTF-8
| 1,165
| 1.953125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.timberliu.chat.server.dao.mysql.entity;
import com.timberliu.chat.server.dao.BaseEntity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.util.Date;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 访问令牌表
* </p>
*
* @author liujie
* @since 2021-09-24
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("auth_access_token")
@Accessors(chain = true)
public class AuthAccessTokenEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 用户Id
*/
private Long userId;
/**
* 访问令牌
*/
private String accessToken;
/**
* 刷新令牌
*/
private String refreshToken;
/**
* 过期时间
*/
private Date expireTime;
/**
* 创建IP
*/
private String createIp;
/**
* 是否删除
*/
private Integer deleted;
}
| true
|
6393db54a927f9e91af9c3203620fc361b94e180
|
Java
|
Alex-ZHOU/VMServer
|
/src/entities/Login.java
|
UTF-8
| 936
| 2.625
| 3
|
[] |
no_license
|
package entities;
public class Login {
/**
* 用户信息
*/
private User User = new User();
/**
* 返回的数据
*/
private String Return;
public User getUser() {
return User;
}
public void setUser(User user) {
User = user;
}
public String getReturn() {
return Return;
}
public void setReturn(String return1) {
Return = return1;
}
public class User {
/**
* 账户名
*/
private String UserName;
/**
* 密码
*/
private String Password;
/**
* 用户id号
*/
private int UserId;
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public int getUserId() {
return UserId;
}
public void setUserId(int userId) {
this.UserId = userId;
}
}
}
| true
|
f1355d11c4bf16fbc93a258a1df9bd827aaa3475
|
Java
|
mariollori/chatwebback
|
/src/main/java/proyect/controllers/ChatController.java
|
UTF-8
| 1,853
| 2.421875
| 2
|
[] |
no_license
|
package proyect.controllers;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import proyect.Service.ChatServImp;
import proyect.models.Mensaje;
@Controller
public class ChatController {
@Autowired
private ChatServImp chas;
@Autowired
private SimpMessagingTemplate simp;
private String[] colores= {"red","green","blue","magenta","purple","orange","yellow"};
@MessageMapping("/mensaje")
/*aca si se agrega el prefijo*/
@SendTo("/chat/mensaje")
public Mensaje recibirMensaje(Mensaje mensaje) {
mensaje.setFecha(new Date().getTime());
switch (mensaje.getTipo()) {
case "USERNAME":
mensaje.setColor(colores[new Random().nextInt(colores.length)]);
mensaje.setTexto("nuevo usuario");
break;
case "MENSAJE":
chas.save(mensaje);
break;
case "DESCONECTADO":
mensaje.setColor("red");
break;
default:
System.out.println("F");
break;
}
return mensaje;
}
@MessageMapping("/escribiendo")
/*aca si se agrega el prefijo*/
@SendTo("/chat/escribiendo")
public String verescrib(String username) {
return username.concat("esta escribiendo....");
}
@MessageMapping("/historial")
/*Ya que necesitamos enviar una variable por la ruta utilizaremos
* otra clase de websocket, ya que sendto no nos permite
* personalizar la ruta*/
public void historial(String ClienteId){
/*y asi recibimos la id por la ruta y esta envia el resultado*/
simp.convertAndSend("/chat/historial/" + ClienteId ,chas.findLastMessajes());
}
}
| true
|
b9a46643e73dfc427a18df37b34b0ccf7d4b35f2
|
Java
|
sichengde/sygd-3.0
|
/sygd-core/src/main/java/com/sygdsoft/controller/PointOfSaleController.java
|
UTF-8
| 1,935
| 2.09375
| 2
|
[] |
no_license
|
package com.sygdsoft.controller;
import com.sygdsoft.jsonModel.CookHelper;
import com.sygdsoft.jsonModel.Query;
import com.sygdsoft.model.PointOfSale;
import com.sygdsoft.service.PointOfSaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Created by 舒展 on 2016-05-19.
*/
@RestController
public class PointOfSaleController {
@Autowired
PointOfSaleService pointOfSaleService;
@RequestMapping(value = "pointOfSaleGet")
public List<PointOfSale> pointOfSaleGetAllSecond(@RequestBody Query query) throws Exception {
return pointOfSaleService.get(query);
}
@RequestMapping(value = "pointOfSaleDelete")
@Transactional(rollbackFor = Exception.class)
public void pointOfSaleDelete(@RequestBody List<PointOfSale> pointOfSaleList) throws Exception {
pointOfSaleService.delete(pointOfSaleList);
}
@RequestMapping(value = "pointOfSaleAdd")
public void pointOfSaleAdd(@RequestBody PointOfSale pointOfSale) throws Exception {
pointOfSaleService.add(pointOfSale);
}
@RequestMapping(value = "pointOfSaleUpdate")
@Transactional(rollbackFor = Exception.class)
public void pointOfSaleUpdate(@RequestBody List<PointOfSale> pointOfSaleList) throws Exception {
if (pointOfSaleList.size() > 1) {
if (pointOfSaleList.get(0).getId().equals(pointOfSaleList.get(pointOfSaleList.size() / 2).getId())) {
pointOfSaleService.update(pointOfSaleList.subList(0, pointOfSaleList.size() / 2));
return;
}
}
pointOfSaleService.update(pointOfSaleList);
}
@RequestMapping(value = "getRoomPointOfSaleList")
public List<String> getRoomPointOfSaleList(){
return pointOfSaleService.getRoomPointOfSaleList();
}
}
| true
|
2a2cc8d6eef3d28c73ea4dce2da1c4c8b8e8ef8c
|
Java
|
frankhuiatappcara/tomcatdemo
|
/hello/src/test/java/net/appcara/example/Test1.java
|
UTF-8
| 219
| 1.765625
| 2
|
[] |
no_license
|
package net.appcara.example;
import junit.framework.Assert;
import org.junit.Test;
public class Test1 {
@Test
public void testHelloWorld() {
Assert.assertEquals("Hello World", "Hello World");
}
}
| true
|
3514aaaae1527a3dd16565b346d869ac95bd83b2
|
Java
|
WilderGao/leetcode
|
/src/贪婪算法/GenerateParenthesis.java
|
UTF-8
| 1,268
| 3.9375
| 4
|
[] |
no_license
|
package 贪婪算法;
import java.util.LinkedList;
import java.util.List;
/**
* @author wilder
* @date 19-2-2 下午4:20
* description leetcode 22
* 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
* <p>
* 例如,给出 n = 3,生成结果为:
* <p>
* [
* "((()))",
* "(()())",
* "(())()",
* "()(())",
* "()()()"
* ]
*/
public class GenerateParenthesis {
private List<String> solution(int n) {
if (n <= 0) return null;
List<String> result = new LinkedList<>();
String s = "";
helper(n, n, result, s);
return result;
}
private void helper(int left, int right, List<String> result, String s) {
//不能出现右括号比左括号多的情况,这样不符合情况
if (left < 0 || right < 0 || left > right) {
return;
}
if (left == 0 && right == 0) {
result.add(s);
} else {
if (left > 0) helper(left - 1, right, result, s + "(");
if (right > 0) helper(left, right - 1, result, s + ")");
}
}
public static void main(String[] args) {
System.out.println(new GenerateParenthesis().solution(3));
}
}
| true
|
cdcf1d761ac4f3f6c04909dce2e821b79dd946b0
|
Java
|
adamIqbal/Health
|
/health/src/main/java/com/health/gui/script/ScriptPanelSidebar.java
|
UTF-8
| 899
| 2.484375
| 2
|
[
"MIT"
] |
permissive
|
package com.health.gui.script;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
public class ScriptPanelSidebar extends JPanel {
/**
* Constant serialized ID used for compatibility.
*/
private static final long serialVersionUID = 3261823517410374339L;
private static JProgressBar progress = new JProgressBar();
private static JLabel label = new JLabel("");
public ScriptPanelSidebar() {
super();
this.setLayout(new GridLayout(2,1));
progress.setIndeterminate(true);
progress.setVisible(false);
this.add(label);
this.add(progress);
}
public static void toggleProgress() {
if(progress.isVisible()) {
progress.setVisible(false);
label.setText("");
}
else {
progress.setVisible(true);
label.setText("Analysis is running. Please wait..");
}
}
}
| true
|
6428fc1b4a385512a016654c8acd80b49a48955f
|
Java
|
hrithiksrinivas/Sprint-HotelBookingManagementSystem-Gradle
|
/sprint.hbms/src/main/java/com/cap/sprint/hbms/services/PaymentsServicesImpl.java
|
UTF-8
| 1,228
| 2.203125
| 2
|
[] |
no_license
|
package com.cap.sprint.hbms.services;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cap.sprint.hbms.entities.BookingDetails;
import com.cap.sprint.hbms.entities.Hotel;
import com.cap.sprint.hbms.entities.Payments;
import com.cap.sprint.hbms.entities.RoomDetails;
import com.cap.sprint.hbms.repos.IPaymentsRepository;
import com.cap.sprint.hbms.services_interfaces.IPaymentsService;
@Service
public class PaymentsServicesImpl implements IPaymentsService
{
@Autowired
IPaymentsRepository paymentRepository;
@Autowired
BookingDetailsServicesImpl bookingDetailsServicesImpl;
@Transactional
public Payments addPayment(Payments payment)
{
Optional <BookingDetails> bd= bookingDetailsServicesImpl.viewBookingDetails(payment.getBookingDetails().getBookingId());
payment.setBookingDetails(bd.get());
paymentRepository.save(payment);
return payment;
}
public Optional<Payments> viewPayments(int paymentId)
{
Optional<Payments> payments = paymentRepository.findById(paymentId);
return payments;
}
}
| true
|
bed6899e9b13bff6b1a38b769f229b86d795d118
|
Java
|
00mjk/cto-spring-webflux-training
|
/webflux-server/src/main/java/com/telefonica/training/webflux/server/exceptions/ResponseException.java
|
UTF-8
| 1,082
| 2.265625
| 2
|
[] |
no_license
|
/*
* Copyright (c) Telefonica I+D. All rights reserved.
*/
package com.telefonica.training.webflux.server.exceptions;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class ResponseException extends RuntimeException {
private static final long serialVersionUID = -7053061576358356336L;
private final HttpStatus status;
private final String error;
private final String reason;
private final HttpHeaders headers;
public ResponseException(HttpStatus status) {
this(status, null, null);
}
public ResponseException(HttpStatus status, String error, String reason) {
this(status, error, reason, null);
}
public ResponseException(HttpStatus status, String error, String reason, Throwable t) {
super(t);
this.status = status;
this.error = error;
this.reason = reason;
this.headers = new HttpHeaders();
}
public void addHeader(String headerName, String headerValue) {
headers.add(headerName, headerValue);
}
}
| true
|
1ab2f2ca67e90e42a07de0e44311c4db1e433207
|
Java
|
anish-kapuskar/cloud_webapp
|
/src/main/java/com/me/controllers/uploads3controller.java
|
UTF-8
| 3,444
| 2.359375
| 2
|
[] |
no_license
|
package com.me.controllers;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class uploads3controller {
@Autowired
private AmazonS3 s3client;
@Value("http://webapp.anish.kapuskar.s3-website-us-east-1.amazonaws.com")
private String endpointUrl;
@Value("webapp.anish.kapuskar")
private String bucketName;
@RequestMapping(value = "uploads3controller.htm", method = RequestMethod.POST)
public String uploadFile(@RequestParam("file") MultipartFile multipartFile,
HttpServletRequest request, HttpServletResponse response) throws IOException {
String fileUrl = "";
String status = null;
//converting multipart file to file
File file = convertMultiPartToFile(multipartFile);
//filename
String fileName = multipartFile.getOriginalFilename();
fileUrl = endpointUrl + "/" + bucketName + "/" + fileName;
status = uploadFileTos3bucket(fileName, file);
file.delete();
return "SellBooks";
}
/* @PostMapping("addBooks.htm")
public String uploadFile(@RequestPart(value = "file") MultipartFile multipartFile) {
String fileUrl = "";
String status = null;
try {
//converting multipart file to file
File file = convertMultiPartToFile(multipartFile);
//filename
String fileName = multipartFile.getOriginalFilename();
fileUrl = endpointUrl + "/" + bucketName + "/" + fileName;
status = uploadFileTos3bucket(fileName, file);
file.delete();
} catch (Exception e) {
return "UploadController().uploadFile().Exception : " + e.getMessage();
}
return status + " " + fileUrl;
}*/
private File convertMultiPartToFile(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}
private String uploadFileTos3bucket(String fileName, File file) {
try {
s3client.putObject(new PutObjectRequest(bucketName, fileName, file).withCannedAcl(CannedAccessControlList.PublicRead));
}catch(AmazonServiceException e) {
return "uploadFileTos3bucket().Uploading failed :" + e.getMessage();
}
return "SellBooks";
}
public void deleteFile(final String fileName) {
final DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, fileName);
s3client.deleteObject(deleteObjectRequest);
}
}
| true
|
14be062741e42db6c28e9510a5a02d2af284b395
|
Java
|
DamianNowakk/pamietaj-wyrzuc.to
|
/app/src/main/java/pl/mod3city/powiadomienia/wyrzucto/fragments/GlownyFragment.java
|
UTF-8
| 864
| 1.796875
| 2
|
[] |
no_license
|
package pl.mod3city.powiadomienia.wyrzucto.fragments;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import pl.mod3city.powiadomienia.wyrzucto.api.JSONParser;
import pl.mod3city.powiadomienia.wyrzucto.R;
import pl.mod3city.powiadomienia.wyrzucto.res.rodzajSmieci;
public class GlownyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.content_main,container,false);
JSONParser.getInstance().wyswietlanieDni(getContext(), rootView);
return rootView;
}
}
| true
|
d43637389cd21172f934783487dd2a7bce68a9c8
|
Java
|
cgb-extjs-gwt/avgust-extjs-generator
|
/Trabajos/Cibertec/Dawii/Sources/AcmeUtil/src/main/java/com/acme/util/HibernateRepositoryHelper.java
|
UTF-8
| 2,131
| 2.578125
| 3
|
[] |
no_license
|
package com.acme.util;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
public abstract class HibernateRepositoryHelper <T, K extends Serializable> implements IHibernateRepositoryHelper<T, K>{
@PersistenceContext
private EntityManager entityManager;
private Class<T> entityClass;
private T t;
public HibernateRepositoryHelper() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.setEntityClass((Class<T>) genericSuperclass.getActualTypeArguments()[0]);
}
private T getT(){
return t;
}
public EntityManager getEntityManager() {
return this.entityManager;
}
@Override
public void create(T record) throws Exception {
this.entityManager.persist(record);
}
@Override
public void createAll(List<T> list) throws Exception {
for(T record : list ){
this.entityManager.persist(record);
}
}
@Override
public T get(K id) throws Exception {
return this.entityManager.find(getEntityClass(), id);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public List<T> getAll() throws Exception {
CriteriaQuery cq = this.entityManager.getCriteriaBuilder().createQuery();
cq.select(cq.from(getEntityClass()));
return this.entityManager.createQuery(cq).getResultList();
}
@Override
public void update(T record) throws Exception {
this.entityManager.merge(record);
}
@Override
public void updateAll(List<T> list) throws Exception {
for(T record : list ){
this.entityManager.merge(record);
}
}
@Override
public void delete(T record) throws Exception {
this.entityManager.remove(this.entityManager.merge(record));
}
@Override
public void deleteAll(List<T> list) throws Exception {
for(T record : list ){
this.entityManager.remove(record);
}
}
public Class<T> getEntityClass() {
return entityClass;
}
public void setEntityClass(Class<T> entityClass) {
this.entityClass = entityClass;
}
}
| true
|
740cb1cc8ecc678fb4f2452b16e6fb2408b87c5d
|
Java
|
mhsharafi/Census-Management-System
|
/src/ExcelReader.java
|
UTF-8
| 11,669
| 2.640625
| 3
|
[] |
no_license
|
/**
* Created by mohammad hosein on 21/02/2016.
*/
import com.aspose.cells.SaveFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.charts.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.SystemOutLogger;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class ExcelReader {
private XSSFWorkbook workbook;
// private FormulaEvaluator evaluator;
private String address;
private XSSFSheet e;
private File ex = null;
private HashMap<Integer, Integer> year2Col;
public ExcelReader(String address) {
try {
this.address = address;
ex = new File(address);
FileInputStream fileinput = new FileInputStream(ex);
this.workbook = new XSSFWorkbook(fileinput);
} catch (Exception var4) {
System.out.println("ERROR!");
// var4.printStackTrace();
}
createYearIndex();
}
private void createYearIndex() {
ArrayList<Cell> data = new ArrayList<>();
try {
XSSFSheet e = this.workbook.getSheetAt(0);
//this.evaluator = this.workbook.getCreationHelper().createFormulaEvaluator();
Iterator rowIterator = e.iterator();
//skip invalid first rows
for (int i = 0; i < 16; i++) {
rowIterator.next();
}
Row years = (Row) rowIterator.next();
Iterator yearCells = years.iterator();
//skip invalid first columns
for (int i = 0; i < 5; i++) {
yearCells.next();
}
year2Col = new HashMap<>();
while (yearCells.hasNext()) {
Cell c = (Cell) yearCells.next();
int year = getIntValue(c);
year2Col.put(year, c.getColumnIndex());
}
} catch (Exception var15) {
}
// projectNameCellIterator.next();
// projectCodeCellIterator.next();
// ArrayList projectsCode = new ArrayList();
//
// try {
// while(projectCodeCellIterator.hasNext()) {
// Cell row = (Cell)projectCodeCellIterator.next();
// Cell cellIterator = (Cell)projectNameCellIterator.next();
// switch(row.getCellType()) {
// case 0:
// projectsCode.add((new Integer((int)row.getNumericCellValue())).toString());
// break;
// case 1:
// projectsCode.add(row.getStringCellValue());
// break;
// case 2:
// projectsCode.add(this.evaluator.evaluate(row).getStringValue());
// }
//
// switch(cellIterator.getCellType()) {
// case 0:
// data.addProject((new Double(cellIterator.getNumericCellValue())).toString(), (String)projectsCode.get(projectsCode.size() - 1));
// break;
// case 1:
// data.addProject(cellIterator.getStringCellValue(), (String)projectsCode.get(projectsCode.size() - 1));
// break;
// case 2:
// data.addProject(this.evaluator.evaluate(cellIterator).getStringValue(), (String)projectsCode.get(projectsCode.size() - 1));
// }
//
// if(row.getColumnIndex() != cellIterator.getColumnIndex()) {
// if(row.getColumnIndex() < cellIterator.getColumnIndex()) {
// Program.error.append("??? ????? ?? ?? ").append((String)projectsCode.get(projectsCode.size() - 1)).append(" ???? ?????.").append("\n");
// } else {
// switch(cellIterator.getCellType()) {
// case 0:
// Program.error.append("?? ????? ?? ??? ").append((new Double(cellIterator.getNumericCellValue())).toString()).append(" ???? ?????.").append("\n");
// break;
// case 1:
// Program.error.append("?? ????? ?? ??? ").append(cellIterator.getStringCellValue()).append(" ???? ?????.").append("\n");
// break;
// case 2:
// Program.error.append("?? ????? ?? ??? ").append(this.evaluator.evaluate(cellIterator).getStringValue()).append(" ???? ?????.").append("\n");
// }
// }
// }
// }
// } catch (NoSuchElementException var14) {
// Program.error.append("?? ??? ?? ?? ????? ?? ????? ???? ???? ?? ???? : \n" + this.address + "\n???? ????? ????? ? ?????? ?????? ????.").append("\n");
// }
//
// while(true) {
// Cell personCell;
// String name;
// Iterator cellIterator1;
// do {
// do {
// do {
// if(!rowIterator.hasNext()) {
// if(data.persons.size() == 0) {
// Program.error.append("??? 2 ???? " + this.address + " ???? ??????? ????? ????.").append("\n");
// }
//
// return data;
// }
//
// Row row1 = (Row)rowIterator.next();
// cellIterator1 = row1.cellIterator();
// personCell = (Cell)cellIterator1.next();
// } while(!cellIterator1.hasNext());
//
// personCell = (Cell)cellIterator1.next();
// name = personCell.getStringCellValue();
// } while(name.equals(""));
// } while(personCell.getColumnIndex() != 1);
//
// data.addName(name);
//
// while(cellIterator1.hasNext()) {
// Cell cell = (Cell)cellIterator1.next();
// if(cell.getColumnIndex() - 2 != projectsCode.size()) {
// if(cell.getCellType() == 0) {
// data.addMin((String)projectsCode.get(cell.getColumnIndex() - 2), personCell.getStringCellValue(), Double.valueOf(cell.getNumericCellValue()));
// } else if(cell.getCellType() == 2) {
// data.addMin((String)projectsCode.get(cell.getColumnIndex() - 2), personCell.getStringCellValue(), Double.valueOf(this.evaluator.evaluate(cell).getNumberValue()));
// }
// }
// }
// }
//return null;
}
public void createChart(String country) {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet 1");
final int NUM_OF_ROWS = 2;
final int NUM_OF_COLUMNS = year2Col.size();
// Create a row and put some cells in it. Rows are 0 based.
Row row;
Cell cell;
for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
row = sheet.createRow((short) rowIndex);
switch (rowIndex) {
case 0:
for (Integer i : year2Col.keySet()) {
cell = row.createCell(year2Col.get(i) - 5);
cell.setCellValue(getPopulation(country, i));
}
break;
case 1:
for (Integer i : year2Col.keySet()) {
cell = row.createCell(year2Col.get(i) - 5);
cell.setCellValue(i);
}
}
}
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 20);
Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend();
legend.setPosition(LegendPosition.TOP_RIGHT);
ScatterChartData data = chart.getChartDataFactory().createScatterChartData();
ValueAxis bottomAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM);
ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));
for (int i = 0; i < NUM_OF_COLUMNS; i++) {
sheet.autoSizeColumn(i);
}
data.addSerie(xs, ys1);
data.addSerie(xs, ys2);
chart.plot(data, bottomAxis, leftAxis);
// Write the output to a file
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream("Data/chart-year.xlsx");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public int getPopulation(String country, int year) {
Cell cell = findCell(country, year, 0);
if (cell != null)
return (int) (getDoubleValue(cell) * 1000);
return 0;
}
private double getDoubleValue(Cell c) {
switch (c.getCellType()) {
case 0:
return c.getNumericCellValue();
case 1:
return Double.parseDouble(c.getStringCellValue());
}
return 0;
}
private int getIntValue(Cell c) {
switch (c.getCellType()) {
case 0:
return (int) c.getNumericCellValue();
case 1:
return Integer.parseInt(c.getStringCellValue());
}
return 0;
}
private Cell findCell(String country, int year, int sheetNumber) {
XSSFSheet e = this.workbook.getSheetAt(sheetNumber);
Iterator rowIterator = e.iterator();
while (rowIterator.hasNext()) {
try {
Row r = (Row) rowIterator.next();
Cell c = r.getCell(2);
if (c.getStringCellValue().equals(country)) {
Cell res = r.getCell(year2Col.get(year));
return res;
}
} catch (Exception ee) {
}
}
return null;
}
public void setPopulation(String country, int year, double population) {
Cell cell = findCell(country, year, 0);
if (cell != null) {
cell.setCellValue(population);
try {
FileOutputStream fos = new FileOutputStream(ex);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
| true
|
fdbe0149a2e99f38d020951d73ecf48ae165a14e
|
Java
|
fifty56/vistadmin
|
/webapp/src/main/java/org/vist/vistadmin/reporting/VistReportException.java
|
UTF-8
| 335
| 2.125
| 2
|
[] |
no_license
|
package org.vist.vistadmin.reporting;
public class VistReportException extends Exception {
private String messageKey;
public String getMessageKey() {
return messageKey;
}
public void setMessageKey(String messageKey) {
this.messageKey = messageKey;
}
public VistReportException(String key) {
messageKey = key;
}
}
| true
|
4c05eae0bc6223fe2096150dcb07ae00fa4196de
|
Java
|
bennettdr/lensclient
|
/src/client/lensmoor/com/EnumSpecialization.java
|
UTF-8
| 2,175
| 2.703125
| 3
|
[] |
no_license
|
package client.lensmoor.com;
public enum EnumSpecialization {
WEAPONMASTER (1, "weaponmaster", EnumAttribute.STRENGTH),
HEALING (2, "healing", EnumAttribute.CHARISMA),
ILLUSIONS (3, "illusions", EnumAttribute.CHARISMA),
NECROMANCY (4,"necromancy", EnumAttribute.CONSTITUTION),
THIEVING (5, "thieving", EnumAttribute.DEXTERITY),
ENCHANTING (6, "enchanting", EnumAttribute.INTELLIGENCE),
ASSASSINATION (7, "assassination", EnumAttribute.DEXTERITY),
SORCERY (8, "sorcery", EnumAttribute.INTELLIGENCE),
PROTECTION(9, "protection", EnumAttribute.WISDOM),
CONJURER(10, "conjurer", EnumAttribute.INTELLIGENCE),
DIVINING(11, "divining", EnumAttribute.INTELLIGENCE),
BARBARISM(12, "barbarism", EnumAttribute.STRENGTH),
MAGIC (13, "magic", EnumAttribute.INTELLIGENCE),
PSIONICS(14, "psionics", EnumAttribute.WISDOM),
DRUID (15, "druid", EnumAttribute.WISDOM),
BARD (16, "bard", EnumAttribute.CHARISMA),
CRAFTER (17, "crafter", EnumAttribute.CONSTITUTION),
WITCHCRAFT (18, "witchcraft", EnumAttribute.CHARISMA),
PALADIN (19, "paladin", EnumAttribute.STRENGTH),
ANIMAL (20, "animal", EnumAttribute.CONSTITUTION),
GLAMOUR (21, "glamour", EnumAttribute.CHARISMA),
NONE (0, "none", EnumAttribute.SIZEOF),
ALL (-1, "all", EnumAttribute.WISDOM);
private int value;
private String string;
private EnumAttribute attribute;
private EnumSpecialization (int value, String string, EnumAttribute attribute) {
this.value = value;
this.string = string;
this.attribute = attribute;
}
public int getInt() {
return (value);
}
public String getString() {
return (string);
}
public EnumAttribute getStat() {
return (attribute);
}
public static EnumSpecialization getSpecialization(String string) {
for (EnumSpecialization current : values()) {
if(current.getString().equalsIgnoreCase(string)) {
return current;
}
}
return EnumSpecialization.NONE;
}
public static EnumSpecialization getSpecialization(int value) {
for (EnumSpecialization current : values()) {
if(current.getInt() == value) {
return current;
}
}
return EnumSpecialization.NONE;
}
}
| true
|
6ddd9eeb9f5aaf1da2803de8c038ca48beec777a
|
Java
|
OlderG/springcloud-nacos
|
/nacosCloud-consumer/src/main/java/com/example/nacoscloudconsumer/controller/FeignNacosController.java
|
UTF-8
| 1,013
| 1.90625
| 2
|
[] |
no_license
|
package com.example.nacoscloudconsumer.controller;
import com.example.nacoscloudconsumer.client.FeignNacosCloud;
import com.example.nacoscloudprovide.client.FeignNacosCloudProvide;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author gyingfei
* @date 2021/11/11
*/
@RestController
public class FeignNacosController {
@Autowired
private FeignNacosCloud feignNacosCloud;
@Autowired
private RestTemplate restTemplate;
@GetMapping(value = "/service")
public String service(){
return feignNacosCloud.get();
}
@GetMapping(value = "/test/{string}")
public String get(@PathVariable String string){
return restTemplate.getForObject("http://nacos-cloud-provide/login/get/"+string,String.class);
}
}
| true
|
7419d26bd920c75a1be7c2df3c9e8b46451b9062
|
Java
|
Ariful0007/PDF_Project
|
/app/src/main/java/com/example/pdf_project/admin_panel/Add_User.java
|
UTF-8
| 10,965
| 1.742188
| 2
|
[] |
no_license
|
package com.example.pdf_project.admin_panel;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.pdf_project.Client_SMS.Client_SMS;
import com.example.pdf_project.Give_License;
import com.example.pdf_project.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.kaopiz.kprogresshud.KProgressHUD;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Add_User extends AppCompatActivity {
EditText username_added,phone_added,email_add;
TextView date_picker;
Button addEd;
FirebaseFirestore firebaseFirestore;
DocumentReference documentReference;
FirebaseAuth firebaseAuth;
String url;
KProgressHUD progressHUD;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__user);
firebaseAuth=FirebaseAuth.getInstance();
firebaseFirestore=FirebaseFirestore.getInstance();
username_added=findViewById(R.id.username_added);
phone_added=findViewById(R.id.phone_added);
email_add=findViewById(R.id.email_add);
date_picker=findViewById(R.id.date_picker);
addEd=findViewById(R.id.addEd);
Calendar calendar=Calendar.getInstance();
String current= DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
String current1= DateFormat.getDateInstance().format(calendar.getTime());
date_picker.setText(current);
progressHUD=KProgressHUD.create(Add_User.this);
addEd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String name,address,phobe,email;
name=username_added.getText().toString().toLowerCase().trim();
address=phone_added.getText().toString().toLowerCase().trim();
phobe=email_add.getText().toString().toLowerCase().trim();
email=date_picker.getText().toString().toLowerCase().trim();
Random myRandom = new Random();
final String randomkey=String.valueOf(myRandom.nextInt(100000));
url=randomkey;
if (TextUtils.isEmpty(name)||TextUtils.isEmpty(address)
||TextUtils.isEmpty(phobe)||TextUtils.isEmpty(email)) {
Toast.makeText(Add_User.this, "Fill up all fields", Toast.LENGTH_SHORT).show();
return;
}
else {
progress_check();
//textSend_user();
firebaseAuth.createUserWithEmailAndPassword(phobe,"123456")
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
textSend_user();
store_information1(name,address,phobe,email,randomkey);
store_information2(name,address,phobe,email,randomkey);
store_information(name,address,phobe,email,randomkey);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressHUD.dismiss();
Toast.makeText(Add_User.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
private void store_information2(String name,
String address, String phobe,
String email, String randomkey) {
/* Map<String, Object> user = new HashMap<>();
user.put("name", name);
user.put("address", address);
user.put("phobe", phobe);
user.put("email", email);
user.put("randomkey",randomkey);*/
User_model user_model=new User_model(name,phobe,email,randomkey);
// Add a new document with a generated ID
firebaseFirestore.collection("Profile")
.document(phobe)
.set(user_model)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
//progressHUD.dismiss();
textSend_user();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//Log.w(TAG, "Error adding document", e);
progressHUD.dismiss();
Toast.makeText(Add_User.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void store_information1(String name,
String address, String phobe,
String email, String randomkey) {
/* Map<String, Object> user = new HashMap<>();
user.put("name", name);
user.put("address", address);
user.put("phobe", phobe);
user.put("email", email);
user.put("randomkey",randomkey);*/
User_model user_model=new User_model(name,phobe,email,randomkey);
// Add a new document with a generated ID
firebaseFirestore.collection("users")
.document(randomkey)
.set(user_model)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
//progressHUD.dismiss();
textSend_user();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//Log.w(TAG, "Error adding document", e);
progressHUD.dismiss();
Toast.makeText(Add_User.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void store_information(String name,
String address, String phobe,
String email, String randomkey) {
/*Map<String, Object> user = new HashMap<>();
user.put("name", name);
user.put("address", address);
user.put("phobe", phobe);
user.put("email", email);
user.put("randomkey",randomkey);*/
User_model user_model=new User_model(name,phobe,email,randomkey);
// Add a new document with a generated ID
firebaseFirestore.collection("Temporary")
.document(randomkey)
.set(user_model)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
progressHUD.dismiss();
Toast.makeText(Add_User.this, "Account Activated", Toast.LENGTH_SHORT).show();
textSend_user();
startActivity(new Intent(getApplicationContext(),Admin_panel.class));
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//Log.w(TAG, "Error adding document", e);
progressHUD.dismiss();
Toast.makeText(Add_User.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void textSend_user() {
int permission= ContextCompat.checkSelfPermission(Add_User.this, Manifest.permission.SEND_SMS);
if (permission== PackageManager.PERMISSION_GRANTED) {
sending();
}
else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},0);
}
}
private void sending() {
String phone_number1233=phone_added.getText().toString();
String sm333s="Your Accout Actived"+"\nYour License key is : "+url+"\nThank You.";
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage(phone_number1233,null,sm333s,null,null);
Toast.makeText(this, "Message Sent", Toast.LENGTH_SHORT).show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case 0:
if (grantResults.length>=0 && grantResults[0]==PackageManager.PERMISSION_GRANTED) {
sending();;
}
else {
Toast.makeText(this, "Don't Have permission", Toast.LENGTH_SHORT).show();
}
break;
}
}
private void progress_check() {
progressHUD.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel("Please wait")
.setCancellable(false)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
}
}
| true
|
42129049a6e4b22b37bff40ca930d6dfa2af5f39
|
Java
|
flubacheski/AlgProgII
|
/Aula01/testaInterseccao/src/testainterseccao/testeInterseccao.java
|
UTF-8
| 937
| 3.5625
| 4
|
[] |
no_license
|
package testainterseccao;
/**
*
* @author fabio
*/
public class testeInterseccao {
public static void main(String[] args) {
int A[] = { 7, 2, 5, 8, 4};
int B[]= {4, 2, 9, 5};
System.out.println("resposta da interseccao = "+interseccao(A,B));
}
public static String interseccao( int A[], int B[]){
String resp = "";
// 1 - Para cada elemento do vetor A[] – andar nas posições do vetor A[] (for ou while)
for( int i = 0; i < A.length; i++ ){
// 2 - olhar se o elemento de A[] consta no vetor B[],
// para um elemento de A[] verificar todos os elementos de B[]
for( int j=0; j < B.length; j++){
// 3 - se constar o elemento de A[] no vetor B[]
// fará parte da resposta.
if( A[i] == B[j])
resp = resp + " "+A[i];
}
}
return resp;
}
}
| true
|
a6b779ef9be6e30038400aed73c506e6c775fcdc
|
Java
|
Wolfik-cloud/Yammi-1.8.8
|
/ru/yammi/module/movement/Fly.java
|
UTF-8
| 1,503
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
package ru.yammi.module.movement;
import ru.yammi.event.EventTarget;
import ru.yammi.event.events.TickEvent;
import ru.yammi.event.events.UpdateEvent;
import ru.yammi.module.Category;
import ru.yammi.module.Module;
import ru.yammi.module.option.Option;
public class Fly extends Module {
public Fly(){
super("Fly", Category.Movement, "Become a God! You can fly!");
this.getOptions().add(new Option("Speed", 0, 10));
this.getOptions().add(new Option("Vanilla fly" ));
}
@Override
public void onDisable() {
this.mc.thePlayer.capabilities.isFlying = false;
}
@Override
public void onEnable() {
this.mc.thePlayer.capabilities.isFlying = true;
}
@EventTarget
public void onUpdate(UpdateEvent event) {
if(this.getState()) {
this.mc.thePlayer.capabilities.isFlying = true;
int speed = this.getOption("Speed").getIntValue();
float var10 = (float) speed / 5.0F * 0.9F;
this.mc.thePlayer.capabilities.setFlySpeed(0.35F * var10);
if(this.getOption("Vanilla fly").isBooleanValue())
return;
if (this.mc.gameSettings.keyBindJump.isKeyDown()) {
this.mc.thePlayer.motionY = 0.02D;
} else {
this.mc.thePlayer.motionY -= 0.006D;
}
if (this.mc.gameSettings.keyBindSneak.isKeyDown()) {
this.mc.thePlayer.motionY -= 0.03D;
}
}
}
}
| true
|
b29bcf9b8568ede20b3ab100c38ae6cad6e06b8a
|
Java
|
clementselvaprasath/learning
|
/android/do-it-android/practice/Chapter2_5/app/src/main/java/com/muchine/chapter2_5/ui/graphics/painter/Paintable.java
|
UTF-8
| 275
| 2.359375
| 2
|
[] |
no_license
|
package com.muchine.chapter2_5.ui.graphics.painter;
import android.view.View;
/**
* Created by sejoonlim on 9/3/16.
*/
public interface Paintable {
void paint(View view);
void begin(int x, int y);
void moveTo(int x, int y);
void end(int x, int y);
}
| true
|
b747832b55e4279c86c79ebebd925968a56314b4
|
Java
|
nlanglois/SimpleBank3
|
/src/com/superbank/Saving.java
|
UTF-8
| 389
| 2.53125
| 3
|
[] |
no_license
|
package com.superbank;
public class Saving extends Account {
private String type = "Savings";
public Saving (Client client) {
super(client);
}
public Saving (Client client, double balance) {
super(client, balance);
}
public String getType () {
return this.type;
}
public double getInterest () {
return 0.04;
}
}
| true
|
f498d469e02cb3a445b96301d069ce9d88f297dc
|
Java
|
thenukagunawardana/timetablesystem
|
/src/main/java/com/eea/timetablesystem/Web/TimeTableController.java
|
UTF-8
| 2,087
| 2.140625
| 2
|
[] |
no_license
|
package com.eea.timetablesystem.Web;
import com.eea.timetablesystem.Model.Modules;
import com.eea.timetablesystem.Model.TimeTable;
import com.eea.timetablesystem.Service.TimeTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
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 java.util.List;
@Controller
public class TimeTableController
{
@Autowired
private TimeTableService timeTableService;
@GetMapping("/timetable")
public String timetable(Model model, @Param("keyword")String keyword)
{
List<TimeTable>listTimeTable=timeTableService.getAllTimeTables(keyword);
model.addAttribute("listTimeTable",timeTableService.getAllTimeTables(keyword));
model.addAttribute("keyword",keyword);
return "timetable";
}
@GetMapping("/addTimeTable")
public String addTimeTable(Model model)
{
TimeTable timeTable= new TimeTable();
model.addAttribute("timetable",timeTable);
return "addTimeTable";
}
@PostMapping("/addTimeTable")
public String addTimeTable(@ModelAttribute("timetable")TimeTable timeTable)
{
timeTableService.addTimeTable(timeTable);
return "redirect:/timetable";
}
@GetMapping("/updateTimetable/{id}")
public String showFormForUpdateTimeTable(@PathVariable(value = "id")int id,Model model)
{
TimeTable timeTable=timeTableService.getTimeTableById(id);
model.addAttribute("timetable",timeTable);
return "updateTimetable";
}
@GetMapping("/deleteTimeTable/{id}")
public String deleteTimeTable(@PathVariable(value = "id") int id)
{
this.timeTableService.deleteTimeTableById(id);
return "redirect:/timetable";
}
}
| true
|
ccd5a8b530afae9776993bf456ccfde756ddd7d9
|
Java
|
cshanor/Project-Zero----Bank-Application
|
/week1-bankproject-3/src/main/java/com/revature/BankDriver.java
|
UTF-8
| 750
| 2.671875
| 3
|
[] |
no_license
|
package com.revature;
import java.util.InputMismatchException;
import java.util.Scanner;
import com.revature.screens.MenuScreen;
import com.revature.screens.Screen;
import com.revature.utils.AppState;
public class BankDriver {
public static void main(String[] args) {
runApp();
}
public static void runApp() {
System.out.println("[LOG] - Initializing system...");
AppState.setAppRunning(true);
AppState.setRestartingApp(false);
Screen screen = new MenuScreen();
Scanner scan = new Scanner(System.in);
while(AppState.isAppRunning()) {
screen.start(scan);
}
try {
scan.close();
} catch (InputMismatchException ime) {
ime.printStackTrace();
}
}
}
| true
|
1bc3c4790892e463aea875b6a7fa625a02969612
|
Java
|
saikatHi6/security_module
|
/src/main/java/org/atom/login/model/payload/AuthenticationResponse.java
|
UTF-8
| 444
| 2.3125
| 2
|
[] |
no_license
|
package org.atom.login.model.payload;
import java.io.Serializable;
public class AuthenticationResponse implements Serializable {
private final String jwt;
private String tokenType = "Bearer";
public AuthenticationResponse(String jwt) {
this.jwt = jwt;
}
public String getJwt() {
return jwt;
}
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
}
| true
|
28aca8e11db7b4223f2fd9767fd1de15ba89b226
|
Java
|
jichanho/SNS
|
/src/main/java/servlet/impl/testDAO.java
|
UTF-8
| 361
| 1.703125
| 2
|
[] |
no_license
|
package servlet.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import egovframework.rte.psl.dataaccess.EgovAbstractDAO;
@Repository("testDAO")
public class testDAO extends EgovAbstractDAO{
public List<?> selectAll() throws Exception{
System.out.println("testDAO.java - selectAll()");
return list("ul_selectAll");
}
}
| true
|
5f303cd433b45f3b998e5860031924a3e54dd3af
|
Java
|
zhang3371289/FindDog
|
/app/src/main/java/com/find/dog/Retrofit/RetroFitRequestEngine.java
|
UTF-8
| 4,091
| 1.929688
| 2
|
[] |
no_license
|
package com.find.dog.Retrofit;
import android.database.Observable;
import com.find.dog.data.GetUserInfo;
import com.find.dog.data.QiNiuInfo;
import com.find.dog.data.UserPetInfo;
import com.find.dog.data.stringInfo;
import java.util.ArrayList;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
/**
* Created by czz on 2017/4/15.
* 所有的接口信息都在这里配置
*/
public interface RetroFitRequestEngine {
//登录
@POST("login.php")
Call<BaseEntity<stringInfo>> getLoginInfo(@Body RequestBody route);
//注册
@POST("regist_user.php")
Call<BaseEntity<stringInfo>> getRegistInfo(@Body RequestBody route);
//修改user信息
@POST("alter_user.php")
Call<BaseEntity<stringInfo>> alterUserInfo(@Body RequestBody route);
//发送心跳(客户端发送)登陆后开始间隔发送
@POST("alive.php")
Call<BaseEntity<stringInfo>> sendAliveInfo(@Body RequestBody route);
//宠物信息录入
@POST("regist_pat.php")
Call<BaseEntity<stringInfo>> getRegistPetInfo(@Body RequestBody route);
//获取用户信息
@POST("getinfo_user.php")
Call<BaseEntity<GetUserInfo>> getUserInfo(@Body RequestBody route);
//获取用户所有宠物
@POST("getinfo_userpats.php")
Call<BaseEntity<ArrayList<UserPetInfo>>> getUserAllPetInfo(@Body RequestBody route);
//获取单个宠物
@POST("getinfo_pat.php")
Call<BaseEntity<ArrayList<UserPetInfo>>> getUserPetInfo(@Body RequestBody route);
//获取已找到的所有宠物
@POST("getinfo_backpat.php")
Call<BaseEntity<stringInfo>> getUserBackPetInfo(@Body RequestBody route);
//获取正在悬赏的宠物(XX省XX市XX区/镇)
@POST("getinfo_reward.php")
Call<BaseEntity<ArrayList<UserPetInfo>>> getRewardInfo(@Body RequestBody route);
//获取“发现”数据
@POST("getfindinfo.php")
Call<BaseEntity<ArrayList<UserPetInfo>>> getFindInfo(@Body RequestBody route);
//获取 扫一扫 登录后 “发现”数据
@POST("getfindinfo_login_sao.php")
Call<BaseEntity<ArrayList<UserPetInfo>>> getFindIsLoginInfo(@Body RequestBody route);
//改变宠物状态(确认中) lose->confirming
@POST("state_loseToConfirming.php")
Call<BaseEntity<stringInfo>> changeLoseToConfirmingState(@Body RequestBody route);
//改变宠物状态(取消悬赏) lose->normal
@POST("state_loseToNormal.php")
Call<BaseEntity<stringInfo>> changeLoseToNormalState(@Body RequestBody route);
//改变宠物状态(确认失败,继续悬赏) confirming->lose
@POST("state_confirmingToLose.php")
Call<BaseEntity<stringInfo>> changeConfirmingToLoseState(@Body RequestBody route);
//改变宠物状态(宠物找回) confirming->normal
@POST("state_confirmingToNormal.php")
Call<BaseEntity<stringInfo>> changeConfirmingToNormalState(@Body RequestBody route);
//发布悬赏
@POST("release_reward.php")
Call<BaseEntity<stringInfo>> sendRewardInfo(@Body RequestBody route);
//改变宠物信息
@POST("alter_pat.php")
Call<BaseEntity<stringInfo>> changePetInfo(@Body RequestBody route);
//删除宠物
@POST("delet_pat.php")
Call<BaseEntity<stringInfo>> deletePetInfo(@Body RequestBody route);
//获取七牛token
@POST("phpsdk/examples/upload_token.php")
Call<BaseEntity<QiNiuInfo>> getTokenInfo(@Body RequestBody route);
//上传图片和描述
@Multipart
@POST("url")
Observable<String> uploadUserFile(
@Part("fileName") RequestBody description,
@Part("file\"; filename=\"image.png\"") RequestBody img
);
@Multipart
@POST("url")
Observable<String> uploadUserFileAndId(
@Part("describe") String describe,
@Part("type") String type,
@Part("userid") String userid,
@Part("fileName") RequestBody description,
@Part("file\"; filename=\"image.png\"") RequestBody img
);
}
| true
|
0d3f6ab0072258bd43849d5ff469a8a608f360a2
|
Java
|
Svagtlys/FunWithQuizzes
|
/src/QuizRunner.java
|
UTF-8
| 1,172
| 3.265625
| 3
|
[] |
no_license
|
import QuestionTypes.Checkbox;
import QuestionTypes.MultipleChoice;
import QuestionTypes.TrueOrFalse;
import java.util.ArrayList;
public class QuizRunner {
public static void main(String[] args){
Quiz myFirstQuiz = new Quiz("My First Quiz");
myFirstQuiz.addQuestion(
new MultipleChoice(
"What is the first letter of the alphabet?",
new ArrayList<String>(){{add("B"); add("Z"); add("A"); add("F");}},
"A")
);
myFirstQuiz.addQuestion(
new Checkbox(
"What years are in the 21st century?",
new ArrayList<String>(){{add("1991"); add("2001"); add("2006"); add("2099"); add("2100");}},
new ArrayList<String>(){{add("2001"); add("2006"); add("2099");}}
)
);
myFirstQuiz.addQuestion(
new TrueOrFalse(
"Java is an object-oriented programming language?",
"True"
)
);
myFirstQuiz.runQuiz();
myFirstQuiz.getLatestGrade();
}
}
| true
|
30f86862672373c42756005e48c47d26334d86ce
|
Java
|
gabrielvicenteYT/melon-client-src
|
/com/mysql/cj/xdevapi/InsertStatementImpl.java
|
UTF-8
| 1,839
| 2.21875
| 2
|
[
"MIT"
] |
permissive
|
package com.mysql.cj.xdevapi;
import com.mysql.cj.*;
import com.mysql.cj.protocol.x.*;
import com.mysql.cj.protocol.*;
import java.util.concurrent.*;
import java.util.*;
public class InsertStatementImpl implements InsertStatement
{
private MysqlxSession mysqlxSession;
private String schemaName;
private String tableName;
private InsertParams insertParams;
InsertStatementImpl(final MysqlxSession mysqlxSession, final String schema, final String table, final String[] fields) {
this.insertParams = new InsertParams();
this.mysqlxSession = mysqlxSession;
this.schemaName = schema;
this.tableName = table;
this.insertParams.setProjection(fields);
}
InsertStatementImpl(final MysqlxSession mysqlxSession, final String schema, final String table, final Map<String, Object> fieldsAndValues) {
this.insertParams = new InsertParams();
this.mysqlxSession = mysqlxSession;
this.schemaName = schema;
this.tableName = table;
this.insertParams.setFieldsAndValues(fieldsAndValues);
}
@Override
public InsertResult execute() {
return this.mysqlxSession.query(((XMessageBuilder)this.mysqlxSession.getMessageBuilder()).buildRowInsert(this.schemaName, this.tableName, this.insertParams), (ResultBuilder<InsertResult>)new InsertResultBuilder());
}
@Override
public CompletableFuture<InsertResult> executeAsync() {
return this.mysqlxSession.queryAsync(((XMessageBuilder)this.mysqlxSession.getMessageBuilder()).buildRowInsert(this.schemaName, this.tableName, this.insertParams), (ResultBuilder<InsertResult>)new InsertResultBuilder());
}
@Override
public InsertStatement values(final List<Object> row) {
this.insertParams.addRow(row);
return this;
}
}
| true
|
0984bc95ad2440a74e63aae690b652a80886105d
|
Java
|
xiaojinzi123/Component
|
/ComponentApi/src/main/java/com/xiaojinzi/component/anno/ImplicitUseAnno.java
|
UTF-8
| 418
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.xiaojinzi.component.anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 表示隐式的使用了
*/
@Retention(RetentionPolicy.SOURCE)
@Target({
ElementType.TYPE, ElementType.METHOD,
ElementType.FIELD, ElementType.PARAMETER
})
public @interface ImplicitUseAnno {
}
| true
|
1234f18171c72b5a67e67428f0f28cbc2a0d4e53
|
Java
|
StephenOTT/STIX-Java
|
/src/main/java/io/digitalstate/stix/vocabulary/vocabularies/ReportLabels.java
|
UTF-8
| 1,014
| 2.25
| 2
|
[
"MIT"
] |
permissive
|
package io.digitalstate.stix.vocabulary.vocabularies;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.digitalstate.stix.vocabulary.StixVocabulary;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ReportLabels implements StixVocabulary {
@JsonProperty("report_labels_vocabulary")
private Set<String> terms = new HashSet<>(Arrays.asList(
"threat-report", "attack-pattern", "campaign",
"identity", "indicator", "malware",
"observed-data", "threat-actor", "tool",
"vulnerability"));
//
// Getters and Setters
//
@Override
public Set<String> getAllTerms() {
return terms;
}
@Override
public Set<String> getAllTermsWithAdditional(String[] terms) {
return Stream.concat(getAllTerms().stream(), Arrays.stream(terms))
.collect(Collectors.toCollection(HashSet::new));
}
}
| true
|
794a153e658afdbb38771fcd5957124673f203df
|
Java
|
Xoric/Prism
|
/PrismSceneBase/src/xoric/prism/scene/art/grid/GridMeta.java
|
UTF-8
| 4,093
| 2.40625
| 2
|
[] |
no_license
|
package xoric.prism.scene.art.grid;
import java.util.ArrayList;
import java.util.List;
import xoric.prism.data.exceptions.PrismException;
import xoric.prism.data.exceptions.UserErrorText;
import xoric.prism.data.meta.MetaBlock_in;
import xoric.prism.data.meta.MetaKey;
import xoric.prism.data.meta.MetaLine_in;
import xoric.prism.data.meta.MetaList_in;
import xoric.prism.data.meta.MetaType;
import xoric.prism.data.types.FloatPoint;
import xoric.prism.data.types.FloatRect;
import xoric.prism.data.types.IFloatPoint_r;
import xoric.prism.data.types.IFloatRect_r;
import xoric.prism.data.types.IText_r;
import xoric.prism.scene.art.ArtMeta;
public class GridMeta extends ArtMeta
{
private IText_r name;
private IFloatPoint_r spriteSize;
private int columnCount;
private final List<FloatRect> rects;
public GridMeta()
{
rects = new ArrayList<FloatRect>();
}
@Override
public void load(MetaList_in metaList) throws PrismException
{
super.load(metaList);
rects.clear();
columnCount = 0;
MetaBlock_in mb = metaList.claimMetaBlock(MetaType.GRID);
IFloatPoint_r textureSize = null;
for (MetaLine_in ml : mb.getMetaLines())
{
textureSize = interpretLine(textureSize, ml);
}
}
public IFloatRect_r getRect(int index)
{
return rects.get(index);
}
public IFloatPoint_r getSpriteSize()
{
return spriteSize;
}
public int getSpriteCount()
{
return rects.size();
}
private IFloatPoint_r interpretLine(IFloatPoint_r textureSize, MetaLine_in ml) throws PrismException
{
MetaKey key = ml.getKey();
if (key == MetaKey.ITEM)
{
name = interpretItem(ml);
}
else if (key == MetaKey.SIZE)
{
textureSize = interpretSize(ml);
}
else if (key == MetaKey.ALT)
{
columnCount = interpretAlt(ml);
}
else if (key == MetaKey.COUNT)
{
interpretCount(ml, textureSize);
}
return textureSize;
}
private IText_r interpretItem(MetaLine_in ml) throws PrismException
{
ml.ensureMinima(0, 0, 1);
IText_r name = ml.getHeap().texts.get(0);
return name;
}
private IFloatPoint_r interpretSize(MetaLine_in ml) throws PrismException
{
ml.ensureMinima(4, 0, 0);
int w = ml.getHeap().ints.get(0);
int h = ml.getHeap().ints.get(1);
FloatPoint textureSize = new FloatPoint(w, h);
w = ml.getHeap().ints.get(2);
h = ml.getHeap().ints.get(3);
spriteSize = new FloatPoint(w, h);
return textureSize;
}
private int interpretAlt(MetaLine_in ml) throws PrismException
{
ml.ensureMinima(1, 0, 0);
int columnCount = ml.getHeap().ints.get(0);
return columnCount;
}
private void interpretCount(MetaLine_in ml, IFloatPoint_r textureSize) throws PrismException
{
ml.ensureMinima(1, 0, 0);
ensureColumnSpriteSizeIsSet(ml);
ensureTextureSizeIsSet(ml, textureSize);
ensureColumnCountIsSet(ml);
int n = ml.getHeap().ints.get(0);
int c = 0;
int r = 0;
final float w = spriteSize.getX() / textureSize.getX();
final float h = spriteSize.getY() / textureSize.getY();
for (int i = 0; i < n; ++i)
{
rects.add(new FloatRect(c * w, r * h, w, h));
if (++c >= columnCount)
{
c = 0;
++r;
}
}
}
private void ensureColumnCountIsSet(MetaLine_in ml) throws PrismException
{
if (columnCount <= 0)
{
PrismException e = new PrismException();
e.user.setText(UserErrorText.LOCAL_GAME_FILE_CAUSED_PROBLEM);
e.code.setText("column count of grid was zero");
ml.addExceptionInfoTo(e);
throw e;
}
}
private void ensureColumnSpriteSizeIsSet(MetaLine_in ml) throws PrismException
{
if (spriteSize == null)
{
PrismException e = new PrismException();
e.user.setText(UserErrorText.LOCAL_GAME_FILE_CAUSED_PROBLEM);
e.code.setText("sprite size of grid was null");
ml.addExceptionInfoTo(e);
throw e;
}
}
private void ensureTextureSizeIsSet(MetaLine_in ml, IFloatPoint_r textureSize) throws PrismException
{
if (textureSize == null)
{
PrismException e = new PrismException();
e.user.setText(UserErrorText.LOCAL_GAME_FILE_CAUSED_PROBLEM);
e.code.setText("texture size of grid was null");
ml.addExceptionInfoTo(e);
throw e;
}
}
}
| true
|