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 |
---|---|---|---|---|---|---|---|---|---|---|---|
21e323cc0de0979b4c4174bf2175fe3c2022931a
|
Java
|
minhaj-boop/Basic-java
|
/Bank Acoount UI/src/bank/acoount/ui/FXMLDocumentController.java
|
UTF-8
| 2,107 | 2.671875 | 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 bank.acoount.ui;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
/**
*
* @author HP
*/
public class FXMLDocumentController implements Initializable {
@FXML
private TextField accountIdTextField;
@FXML
private TextField accountNameTextField;
@FXML
private TextArea addressTextField;
@FXML
private TextField balanceTextField;
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
@FXML
private void handleResetAction(ActionEvent event) {
}
@FXML
private void handleCreateAccountAction(ActionEvent event) {
long accountID = Long.parseLong(accountIdTextField.getText());
String accountName = accountNameTextField.getText();
String address = addressTextField.getText();
double balance = Double.parseDouble(balanceTextField.getText());
BankAccount bankAccount = new BankAccount(accountID, accountName, address, balance);
System.out.println(bankAccount);
try {
RandomAccessFile output = new RandomAccessFile("C:\\Users\\HP\\Desktop\\Tomal sirs java\\Bank Acoount UI\\accounts.txt", "rw");
long length = output.length();
output.seek(length);
output.writeBytes(bankAccount + "\n");
} catch (FileNotFoundException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| true |
4e2b572f9a956b8e7e7afeb82415538e4b9c272d
|
Java
|
i-am-ayush/care-training
|
/src/main/java/form/CloseJobForm.java
|
UTF-8
| 546 | 2.359375 | 2 |
[] |
no_license
|
package form;
import java.util.HashMap;
import java.util.Map;
public class CloseJobForm extends Form {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private Map<String, String> errorMessage;
public Map<String, String> vaidate() {
errorMessage = new HashMap<>();
validateId();
return errorMessage;
}
private void validateId(){
if(id>0 && id<1000)
errorMessage.put("id","id is not valid");
}
}
| true |
57c8699f642ef1d792ff2f94e6fada1d2cae2c44
|
Java
|
AngeloWei/taotao
|
/taotao-search/search-service/src/test/java/TestSolrCloud.java
|
UTF-8
| 1,780 | 1.921875 | 2 |
[] |
no_license
|
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/spring/applicationContext-solr.xml")
public class TestSolrCloud {
@Autowired
private SolrClient solrClient;
@Test
public void testCloud() throws IOException, SolrServerException {
//执行添加
// HttpSolrClient build = new HttpSolrClient.Builder("http://192.168.2.129:8080/solr/core1").build();
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "213122222");
document.addField("item_sell_point", "卖点描述??");
solrClient.add(document);
solrClient.commit();
}
@Test
public void testCloud1() throws IOException, SolrServerException {
String zkHost = "192.168.2.128:2281,192.168.2.129:2281,192.168.2.129:2282";
CloudSolrClient cloudSolrClient = new CloudSolrClient.Builder().withZkHost(zkHost).build();
cloudSolrClient.setDefaultCollection("collection2");
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "test2131");
document.addField("item_desc", "这是一个描述");
cloudSolrClient.add(document);
cloudSolrClient.commit();
}
}
| true |
edc3643c94366812149de1d9f71eb71200ffd167
|
Java
|
Javachenxu/JavaStudy
|
/day_08/Extends/ExtendDmeo.java
|
UTF-8
| 562 | 3.625 | 4 |
[] |
no_license
|
package JavaStudySpace.day_08.Extends;
//普通人类
class Person{
public String name;
protected int age;
public void sleep() {
System.out.println("睡着");
}
}
//学生类
class Student extends Person{
String sn;
}
//老师类
class Teacher extends Person{
private String level;
}
//员工类
class Employee extends Person{
String hireDate;//入职时间
}
public class ExtendDmeo {
public static void main(String[] args) {
Teacher t = new Teacher();
t.sleep();
}
}
| true |
3acf3fed6baa32610332f99b2f06b5be39166a4d
|
Java
|
mazbergaz/sample_scrapper
|
/src/test/java/org/mazb/samplescrapper/test/ParserTest.java
|
UTF-8
| 2,558 | 2.03125 | 2 |
[] |
no_license
|
package org.mazb.samplescrapper.test;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mazb.samplescrapper.client.AirAsiaHttpClient;
import org.mazb.samplescrapper.model.FlightInfo;
import org.mazb.samplescrapper.model.FlightSearchAirAsiaModel;
import org.mazb.samplescrapper.util.AirasiaMobileConverter;
import org.mazb.samplescrapper.util.ModelConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-context-test.xml")
public class ParserTest {
@Autowired(required=true)
private ModelConverter modelConverter;
@Autowired(required=true)
private AirAsiaHttpClient airasiaHttpClient;
@Test
public void postToAirAsiaMockupWeb(){
FlightSearchAirAsiaModel airAsiaModel = new FlightSearchAirAsiaModel();
airAsiaModel.setMarketStructure("RoundTrip");
airAsiaModel.setDatePicker1("12/30/2013");
airAsiaModel.setDatePicker2("12/31/2013");
File file = null;
try {
file = new ClassPathResource("test01.html").getFile();
FlightInfo flightInfo = airasiaHttpClient.postToAirAsiaWebMockup(airAsiaModel, file);
assertTrue(flightInfo.getGoFlightDetails().size()==8);
assertTrue(flightInfo.getReturnFlightDetails().size()==8);
file = new ClassPathResource("test03.html").getFile();
flightInfo = airasiaHttpClient.postToAirAsiaWebMockup(airAsiaModel, file);
assertTrue(flightInfo.getGoFlightDetails().size()==8);
assertTrue(flightInfo.getReturnFlightDetails().size()==0);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void postToAirAsiaMockupMobile(){
FlightSearchAirAsiaModel airAsiaModel = new FlightSearchAirAsiaModel();
airAsiaModel.setMarketStructure("round-trip");
airAsiaModel.setDatePicker1("12/30/2013");
airAsiaModel.setDatePicker2("12/31/2013");
airAsiaModel.setCurrency("IDR");
File file = null;
try {
file = new ClassPathResource("postmobile_result.html").getFile();
FlightInfo flightInfo = airasiaHttpClient.postToAirasiaMobileMockup(airAsiaModel, file);
assertTrue(flightInfo.getGoFlightDetails().size()==9);
assertTrue(flightInfo.getReturnFlightDetails().size()==9);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
22853ae0c2a58082297565daaf2ba16a5f110fa4
|
Java
|
KarolUracz/GymProject
|
/src/main/java/pl/coderslab/gymproject/controller/HomeController.java
|
UTF-8
| 2,301 | 2.203125 | 2 |
[] |
no_license
|
package pl.coderslab.gymproject.controller;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import pl.coderslab.gymproject.Model.CurrentUser;
import pl.coderslab.gymproject.entity.User;
import pl.coderslab.gymproject.fixture.InitDataFixture;
import pl.coderslab.gymproject.service.RoleService;
import pl.coderslab.gymproject.service.UserService;
import javax.validation.Valid;
@Controller
public class HomeController {
private InitDataFixture initDataFixture;
private UserService userService;
private RoleService roleService;
public HomeController(InitDataFixture initDataFixture, UserService userService, RoleService roleService) {
this.initDataFixture = initDataFixture;
this.userService = userService;
this.roleService = roleService;
}
@GetMapping("/initData")
@ResponseBody
public String createUser() {
this.initDataFixture.initRoles();
this.initDataFixture.initUsers();
return "initialized";
}
@GetMapping("/")
public String home() {
return "home";
}
@GetMapping("/form")
public String save(Model model) {
model.addAttribute("user", new User());
return "userForm";
}
@PostMapping("/form")
public String save(@Valid @ModelAttribute User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()){
return "userForm";
}
user.setEnabled(1);
userService.saveUser(user);
return "redirect:/";
}
@GetMapping("/panel")
public String panelRedirection(
@AuthenticationPrincipal CurrentUser currentUser
) {
if (currentUser.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) {
return "redirect:/admin/panel";
} else if (currentUser.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_TRAINER"))) {
return "redirect:/trainer/panel";
} else {
return "redirect:/user/panel";
}
}
}
| true |
1a14ea5170c6f44ee7dba9a47a0c9f6c8cfd331d
|
Java
|
vincentfack/Projet-S3
|
/3DGenerator/src/autre/Error.java
|
ISO-8859-1
| 4,454 | 2.671875 | 3 |
[] |
no_license
|
package autre;
import graphic.Frame;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Iterator;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
/**
* Permet d'afficher une liste de message d'erreur
* @author Alex
*
*/
public class Error extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Contient la liste des erreurs afficher
*/
private Set<FileError> errorList;
/**
* contient le message afficher
*/
private String message;
/**
* contient la liste qui permet d'afficher les details
*/
private JList<String> detail;
/**
* contient la scroll permetant de faire dfiler les messages
*/
private JScrollPane scroll;
/**
* contient les messages d'erreur
*/
private DefaultListModel<String> list;
/**
* permet de cacher les details
*/
private JLabel less;
/**
* permet d'afficher les details
*/
private JLabel more;
/**
* Constructeur de la boite de dialogue
* @param parent
* @param errorList
* @param message
*/
public Error(Frame parent,Set<FileError> errorList,String message){
super(parent,"Attention",true);
this.errorList = errorList;
this.message = message;
this.initComponents();
this.pack();
this.setResizable(false);
int x = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2-this.getWidth()/2);
int y = (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2-this.getHeight()/2);
this.setLocation(x, y);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setVisible(true);
}
/**
* Permet d'initialiser les composants
*/
private void initComponents() {
JLabel libelle = new JLabel(this.message);
Border tmp = BorderFactory.createTitledBorder(null, "Attention", TitledBorder.DEFAULT_POSITION, TitledBorder.DEFAULT_POSITION, new Font("tmp", Font.BOLD, 20));
libelle.setBorder(tmp);
this.more = new JLabel("Afficher les dtails");
this.more.setForeground(Color.BLUE);
this.more.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent arg0) {
more.setVisible(false);
scroll.setVisible(true);
less.setVisible(true);
pack();
}
});
this.detail = new JList<String>();
this.scroll = new JScrollPane(detail);
this.scroll.setVisible(false);
this.list = new DefaultListModel<String>();
Iterator<FileError> it = this.errorList.iterator();
while(it.hasNext())
this.list.addElement(it.next().message());
this.detail.setModel(this.list);
this.less = new JLabel("Afficher moins");
this.less.setForeground(Color.BLUE);
this.less.setVisible(false);
this.less.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent arg0) {
more.setVisible(true);
scroll.setVisible(false);
less.setVisible(false);
pack();
}
});
JButton close = new JButton("Continuer");
close.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
GridBagLayout bagLayout = new GridBagLayout();
this.setLayout(bagLayout);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.NORTH;
c.insets = new Insets(10,30,10,30);
c.weightx = 1;
c.weighty = 0;
c.fill = GridBagConstraints.NORTHEAST;
c.gridwidth = 1;
c.gridheight = 1;
c.gridx = 0;
c.gridy = 0;
bagLayout.setConstraints(libelle, c);
this.add(libelle);
c.gridy = 1;
bagLayout.setConstraints(this.more, c);
this.add(this.more);
c.gridy = 2;
bagLayout.setConstraints(this.scroll, c);
this.add(this.scroll);
c.gridy = 3;
bagLayout.setConstraints(this.less, c);
this.add(this.less);
c.gridy = 4;
bagLayout.setConstraints(close, c);
this.add(close);
}
}
| true |
48acf80959b41cf9297dbf575a8a241e679f9a70
|
Java
|
fangdongliu/market
|
/src/main/java/cn/fdongl/market/security/controller/SecurityController.java
|
UTF-8
| 1,224 | 1.90625 | 2 |
[] |
no_license
|
package cn.fdongl.market.security.controller;
import cn.fdongl.market.example.mapper.ExampleMapper;
import cn.fdongl.market.security.entity.AppUserDetail;
import cn.fdongl.market.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
@Controller
public class SecurityController {
@Autowired
UserMapper mapper;
@RequestMapping("/login")
public String login(){
return "login";
}
@RequestMapping("/login-error")
public String loginError(Model model){
model.addAttribute("loginError",true);
return "login";
}
@RequestMapping("/data")
@ResponseBody
public Object cas(AppUserDetail userDetail){
return 1;
//mapper.getListOne();
}
}
| true |
ab472779fb6e0061012f8d0c8617d6ef7e9dd1ed
|
Java
|
techKJE/EDUC
|
/src/re/kr/enav/sv40/educ/view/SV40EDUCConfigView.java
|
UTF-8
| 11,447 | 1.976563 | 2 |
[] |
no_license
|
/* -------------------------------------------------------- */
/** Config View of EDUC
File name : SV40EDUCConfigView.java
Author : Sang Whan Oh([email protected])
Creation Date : 2017-04-04
Version : v0.1
Rev. history :
Modifier :
*/
/* -------------------------------------------------------- */
package re.kr.enav.sv40.educ.view;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import com.google.gson.JsonObject;
import re.kr.enav.sv40.educ.controller.SV40EDUCController;
import re.kr.enav.sv40.educ.util.SV40EDUErrCode;
import re.kr.enav.sv40.educ.util.SV40EDUErrMessage;
import re.kr.enav.sv40.educ.util.SV40EDUUtil;
/**
* @brief Configuration view class for EDUC
* @details save properties
* @author Sang Whan Oh
* @date 2017.04.04
* @version 0.0.1
*
*/
public class SV40EDUCConfigView extends JDialog implements ActionListener {
private SV40EDUCController m_controller;
private String m_fields[] = {
"enc.zone", "enc.license", "enc.path", "enc.schedule",
"ecs.position.lat", "ecs.position.lon", "ecs.ship.name", "ecs.maker", "ecs.model", "ecs.serial",
"cloud.srcMRN", "cloud.destServiceMRN", "cloud.destMccMRN"
}; /**< name of ui component field */
public HashMap<String,JComponent> m_mapComponent;
/**
* @brief create configuration view
* @details create configuration view
* @param parent parent container panel
* @param controller EDUC controller reference
*/
public SV40EDUCConfigView(JFrame parent, SV40EDUCController controller, boolean isModal) {
super(parent, "Configuration-EDUC", isModal);
m_mapComponent = new HashMap<String, JComponent>();
m_controller = controller;
createFrame();
setUIFromConfig(m_controller.getConfig());
setVisible(true);
}
/**
* @brief set tab field from config
* @details read config and set each field value
* @param jsonConfig configuration information
*/
@SuppressWarnings("unchecked")
private void setUIFromConfig(JsonObject jsonConfig) {
JTextField txtField;
JComboBox<String> comboField;
for (int i=0;i<m_fields.length;i++) {
String field = m_fields[i];
String value = SV40EDUUtil.queryJsonValueToString(jsonConfig, field);
if (field.equals("enc.schedule")) {
comboField = (JComboBox<String>)m_mapComponent.get(field);
comboField.setSelectedItem(value);
} else {
txtField = (JTextField)m_mapComponent.get(field);
if(txtField != null)
txtField.setText(value);
else {
StackTraceElement el = Thread.currentThread().getStackTrace()[1];
m_controller.addLog(el, "Invalid Configuration Field:"+field);
}
}
}
}
@SuppressWarnings("unchecked")
private JsonObject getConfigFromUI() {
JsonObject json = m_controller.loadDefaultConfig();
JTextField txtField;
JComboBox<String> comboField;
for (int i=0;i<m_fields.length;i++) {
String field = m_fields[i];
String value = "";
if (field.equals("enc.schedule")) {
comboField = (JComboBox<String>)m_mapComponent.get(field);
value = (String)comboField.getSelectedItem();
} else {
txtField = (JTextField)m_mapComponent.get(field);
value = txtField.getText().trim();
if (value.isEmpty()) {
if (field.equals("enc.zone") || field.equals("enc.license")) {
String msg = SV40EDUErrMessage.get(SV40EDUErrCode.ERR_004, field.substring(4));
JOptionPane.showMessageDialog(null, msg, "Warning", JOptionPane.INFORMATION_MESSAGE);
return null;
}
}
}
SV40EDUUtil.setJsonPropertyByQuery(json, field, value);
}
return json;
}
/**
* @brief create frame
* @details create frame, icon, size
*/
private void createFrame() {
setSize(500, 400);
setLocationRelativeTo(null);
Container contentPane = getContentPane();
contentPane.setLayout(new GridBagLayout());
ImageIcon img = new ImageIcon("Res\\config-icon.png");
setIconImage(img.getImage());
createTab();
createToolbar();
setResizable(false);
}
/**
* @brief create Tab
* @details create Tab
*/
private void createTab() {
Container container = getContentPane();
JTabbedPane pane = new JTabbedPane ();
container.add(pane);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
c.weightx =1.0;
c.weighty =1.0;
c.insets = new Insets(5,5,5,5); //top padding
add(pane, c);
createENCTab(pane);
createECSTab(pane);
createMCTab(pane);
}
/**
* @brief create toolbar
* @details create toolbar at the bottom
*/
private void createToolbar() {
Container container = getContentPane();
JPanel toolbar = new JPanel();
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0,5,5,5); //top padding
container.add(toolbar, c);
JButton btn = new JButton("Save");
btn.addActionListener(this);
toolbar.add(btn);
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0,5,5,5); //top padding
btn = new JButton("Reset");
btn.addActionListener(this);
toolbar.add(btn);
}
/**
* @brief create ENC Tab
* @details create ENC Tab
*/
private void createENCTab(JTabbedPane container) {
ImageIcon img = new ImageIcon("Res\\enc-icon.png");
JPanel panel = new JPanel();
container.addTab("ENC", img, panel, "Set download and update configuration");
panel.setLayout(new GridBagLayout());
// Zone
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.PAGE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.2;
c.insets = new Insets(5,5,5,5); //top padding
panel.add(new JLabel("Zone*"), c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 0.8;
JTextField txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("enc.zone" , txtField);
// license
c.gridx = 0;
c.gridy = 1;
c.weightx = 0.2;
panel.add(new JLabel("license*"), c);
c.gridx = 1;
c.gridy = 1;
c.weightx = 0.8;
txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("enc.license" , txtField);
// ENC Path
c.gridx = 0;
c.gridy = 2;
c.weightx = 0.2;
panel.add(new JLabel("ENC"), c);
c.gridx = 1;
c.gridy = 2;
c.weightx = 0.8;
txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("enc.path" , txtField);
// ENC Schedule
c.gridx = 0;
c.gridy = 3;
c.weightx = 0.2;
c.weighty = 1;
panel.add(new JLabel("Schedule"), c);
c.gridx = 1;
c.gridy = 3;
c.weightx = 0.8;
String[] schedule = {"day", "hour", "minute", "none"};
JComboBox<String> combo = new JComboBox<String>(schedule);
panel.add(combo, c);
m_mapComponent.put("enc.schedule" , combo);
}
/**
* @brief create ECS Tab
* @details create ECS Tab
*/
private void createECSTab(JTabbedPane container) {
ImageIcon img = new ImageIcon("Res\\ecs-icon.png");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
container.addTab("ECS", img, panel, "Configuration for ECS");
// Position
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.PAGE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.2;
c.insets = new Insets(5,5,5,5); //top padding
panel.add(new JLabel("Position Lat/Lon"), c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 0.9;
JTextField txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("ecs.position.lat" , txtField);
c.gridx = 2;
c.gridy = 0;
c.weightx = 0.9;
txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("ecs.position.lon" , txtField);
// Ship
c.gridx = 0;
c.gridy = 1;
c.weightx = 0.2;
panel.add(new JLabel("Ship Name"), c);
c.gridx = 1;
c.gridy = 1;
c.weightx = 0.9;
txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("ecs.ship.name" , txtField);
// ECS
c.gridx = 0;
c.gridy = 2;
c.weightx = 0.2;
panel.add(new JLabel("ECS Maker/Model"), c);
c.gridx = 1;
c.gridy = 2;
c.weightx = 0.9;
c.insets = new Insets(5,5,5,5); //top padding
txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("ecs.maker" , txtField);
c.gridx = 2;
c.gridy = 2;
c.weightx = 0.9;
txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("ecs.model" , txtField);
// ECS Serial
c.gridx = 0;
c.gridy = 3;
c.weightx = 0.2;
c.weighty = 1.0;
panel.add(new JLabel("ECS Serial No."), c);
c.gridx = 1;
c.gridy = 3;
c.weightx = 0.9;
c.insets = new Insets(5,5,5,5); //top padding
txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("ecs.serial" , txtField);
}
/**
* @brief create Marine Cloud Tab
* @details create Marine Cloud Tab
*/
private void createMCTab(JTabbedPane container) {
ImageIcon img = new ImageIcon("Res\\mc-icon.png");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
container.addTab("MC", img, panel, "Configuration for Marine Cloud");
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.PAGE_START;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.1;
c.insets = new Insets(5,5,5,5); //top padding
panel.add(new JLabel("Source MRN(ECS)"), c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 0.8;
JTextField txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("cloud.srcMRN" , txtField);
c.gridx = 0;
c.gridy = 1;
c.weighty = 1;
c.weightx = 0.1;
c.insets = new Insets(5,5,5,5); //top padding
panel.add(new JLabel("Dest. MRN(EDUS)"), c);
c.gridx = 1;
c.gridy = 1;
c.weightx = 0.8;
txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("cloud.destServiceMRN" , txtField);
c.gridx = 0;
c.gridy = 2;
c.weighty = 1;
c.weightx = 0.1;
c.insets = new Insets(5,5,5,5); //top padding
panel.add(new JLabel("Dest. MRN(MCC)"), c);
c.gridx = 1;
c.gridy = 2;
c.weightx = 0.8;
txtField = new JTextField();
panel.add(txtField, c);
m_mapComponent.put("cloud.destMccMRN" , txtField);
}
/**
* @brief button event handler
* @details menu event handler
* @param
*/
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Reset")) {
loadDefaultConfig();
} else if (command.equals("Save")) {
applyConfigChange();
}
}
/**
* @brief reset configuration
* @details reset configuration and load default
*/
public void loadDefaultConfig() {
JsonObject defaultConfig = m_controller.loadDefaultConfig();
setUIFromConfig(defaultConfig);
}
/**
* @brief apply configuration change
* @details save configuration and apply change
*/
public void applyConfigChange() {
JsonObject config = getConfigFromUI();
if (config == null)
return;
m_controller.applyConfigChange(config);
this.dispose();
}
}
| true |
8a2a93f0f17288f18f6595756bb857938e13007c
|
Java
|
funskydev/naturally-mod
|
/src/main/java/elfamoso/naturally/container/InfusionTableSlot.java
|
UTF-8
| 449 | 2.28125 | 2 |
[] |
no_license
|
package elfamoso.naturally.container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.container.Slot;
public class InfusionTableSlot extends Slot {
public InfusionTableSlot(IInventory inv, int slotId, int xPos, int yPos) {
super(inv, slotId, xPos, yPos);
}
/*@Override
public boolean isItemValid(ItemStack stack) {
return stack.isEmpty() || stack.getItem() == Item.getItemFromBlock(Blocks.DIRT);
}*/
}
| true |
74f42c27058d0030df98d7e0a2f876c623bd626b
|
Java
|
tiagosousaoliveira/DnSistem
|
/src/CamadaDao/ConexaoUsuario.java
|
ISO-8859-1
| 5,033 | 2.421875 | 2 |
[] |
no_license
|
package CamadaDao;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import CamadaConexao.conexao;
import CamadaModel.Usuario;
public class ConexaoUsuario {
public static int retorno = 0;
public void gravarnoSQL(Usuario usuario) {
// TODO Auto-generated constructor stub
try{
conexao SQL = new conexao();
SQL.conect();
String sql = "insert into usuario (codigo,data_cadastro,nome,cpf,rg,telefone,funcao,cod_loja," +
"nome_loja,endereco,logon,senha,comissao,vendas,metas,inativo)" +
"values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
java.sql.PreparedStatement stm = SQL.con.prepareStatement(sql);
stm.setInt(1,usuario.getId());
stm.setString(2,usuario.getData());
stm.setString(3,usuario.getNome());
stm.setString(4,usuario.getCpf());
stm.setString(5,usuario.getRg());
stm.setString(6,usuario.getTelefone());
stm.setString(7,usuario.getFuncao());
stm.setString(8,usuario.getCodigo_loja());
stm.setString(9,usuario.getLoja());
stm.setString(10,usuario.getEndereco());
stm.setString(11,usuario.getLogon());
stm.setString(12,usuario.getSenha());
stm.setString(13,usuario.getComissao());
stm.setString(14,usuario.getVendas());
stm.setString(15,usuario.getMetas());
stm.setBoolean(16,usuario.getInativo());
stm.execute();
stm.close();
conexao.con.close();
retorno = 0;
retorno = retorno +1;
}catch(SQLException ex){
retorno = 0;
retorno = retorno +2;
}
}
public void deletarnoSQL(Usuario usuario){
// TODO Auto-generated constructor stub
JOptionPane.showMessageDialog(null, "Acessou com exito ");
try{
conexao cont = new conexao();
cont.conect();
String sql = "delete from usuario where nome=?";
java.sql.PreparedStatement stm = cont.con.prepareStatement(sql);
stm.setString(1,usuario.getNome());
stm.execute();
stm.close();
conexao.con.close();
}catch(SQLException ex){
JOptionPane.showMessageDialog(null, " Erro na Excluso ");
}
}
public void pesquisarnoSQL(){
// TODO Auto-generated constructor stub
JOptionPane.showMessageDialog(null, "Acessou com exito ");
}
public void updatenoSQL(Usuario usuario){
// TODO Auto-generated constructor stub
try {
conexao SQL = new conexao();
SQL.conect();
String sql = "update usuario set data_cadastro=?,nome=?,cpf=?,rg=?,telefone=?,funcao=?,logon=?,senha=?,cod_loja=?," +
"nome_loja=?,endereco=?,comissao=?,vendas=?,metas_vendas=?" +
"where codigo=?";
java.sql.PreparedStatement stm = SQL.con.prepareStatement(sql);
stm.setString(1,usuario.getData());
stm.setString(2,usuario.getNome());
stm.setString(3,usuario.getCpf());
stm.setString(4,usuario.getRg());
stm.setString(5,usuario.getTelefone());
stm.setString(6,usuario.getFuncao());
stm.setString(7,usuario.getLogon());
stm.setString(8,usuario.getSenha());
stm.setString(9,usuario.getCodigo_loja());
stm.setString(10,usuario.getLoja());
stm.setString(11,usuario.getEndereco());
stm.setString(12,usuario.getComissao());
stm.setString(13,usuario.getVendas());
stm.setString(14,usuario.getMetas());
stm.setInt(15,usuario.getId());
stm.execute();
stm.close();
JOptionPane.showMessageDialog(null, "Alteraes realizadas");
conexao.con.close();
}catch (SQLException e ){
JOptionPane.showMessageDialog(null, "Entrou no catch");
}
}
/* public int BuscanoSQL(){
try {
conexao SQL = new conexao();
SQL.conect();
String sql= "select *from cliente";
java.sql.PreparedStatement stm = SQL.con.prepareStatement(sql);
ResultSet rst= stm.executeQuery();
if(rst.next()){
if(rst.getInt("codigo")==(Cliente.recebsequencia)){
int c = rst.getInt("codigo");
JOptionPane.showMessageDialog(null, "Codigo "+c+" J existe no Banco de Dados");
retorno = 0;
retorno = retorno+1;
return retorno ;
}else {
ConexaoCliente clien= new ConexaoCliente();
clien.gravarnoSQL();
if (this.retorno ==1){
JOptionPane.showMessageDialog(null, "Gravado com Sucesso !!");
retorno = 0;
retorno = retorno +1;
return retorno ;
}else{
retorno = 0;
retorno = retorno +2;
return retorno ;
}
}
}else {
ConexaoCliente clien= new ConexaoCliente();
clien.gravarnoSQL();
if (retorno ==1){
JOptionPane.showMessageDialog(null, "Gravado com Sucesso !!");
retorno = retorno +1;
return retorno ;
}else{
retorno = retorno +2;
return retorno ;
}
}
}catch(SQLException ex){
JOptionPane.showMessageDialog(null, "SQLException inconsistncia dos dados!!");
retorno = 0;
retorno = retorno+4;
return retorno ;
}
}*/
}
| true |
0f1d7db05efbd270d441391ea7e5a96c975d2a0f
|
Java
|
wangyonglin/app
|
/app/src/main/java/com/khbd/data/WebcamsClient.java
|
UTF-8
| 2,536 | 2.296875 | 2 |
[] |
no_license
|
package com.khbd.data;
import android.content.Context;
import com.khbd.app.R;
import java.util.Iterator;
import java.util.List;
import javakit.network.JavaKitClientResponse;
import javakit.network.JavaKitClientResponseCallback;
import javakit.util.JavaKitJsonUtils;
import javakit.util.URLUtils;
public class WebcamsClient {
public class ViewHolder{
public String image;
public String video;
public ViewHolder(String image, String video) {
this.image = image;
this.video = video;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
}
public static void all(Context context,WebcamsClientCallback callback){
String uri= context.getString(R.string.url_webcams_all);
URLUtils urlUtils = URLUtils.make(context.getString(R.string.url_webcams_all));
JavaKitClientResponse.get(urlUtils.url(), new JavaKitClientResponseCallback<String>() {
@Override
public void success(String res) {
try {
List<Webcams> webcams = JavaKitJsonUtils.json2list(res,Webcams.class);
callback.WebcamsAll(context,webcams);
} catch (Exception e) {
callback.onErrorResume(e);
}
}
});
}
public static void categories(Context context,String key,WebcamsClientCallback callback){
StringBuffer uri= new StringBuffer(context.getString(R.string.url_webcams_categories));
uri.append("?key=").append(key);
System.out.print(uri.toString());
JavaKitClientResponse.get(uri.toString(), new JavaKitClientResponseCallback<String>() {
@Override
public void success(String res) {
System.out.print(res);
try {
List<Webcams> webcams = JavaKitJsonUtils.json2list(res,Webcams.class);
callback.WebcamsAll(context,webcams);
} catch (Exception e) {
callback.onErrorResume(e);
}
}
});
}
public interface WebcamsClientCallback{
void WebcamsAll(Context context,List<Webcams> list);
default void onErrorResume(Exception e){};
}
}
| true |
b8dd5b0be356e234383dc834adc6976d07dac5d9
|
Java
|
rafaelrrs/CatalogoLivros
|
/app/src/main/java/com/example/catalogolivros/FormLivroActivity.java
|
UTF-8
| 4,197 | 2.3125 | 2 |
[] |
no_license
|
package com.example.catalogolivros;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.catalogolivros.models.Livro;
import com.example.catalogolivros.services.LivroAPI;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FormLivroActivity extends AppCompatActivity {
int livroID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form_livro);
Livro livroASalvar = new Livro();
LivroAPI.getInstance().store(livroASalvar).enqueue(new Callback<Livro>() {
@Override
public void onResponse(Call<Livro> call, Response<Livro> response) {
// MSG de sucesso
}
@Override
public void onFailure(Call<Livro> call, Throwable t) {
// t.getMessage()
}
});
//String receberLivro = getIntent().getStringExtra("livro", );
if (getIntent().hasExtra("livro")){
Livro livroEdicao = (Livro) getIntent().getSerializableExtra("livro");
livroID = livroEdicao.getId();
((EditText) findViewById(R.id.txtVwFormLivroTitulo)).setText(livroEdicao.getTitulo());
((EditText) findViewById(R.id.txtVwFormLivroResumo)).setText(livroEdicao.getResumo());
((EditText) findViewById(R.id.txtVwFormLivroPaginas)).setText(livroEdicao.getPaginas());
((EditText) findViewById(R.id.txtVwFormLivroEdicao)).setText(livroEdicao.getEdicao());
((EditText) findViewById(R.id.txtVwFormLivroAno)).setText(livroEdicao.getAno());
((EditText) findViewById(R.id.txtVwFormLivroIsbn)).setText(livroEdicao.getIsbn());
}
}
public void actionFormLivroSalvar(View view){
Livro livroASalvar = new Livro(
((EditText) findViewById(R.id.txtVwFormLivroTitulo)).getText().toString(),
((EditText) findViewById(R.id.txtVwFormLivroResumo)).getText().toString(),
((EditText) findViewById(R.id.txtVwFormLivroPaginas)).getText().toString(),
((EditText) findViewById(R.id.txtVwFormLivroEdicao)).getText().toString(),
((EditText) findViewById(R.id.txtVwFormLivroAno)).getText().toString(),
((EditText) findViewById(R.id.txtVwFormLivroIsbn)).getText().toString()
);
Call<Livro> calllLivro;
if(livroID > 0)
calllLivro = LivroAPI.getInstance().update(livroID, livroASalvar);
else
calllLivro = LivroAPI.getInstance().store(livroASalvar);
calllLivro.enqueue(new Callback<Livro>() {
@Override
public void onResponse(Call<Livro> call, Response<Livro> response) {
if (response.message().equalsIgnoreCase("created")){
Toast.makeText(getBaseContext(), "Livro cadastrado com sucesso.", Toast.LENGTH_LONG).show();
} else if (response.message().equalsIgnoreCase("OK")){
Toast.makeText(getBaseContext(), "Livro ATUALIZADO com sucesso.", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void onFailure(Call<Livro> call, Throwable t) {
Toast.makeText(getBaseContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
// LivroAPI.getInstance().store(livroASalvar).enqueue(new Callback<Livro>() {
// @Override
// public void onResponse(Call<Livro> call, Response<Livro> response) {
// if (response.message().equalsIgnoreCase("created")){
// Toast.makeText(getBaseContext(), "Livro cadastrado com sucesso.", Toast.LENGTH_LONG).show();
// }
//
// }
// @Override
// public void onFailure(Call<Livro> call, Throwable t) {
// Toast.makeText(getBaseContext(), t.getMessage(), Toast.LENGTH_LONG).show();
// }
// });
}
}
| true |
63316161bc51b1ee453056436fd0b1703a8d10e7
|
Java
|
CMU-CREATE-Lab/terk-legacy
|
/TeRKClient/code/java/MyFirstRobot250/src/RSSReaders/StockComparisonChangeStatus.java
|
UTF-8
| 1,015 | 2.828125 | 3 |
[] |
no_license
|
package RSSReaders;
/**
* <p>
* <code>StockComparisonChangeStatus</code> represents the nine possible change states that two stocks can have in
* relation to one another.
* </p>
*
* @author Chris Bartley ([email protected])
*/
public enum StockComparisonChangeStatus
{
BOTH_UP("Both Up"),
STOCK_1_UP_STOCK_2_NO_CHANGE("Stock 1 Up, Stock 2 No Change"),
STOCK_1_UP_STOCK_2_DOWN("Stock 1 Up, Stock 2 Down"),
STOCK_1_NO_CHANGE_STOCK_2_UP("Stock 1 No Change, Stock 2 Up"),
NO_CHANGE("No Change"),
STOCK_1_NO_CHANGE_STOCK_2_DOWN("Stock 1 No Change, Stock 2 Down"),
STOCK_1_DOWN_STOCK_2_UP("Stock 1 Down, Stock 2 Up"),
STOCK_1_DOWN_STOCK_2_NO_CHANGE("Stock 1 Down, Stock 2 No Change"),
BOTH_DOWN("Both Down");
private final String name;
private StockComparisonChangeStatus(final String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public String toString()
{
return name;
}
}
| true |
c34528b534e7bf2b71e665c4d095d7a748385e0f
|
Java
|
ForteScarlet/simple-plusutils
|
/src/main/java/com/forte/utils/thread/threadutil/delay/DelayUtil.java
|
UTF-8
| 3,919 | 3.0625 | 3 |
[] |
no_license
|
package com.forte.utils.thread.threadutil.delay;
import com.forte.utils.thread.BaseLocalThreadPool;
import com.forte.utils.thread.threadutil.inter.delay.DelayFunc;
import java.util.concurrent.Executor;
/**
* 方法循环,类似js里面的 setInterval、setTimeout 和 clearInterval、clearTimeout<br>
* <br>
* setInterval(Object object, String method, long m, Object...args) , return
* ForteTimeBean<br>
* setTimeout(Object object, String method, long m, Object...args) , return
* ForteTimeBean<br>
* 这两个方法中,object为要执行方法的对象,method为方法名,m为延时的时间(毫秒值),args为此方法的参数<br>
* <br>
* 加入线程池<br>
*
* @author ForteScarlet
*
*/
public class DelayUtil extends BaseLocalThreadPool {
/** 线程池 */
private static ThreadLocal<Executor> LocalExecutor;
/**
* 循环执行方法
*
* @param clazz
* 执行方法的class对象
* @param method
* 要执行的方法
* @param m
* 循环间隔
* @param args
* 方法参数
* @return ForteTimeBean对象,用于终止
*/
public static <T> DelayBean<T> interval(Class<T> clazz, String method, long m, Object... args) {
// 创建线程循环对象
Interval<T> interval = new Interval<>(clazz, method, m, args);
// 线程池中线程执行
BaseLocalThreadPool.getThreadPool().execute(interval);
// 返回此对象
return interval;
}
/**
* 循环执行方法 - 函数接口
*
* @param f
* 函数式接口,在当需要循环调用一些并非特定对象的方法的时候可以使用此函数式接口
* @param m
* 延时时长
* @param args
* 方法参数,若没有则不填
* @return 延时对象,用于结束延时
*/
public static DelayBean interval(DelayFunc f, long m, Object... args) {
// 创建线程循环对象
Interval interval = new Interval<>(f, m, args);
// 线程执行
BaseLocalThreadPool.getThreadPool().execute(interval);
// 返回此对象
return interval;
}
/**
* 设置方法延迟执行
*
* @param object
* 执行方法的对象
* @param method
* 要执行的方法
* @param m
* 循环间隔
* @param args
* 方法参数
* @return ForteTimeBean对象,用于终止
*/
public static <T> DelayBean<T> timeout(Class<T> object, String method, long m, Object... args) {
// 创建线程延时对象
Timeout<T> timeout = new Timeout<T>(object, method, m, args);
// 线程执行
BaseLocalThreadPool.getThreadPool().execute(timeout);
// 返回此对象
return timeout;
}
/**
* 循环执行方法 - 函数接口
*
* @param f
* 函数式接口,在当需要循环调用一些并非特定对象的方法的时候可以使用此函数式接口
* @param m
* 延时时长
* @param args
* 方法参数,若没有则不填
* @return 延时对象,用于结束延时
*/
@SafeVarargs
public static DelayBean timeout(DelayFunc f, long m, Object... args) {
// 创建线程延时对象
Timeout timeout = new Timeout(f, m, args);
// 线程执行
BaseLocalThreadPool.getThreadPool().execute(timeout);
// 返回此对象
return timeout;
}
/**
* 移除延时执行
*
* @param timeBean
* ForteTimeBean对象
*/
public static void stop(DelayBean timeBean) {
timeBean.stop();
}
/**
* 移除延时执行 - 延时millis后执行
*
* @param TimeBean
* @param millis
*/
public static void stop(DelayBean TimeBean, long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
TimeBean.stop();
}
/**
* 清除全部任务
*/
public static void clear(){
LocalExecutor.remove();
}
/**
* 构造私有化 构造方法
*/
private DelayUtil() {
super();
}
}
| true |
ce46f651bf709b212ce5f6c53abe8360b45b8cf9
|
Java
|
wenjiey2/Fertilizer_Adulteration_Classification
|
/app/app/src/main/java/edu/illinois/fertilizeradulterationdetection/prediction/InfoActivity.java
|
UTF-8
| 10,339 | 1.875 | 2 |
[] |
no_license
|
package edu.illinois.fertilizeradulterationdetection.prediction;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import edu.illinois.fertilizeradulterationdetection.R;
import edu.illinois.fertilizeradulterationdetection.utils.ConnectivityUtil;
import android.content.Context;
import android.os.SystemClock;
import org.tensorflow.lite.Interpreter;
import org.tensorflow.lite.support.common.FileUtil;
class FetchTask extends AsyncTask<Void, String, Object> {
private ProgressDialog progress;
private Context context;
public FetchTask(Context cxt) {
context = cxt;
progress = new ProgressDialog(context);
progress.setMessage("Detection in progress...");
}
@Override
protected void onPreExecute() {
progress.show();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... unused) {
SystemClock.sleep(5000);
return null;
}
@Override
protected void onPostExecute(Object result) {
progress.dismiss();
super.onPostExecute(result);
}
public void setProgressText(String text){
progress.setMessage(text);
}
}
public class InfoActivity extends AppCompatActivity {
private Spinner existingStoreView;
private LinearLayout newStoreView;
private Button toPrediction;
private String id;
private DatabaseReference databaseRef;
private String storeName;
private Intent intent;
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
initialization();
findViewById(R.id.radio1).setVisibility(View.GONE);
if(ConnectivityUtil.isNetworkAvailable(this)) {
retrieveSavedStores();
}
}
private void initialization() {
newStoreView = findViewById(R.id.newStore);
existingStoreView = findViewById(R.id.existingStore);
id = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseRef = FirebaseDatabase.getInstance().getReference();
// set up background image
Uri uri = Uri.parse(getIntent().getStringExtra("uri"));
try {
int img_rot = readPictureDegree(uri.getPath());
Bitmap src = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
// if (src.getWidth() > src.getHeight()){
// img_rot = 90;
// }
src = rotateBitmap(src, img_rot);
ImageView imageView = findViewById(R.id.info_image);
imageView.setImageBitmap(src);
} catch (Exception e) {
Toast.makeText(this, "Fail to load image",Toast.LENGTH_LONG).show();
}
// inflater is used to inflate district, village and store text field into its parent view. Please refer to template_label_edittext.xml for details about "custom" view
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final List<String> labels = new ArrayList<>(Arrays.asList("District", "Village", "Store"));
final List<Integer> ids = new ArrayList<>();
for (int i = 0; i < 3; i++) {
assert inflater != null;
@SuppressLint("InflateParams") View custom = inflater.inflate(R.layout.template_label_edittext, null);
TextView tv = custom.findViewById(R.id.label);
tv.setText(labels.get(i) + ": ");
EditText et = custom.findViewById(R.id.text);
int id = View.generateViewId();
ids.add(id);
et.setId(id);
newStoreView.addView(custom);
}
//pass info to prediction
final FetchTask fetchTask = new FetchTask(this);
intent = new Intent(getApplicationContext(), PredictActivity.class);
toPrediction = findViewById(R.id.to_prediction);
toPrediction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// relay extras from previous activity
intent.putExtra("uri", getIntent().getStringExtra("uri"));
intent.putExtra("isFromStorage", getIntent().getBooleanExtra("isFromStorage", false));
// pass new extras obtained in this activity
EditText noteView = findViewById(R.id.note_text);
intent.putExtra("note", noteView.getText().toString());
if (storeName == null) {
for (int i = 0; i < 3; i++) {
EditText v = findViewById(ids.get(i));
if(TextUtils.isEmpty(v.getText())){
Toast.makeText(InfoActivity.this, "Store, district and village cannot be null.",Toast.LENGTH_LONG).show();
return;
}
intent.putExtra(labels.get(i), v.getText().toString());
}
} else {
intent.putExtra("Store", storeName);
}
fetchTask.execute();
startActivity(intent);
}
});
}
public void checkButton(View V) {
RadioGroup radioGroup = findViewById(R.id.radio);;
int radioId = radioGroup.getCheckedRadioButtonId();
// save to existing store
if (radioId == R.id.radio1) {
existingStoreView.setVisibility(View.VISIBLE);
newStoreView.setVisibility(View.GONE);
toPrediction.setVisibility(View.VISIBLE);
} else { // save to new store
newStoreView.setVisibility(View.VISIBLE);
existingStoreView.setVisibility(View.GONE);
toPrediction.setVisibility(View.VISIBLE);
intent.putExtra("newStore", true);
}
}
private void retrieveSavedStores() {
findViewById(R.id.radio1).setVisibility(View.VISIBLE);
databaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ArrayList<String> images = new ArrayList<>();
ArrayList<String> stores = new ArrayList<>();
for(DataSnapshot child : dataSnapshot.child(id).child("stores").getChildren()){
stores.add(child.getKey());
HashMap<String, Object> imgs = (HashMap<String, Object>) ((HashMap<String, Object>)child.getValue()).get("images");
for (String s : imgs.keySet()) {
images.add(s);
}
}
if (images.size() == 0) {
findViewById(R.id.radio1).setVisibility(View.GONE);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.spinner_item, stores);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
existingStoreView.setAdapter(adapter);
existingStoreView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
storeName = (String) adapterView.getItemAtPosition(i);
intent.putExtra("newStore", false);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
// check rotation
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
public static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
if (bitmap == null)
return null;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}
}
| true |
a463a2dd8ca0ea3186b586d1c8c951d3c547cd2e
|
Java
|
bluedestiny/maven_project01
|
/cloud-consumer2-stream/src/main/java/com/springcloud/demo/cloudconsumer2stream/CloudConsumer2StreamApplication.java
|
UTF-8
| 374 | 1.59375 | 2 |
[] |
no_license
|
package com.springcloud.demo.cloudconsumer2stream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CloudConsumer2StreamApplication {
public static void main(String[] args) {
SpringApplication.run(CloudConsumer2StreamApplication.class, args);
}
}
| true |
acc3aaf281a6f6bc55c09bb98b1eefb0b2f29e9a
|
Java
|
cybernhl/MediaController
|
/controller/src/main/java/yyl/media/controller/base/ConfigurationListener.java
|
UTF-8
| 170 | 1.625 | 2 |
[] |
no_license
|
package yyl.media.controller.base;
/**
* Created by yuyunlong on 2017/3/13/013.
*/
public interface ConfigurationListener {
void changeScreen(boolean isFull);
}
| true |
c8ff39f56b4ed64d62414a9c5fb703cd67543956
|
Java
|
Petrullica/siw_progettoXPR
|
/src/model/IndicatoreRisultato.java
|
UTF-8
| 892 | 2.359375 | 2 |
[] |
no_license
|
package model;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
@Entity
public class IndicatoreRisultato {
@Id
private String nome;
@ManyToMany(mappedBy = "indicatoriRisultato", cascade = {CascadeType.REFRESH, CascadeType.MERGE})
private List<TipologiaEsame> tipologieEsame = new LinkedList<>();
public IndicatoreRisultato() {
}
public IndicatoreRisultato(String nome) {
this.nome = nome;
}
public List<TipologiaEsame> getTipologieEsame() {
return tipologieEsame;
}
public void setTipologieEsame(List<TipologiaEsame> tipologieEsame) {
this.tipologieEsame = tipologieEsame;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
| true |
f079f032ae0be27048b1e89a0fd3290cf242d4d3
|
Java
|
ppoox/algorithm
|
/src/baekjoon/silver4/No1920.java
|
UTF-8
| 772 | 3.0625 | 3 |
[] |
no_license
|
package baekjoon.silver4;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class No1920 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Set<Integer> set = new HashSet<>();
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
set.add(sc.nextInt());
}
StringBuilder sb = new StringBuilder();
int m = sc.nextInt();
for (int i = 0; i < m; i++) {
int size = set.size();
set.add(sc.nextInt());
if (size == set.size()) {
sb.append(1);
} else {
sb.append(0);
}
sb.append("\n");
}
System.out.println(sb);
}
}
| true |
af58fb10985702c702148c9df5df7aa1cd582d1a
|
Java
|
Ealb/nationgen
|
/src/nationGen/misc/GodGen.java
|
UTF-8
| 1,712 | 2.578125 | 3 |
[] |
no_license
|
package nationGen.misc;
import nationGen.NationGenAssets;
import nationGen.chances.EntityChances;
import nationGen.entities.Filter;
import nationGen.nation.Nation;
import java.util.ArrayList;
import java.util.List;
public class GodGen extends ChanceIncHandler {
private Nation n;
private List<Filter> orig = new ArrayList<>();
private List<Filter> add = new ArrayList<>();
public GodGen(Nation n, NationGenAssets assets) {
super(n);
this.n = n;
for (Arg arg : n.races.get(0).tags.getAllValues("gods")) {
orig.addAll(assets.miscdef.get(arg.get()));
}
for (Arg arg : n.races.get(0).tags.getAllValues("additionalgods")) {
add.addAll(assets.miscdef.get(arg.get()));
}
if(orig.isEmpty())
orig.addAll(assets.miscdef.get("defaultgods"));
}
public List<Command> giveGods()
{
ChanceIncHandler chandler = new ChanceIncHandler(n);
Filter pantheon = chandler.handleChanceIncs(orig).getRandom(n.random);
List<Command> filters = new ArrayList<>(pantheon.getCommands());
filters.add(Command.args("#homerealm", "10"));
if(add.size() > 0)
{
List<Filter> mores = new ArrayList<>();
for(Filter g : add)
{
List<String> allowed = g.tags.getAllStrings("allowed");
if(allowed.size() == 0 || allowed.contains(pantheon.name))
mores.add(g);
}
EntityChances<Filter> possibles = chandler.handleChanceIncs(mores);
// 0 to 4 extra Filters
int moreFilters = n.random.nextInt(Math.min(mores.size() + 1, 5));
for(int i = 0; i < moreFilters; i++)
{
Filter newFilter = possibles.getRandom(n.random);
mores.remove(newFilter);
filters.addAll(newFilter.getCommands());
}
}
return filters;
}
}
| true |
fc459e31c502afa142617b0438cbeb210588de2c
|
Java
|
catedrasaes-umu/NoSQLDataEngineering
|
/projects/es.um.unosql.subtypes/src/es/um/unosql/subtypes/m2m/UNoSQL2SubtypeUNoSQL.java
|
UTF-8
| 3,511 | 2.25 | 2 |
[
"MIT"
] |
permissive
|
package es.um.unosql.subtypes.m2m;
import java.util.List;
import es.um.unosql.subtypes.discovery.DependencyAnalyzer;
import es.um.unosql.subtypes.util.types.EntitySubtype;
import es.um.unosql.uNoSQLSchema.EntityType;
import es.um.unosql.uNoSQLSchema.RelationshipType;
import es.um.unosql.uNoSQLSchema.SchemaType;
import es.um.unosql.uNoSQLSchema.StructuralFeature;
import es.um.unosql.uNoSQLSchema.StructuralVariation;
import es.um.unosql.uNoSQLSchema.uNoSQLSchema;
import es.um.unosql.utils.UNoSQLFactory;
import es.um.unosql.utils.compare.CompareFeature;
public class UNoSQL2SubtypeUNoSQL
{
private UNoSQLFactory factory = new UNoSQLFactory();
private CompareFeature comparer = new CompareFeature();
public uNoSQLSchema m2m(uNoSQLSchema schema, List<DependencyAnalyzer> analyzers)
{
for (DependencyAnalyzer analyzer : analyzers)
m2m(schema, analyzer);
return schema;
}
public uNoSQLSchema m2m(uNoSQLSchema schema, DependencyAnalyzer analyzer)
{
for (EntitySubtype subtype : analyzer.getSubtypes())
{
String newName = analyzer.getSchemaType().getName() + "_"
+ analyzer.getDiscriminatorSeeker().getDiscriminatorValues().get(subtype);
if (analyzer.getSchemaType() instanceof EntityType)
createEntityType(schema, analyzer.getSchemaType(), newName,
((EntityType) analyzer.getSchemaType()).isRoot(), subtype.getVariations());
else if (analyzer.getSchemaType() instanceof RelationshipType)
createRelationshipType(schema, analyzer.getSchemaType(), newName, subtype.getVariations());
}
return schema;
}
private void createEntityType(uNoSQLSchema schema, SchemaType parent, String name, boolean isRoot,
List<StructuralVariation> variations)
{
EntityType newEntityType = factory.createEntityType(name, isRoot);
newEntityType.getVariations().addAll(variations);
newEntityType.getParents().add(parent);
// For each optional structural feature, if all other variations do contain an
// equal feature, then this feature is no longer optional.
for (StructuralVariation v : variations)
for (StructuralFeature f : v.getStructuralFeatures())
if (f.isOptional() && variations.stream().filter(v2 -> v != v2)
.allMatch(v2 -> v2.getFeatures().stream().anyMatch(f2 -> comparer.compare(f, f2))))
f.setOptional(false);
schema.getEntities().add(newEntityType);
}
private void createRelationshipType(uNoSQLSchema schema, SchemaType parent, String name,
List<StructuralVariation> variations)
{
RelationshipType newRelationshipType = factory.createRelationshipType(name);
newRelationshipType.getVariations().addAll(variations);
newRelationshipType.getParents().add(parent);
// For each optional structural feature, if all other variations do contain an
// equal feature, then this feature is no longer optional.
for (StructuralVariation v : variations)
for (StructuralFeature f : v.getStructuralFeatures())
if (variations.stream().filter(v2 -> v != v2)
.allMatch(v2 -> v2.getFeatures().stream().anyMatch(f2 -> comparer.compare(f, f2))))
f.setOptional(false);
schema.getRelationships().add(newRelationshipType);
}
}
| true |
9a451d0ad7ed4ce3f08da80d6b5feb10842baf04
|
Java
|
Junni17/WorkSpace
|
/Array Lists/src/team_and_player/Team.java
|
UTF-8
| 1,753 | 3.671875 | 4 |
[] |
no_license
|
package team_and_player;
import java.util.ArrayList;
public class Team {
private String name;
private ArrayList<Player> players;
public Team(String name) {
this.name = name;
this.players = new ArrayList<Player>();
}
public String getName() {
return this.name;
}
public ArrayList<Player> getPlayers() {
return this.players;
}
public void addPlayer(Player p) {
this.players.add(p);
}
public void printPlayers() {
for (Player element : this.players) {
System.out.println(
"Name: " + element.getName() + " - Age: " + element.getAge() + " - Score: " + element.getScore());
}
}
public double calcAverageAge() {
double total = 0;
double count = 0;
for (Player element : this.players) {
total += element.getAge();
count++;
}
return total / count;
}
public int calcTotalScore() {
int total = 0;
for (Player element : this.players) {
total += element.getScore();
}
return total;
}
public int calcOldPlayersScore(int ageLimit) {
int total = 0;
for (Player element : this.players) {
if (element.getAge() > ageLimit) {
total += element.getScore();
}
}
return total;
}
public int maxScore() {
int maxScore = 0;
for (Player element : this.players) {
if (element.getScore() > maxScore) {
maxScore = element.getScore();
}
}
return maxScore;
}
public ArrayList<String> bestPlayerNames() {
ArrayList<String> bestPlayers = new ArrayList<String>();
int maxScore = 0;
for (Player element : this.players) {
if (element.getScore() > maxScore) {
maxScore = element.getScore();
}
}
for (Player element : this.players) {
if (element.getScore() == maxScore) {
bestPlayers.add(element.getName());
}
}
return bestPlayers;
}
}
| true |
9cd7e404368164bfc92bcda93c9154da10ebe24b
|
Java
|
Master-lyt/xiaomishop
|
/src/main/java/com/xm/service/OrderService.java
|
UTF-8
| 263 | 1.601563 | 2 |
[] |
no_license
|
package com.xm.service;
import com.xm.entity.PageBean;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public interface OrderService {
PageBean<HashMap<String, Object>> getAllOrder(String name, int typeid, int page, int pagesize);
}
| true |
ff20f834db6302d0ffd92173431d596e38d0074b
|
Java
|
HPI-Information-Systems/metanome-algorithms
|
/HyMD/util/src/test/java/de/hpi/is/md/util/HashableTest.java
|
UTF-8
| 528 | 2.1875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package de.hpi.is.md.util;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import org.junit.Test;
public class HashableTest {
@Test
public void test() {
HashFunction function = Hashing.goodFastHash(10);
assertThat(Hasher.of(function).put(new TestHashable()).hash())
.isEqualTo(function.newHasher().putUnencodedChars(TestHashable.class.getName()).hash());
}
private static class TestHashable implements Hashable {
}
}
| true |
7ab59cfbdba20e2e52a8a3eea1bb61e43a1efb42
|
Java
|
shulieTech/LinkAgent
|
/instrument-modules/user-modules/module-shadow-job/src/main/java-quartz/org/quartz/JobKey.java
|
UTF-8
| 1,165 | 1.96875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2021 Shulie Technology, Co.Ltd
* Email: [email protected]
* 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,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.quartz;
import org.quartz.utils.Key;
/**
* @Description
* @Author xiaobin.zfb
* @mail [email protected]
* @Date 2020/7/23 8:20 下午
*/
public final class JobKey extends Key<JobKey> {
private static final long serialVersionUID = -6073883950062574010L;
public JobKey(String name) {
super(name, null);
}
public JobKey(String name, String group) {
super(name, group);
}
public static JobKey jobKey(String name) {
return new JobKey(name, null);
}
public static JobKey jobKey(String name, String group) {
return new JobKey(name, group);
}
}
| true |
33cf399427dd925b304f0cb394b83c97e30518b6
|
Java
|
VolxomInc/StandardOperatingProcedures
|
/app/src/main/java/com/gmpsop/standardoperatingprocedures/Helper/UIHelper.java
|
UTF-8
| 577 | 2.09375 | 2 |
[] |
no_license
|
package com.gmpsop.standardoperatingprocedures.Helper;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import java.util.Locale;
/**
* Created by BD1 on 17-Apr-17.
*/
public class UIHelper {
public static Typeface setFontTypeFace(Context context) {
AssetManager am = context.getApplicationContext().getAssets();
Typeface typeface = Typeface.createFromAsset(am,
String.format(Locale.US, "fonts/%s", "century_gothic.ttf"));
return typeface;
}
}
| true |
7482a4042ead55816fca1d588638659521d694eb
|
Java
|
clilystudio/NetBook
|
/allsrc/com/ushaqi/zhuishushenqi/model/ChangeNickNameRoot.java
|
UTF-8
| 765 | 2.265625 | 2 |
[
"Unlicense"
] |
permissive
|
package com.ushaqi.zhuishushenqi.model;
import android.text.TextUtils;
public class ChangeNickNameRoot extends CodeRoot
{
private String[][] codeMap = { { "LV_NOT_ENOUGH", "等级不够" }, { "TOO_LONG", "名字太长" }, { "ILLEGAL_NICKNAME", "不合法的名字" }, { "TOO_OFTEN", "修改间隔少于30天" } };
public String getErrorMessage()
{
if (TextUtils.isEmpty(getCode()))
return "";
for (String[] arrayOfString1 : this.codeMap)
if (arrayOfString1[0].equals(getCode()))
return arrayOfString1[1];
return "更新失败";
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.model.ChangeNickNameRoot
* JD-Core Version: 0.6.0
*/
| true |
73e7e0f91af7ecaee36a46d3f35dea8b4093fad0
|
Java
|
andrewsiew2/Data_Structures_coursework
|
/Umessage/src/p2/wordsuggestor/NGramToNextChoicesMap.java
|
UTF-8
| 3,813 | 3.046875 | 3 |
[] |
no_license
|
package p2.wordsuggestor;
import java.util.Comparator;
import java.util.Iterator; // Can I import?
import java.util.function.Supplier;
import cse332.datastructures.containers.Item;
import cse332.interfaces.misc.Dictionary;
import cse332.misc.LargeValueFirstItemComparator;
import cse332.types.AlphabeticString;
import cse332.types.NGram;
import p2.sorts.*;
public class NGramToNextChoicesMap {
private final Dictionary<NGram, Dictionary<AlphabeticString, Integer>> map;
private final Supplier<Dictionary<AlphabeticString, Integer>> newInner;
public NGramToNextChoicesMap(
Supplier<Dictionary<NGram, Dictionary<AlphabeticString, Integer>>> newOuter,
Supplier<Dictionary<AlphabeticString, Integer>> newInner) {
this.map = newOuter.get();
this.newInner = newInner;
}
/**
* Increments the count of word after the particular NGram ngram.
*/
public void seenWordAfterNGram(NGram ngram, String word) {
AlphabeticString key = new AlphabeticString(word);
Dictionary<AlphabeticString, Integer> innerHolder = this.map.find(ngram);
if (innerHolder == null) {
innerHolder = this.newInner.get();
this.map.insert(ngram, innerHolder);
}
Integer count = innerHolder.find(key);
if (count == null) {
count = Integer.valueOf(0);
}
innerHolder.insert(key, Integer.sum(1, count));
}
/**
* Returns an array of the DataCounts for this particular ngram. Order is
* not specified.
*
* @param ngram
* the ngram we want the counts for
*
* @return An array of all the Items for the requested ngram.
*/
public Item<String, Integer>[] getCountsAfter(NGram ngram) {
Dictionary<AlphabeticString, Integer> innerMap = this.map.find(ngram);
if (innerMap == null) {
return (Item<String, Integer>[]) new Item[0];
}
Item<String, Integer>[] result = (Item<String, Integer>[]) new Item[innerMap.size()];
Iterator<Item<AlphabeticString, Integer>> loopIterator = innerMap.iterator();
int i = 0;
while (loopIterator.hasNext()) {
Item<AlphabeticString, Integer> referenceItem = loopIterator.next();
Item<String, Integer> element = new Item(referenceItem.key.toString(), referenceItem.value);
result[i] = element;
i++;
}
return result;
}
public String[] getWordsAfter(NGram ngram, int k) {
Item<String, Integer>[] afterNGrams = getCountsAfter(ngram);
Comparator<Item<String, Integer>> comp = new NewComparator<String, Integer>();
if (k < 0) {
HeapSort.sort(afterNGrams, comp);
}
else {
TopKSort.sort(afterNGrams, k, comp.reversed());
HeapSort.sort(afterNGrams,comp);
}
String[] nextWords = new String[k < 0 ? afterNGrams.length : k];
for (int l = 0; l < afterNGrams.length && l < nextWords.length
&& afterNGrams[l] != null; l++) {
nextWords[l] = afterNGrams[l].key;
}
return nextWords;
}
public static class NewComparator<K extends Comparable<K>, V extends Comparable<V>> extends LargeValueFirstItemComparator<K,V>{
@Override
public int compare(Item<K, V> e1, Item<K, V> e2) {
if (e1 != null && e2 != null) {
return super.compare(e1, e2);
} else if (e1 != null && e2 == null) {
return -1;
} else if (e1 == null && e2 != null) {
return 1;
}
return 0;
}
}
@Override
public String toString() {
return this.map.toString();
}
}
| true |
21c5dce1778b8b3e83da36b500ca3c96d504657c
|
Java
|
Talend/apache-camel
|
/core/camel-management/src/test/java/org/apache/camel/management/ManagedProducerRouteAddRemoveRegisterAlwaysTest.java
|
UTF-8
| 4,512 | 1.90625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.management;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import static org.apache.camel.management.DefaultManagementObjectNameStrategy.TYPE_PRODUCER;
import static org.apache.camel.management.DefaultManagementObjectNameStrategy.TYPE_SERVICE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@DisabledOnOs(OS.AIX)
public class ManagedProducerRouteAddRemoveRegisterAlwaysTest extends ManagementTestSupport {
private static final int SERVICES = 14;
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
context.getManagementStrategy().getManagementAgent().setRegisterAlways(true);
return context;
}
@Test
public void testRouteAddRemoteRouteWithRecipientList() throws Exception {
MockEndpoint result = getMockEndpoint("mock:result");
result.expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
result.assertIsSatisfied();
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = getCamelObjectName(TYPE_SERVICE, "*");
// number of services
Set<ObjectName> names = mbeanServer.queryNames(on, null);
assertEquals(SERVICES, names.size());
// number of producers
ObjectName onP = getCamelObjectName(TYPE_PRODUCER, "*");
Set<ObjectName> namesP = mbeanServer.queryNames(onP, null);
assertEquals(3, namesP.size());
log.info("Adding 2nd route");
// add a 2nd route
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:bar").routeId("bar").recipientList(header("bar"));
}
});
// and send a message to it
MockEndpoint bar = getMockEndpoint("mock:bar");
bar.expectedMessageCount(1);
template.sendBodyAndHeader("direct:bar", "Hello World", "bar", "mock:bar");
bar.assertIsSatisfied();
// there should still be the same number of services
names = mbeanServer.queryNames(on, null);
assertEquals(SERVICES, names.size());
// but as its recipient list which is dynamic-to we add new producers because we have register always
namesP = mbeanServer.queryNames(onP, null);
assertEquals(5, namesP.size());
log.info("Removing 2nd route");
// now remove the 2nd route
context.getRouteController().stopRoute("bar");
boolean removed = context.removeRoute("bar");
assertTrue(removed);
// there should still be the same number of services
names = mbeanServer.queryNames(on, null);
assertEquals(SERVICES, names.size());
// and we still have the other producers, but not the one from the 2nd route that was removed
namesP = mbeanServer.queryNames(onP, null);
assertEquals(4, namesP.size());
log.info("Shutting down...");
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").routeId("foo").to("log:foo").to("mock:result");
}
};
}
}
| true |
525c539b62441fc8db1cff542b39e9cf96de9761
|
Java
|
choudharyabhinav15/Springular
|
/server/src/main/java/com/mediatheque/service/LocalisationService.java
|
UTF-8
| 405 | 1.890625 | 2 |
[
"MIT"
] |
permissive
|
package com.mediatheque.service;
import com.mediatheque.model.Localisation;
import java.util.List;
/**
* @Author Ghiles FEGHOUL
* @Date 27/01/2018
* @Licence MIT
*/
public interface LocalisationService {
Localisation find(Long id);
Localisation save(Localisation localisation);
Localisation update(Localisation localisation);
List<Localisation> findAll();
void remove(Long id);
}
| true |
2117f6b0cb9474da9c9ddfe0043ba1ee1a148e4d
|
Java
|
khansaifullah/PizzaOmoreDesktopAppV1.0
|
/src/com/PrintUtility/MyCellRenderer.java
|
UTF-8
| 1,175 | 3 | 3 |
[] |
no_license
|
package com.PrintUtility;
import javax.swing.*;
import java.awt.*;
/**
* Created by DELL on 2/6/2018.
*/
class MyCellRenderer extends DefaultListCellRenderer {
//final static ImageIcon longIcon = new ImageIcon("long.gif");
//final static ImageIcon shortIcon = new ImageIcon("short.gif");
/* This is the only method defined by ListCellRenderer. We just
* reconfigure the Jlabel each time we're called.
*/
public Component getListCellRendererComponent(
JList list,
Object value, // value to display
int index, // cell index
boolean iss, // is the cell selected
boolean chf) // the list and the cell have the focus
{
/* The DefaultListCellRenderer class will take care of
* the JLabels text property, it's foreground and background
* colors, and so on.
*/
super.getListCellRendererComponent(list, value, index, iss, chf);
/* We additionally set the JLabels icon property here.
*/
// String s = value.toString();
//setIcon((s.length > 10) ? longIcon : shortIcon);
return this;
}
}
| true |
e0092c3b3ec276bb0faba4457d77b74f1e74554e
|
Java
|
arnabs542/leetcode-problems
|
/array/hard/longest_consecutive_sequence_128/HashMapSolution.java
|
UTF-8
| 3,174 | 4.09375 | 4 |
[] |
no_license
|
package array.hard.longest_consecutive_sequence_128;
import java.util.HashMap;
import java.util.Map;
/**
128. Longest Consecutive Sequence
https://leetcode.com/problems/longest-consecutive-sequence/
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
--------
1. Complexity
1.1 Time Complexity is O(n)
1.2 Space Complexity is O(n)
2. Approach
2.1 Use hashmap to track boundaries for every number. After updatingthe number with boundaries,
also update boundary numbers with new left or right value, so boundaries are always set
in first and last numbers
*/
class HashMapSolution {
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int max = 0;
Map<Integer, int[]> map = new HashMap<>();
for (int num : nums) {
if (map.containsKey(num)) {
continue;
}
int leftBoundary = num;
if (num > Integer.MIN_VALUE && map.containsKey(num - 1)) {
int[] left = map.get(num - 1);
leftBoundary = left[0];
}
int rightBoundary = num;
if (num < Integer.MAX_VALUE && map.containsKey(num + 1)) {
int[] right = map.get(num + 1);
rightBoundary = right[1];
}
map.put(num, new int[]{leftBoundary, rightBoundary});
if (leftBoundary != num) {
int[] left = map.get(leftBoundary);
left[1] = rightBoundary;
map.put(leftBoundary, left);
}
if (rightBoundary != num) {
int[] right = map.get(rightBoundary);
right[0] = leftBoundary;
map.put(rightBoundary, right);
}
max = Math.max(max, rightBoundary - leftBoundary + 1);
}
return max;
}
}
/**
1. Naive approach: Sort and interate numbers
O(nlogn)
2. Use hashmap to track boundaries
- Use hashmap with arrays where:
0: leftBoundary
1: rightBoundary
- Iterate over the list:
- for every number get the "-1" value
- if it is null - set left boundary to itself
- otherwise - set "-1" left boundary to current left boundary
- get "+1" value
- if null -> set left boundary to itself
- otherwise - set "+1" right boundary to the current right boundary
if curr left boundary != number -> set left boundary . right the current right value
if curr right boundary != number -> set right boundary . left the current left value
get the max as (right - left + 1)
[100:[100:100], 4:[3:4], 200:[200:200], 1:[1:1], 3:[3:4], 2:[1:4]]
[-1,9,-3,-6,7,-8,-6,2,9,2,3,-2,4,-1,0,6,1,-9,6,8,6,5,2]
9
*/
| true |
2933d768c31402b3a20b90def90616fc70b377c8
|
Java
|
FrankRays/college-events-management-system
|
/src/com/buzz/serviceimpl/FaqSerivceImpl.java
|
UTF-8
| 1,688 | 2.421875 | 2 |
[] |
no_license
|
package com.buzz.serviceimpl;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import com.buzz.bean.BranchBean;
import com.buzz.bean.FaqsBean;
import com.buzz.dao.BranchDAO;
import com.buzz.dao.FaqsDAO;
import com.buzz.exception.CommonException;
import com.buzz.exception.ConnectionException;
import com.buzz.pojo.Branch;
import com.buzz.pojo.Faqs;
public class FaqSerivceImpl {
FaqsDAO faqsDAO = new FaqsDAO();
public void addFaqs(FaqsBean faqsBean) throws CommonException {
Faqs faqs = new Faqs(faqsBean);
faqsDAO.save(faqs);
}
public boolean faqsUpdatebyid(FaqsBean faqsBean) throws CommonException,
ConnectionException {
Faqs Faqs = new Faqs(faqsBean);
return faqsDAO.attachDirty(Faqs);
}
public Vector<FaqsBean> viewFaqs() throws CommonException {
Faqs faqs = null;
FaqsBean faqsBean = null;
Vector<FaqsBean> vFaqsBeans = new Vector<FaqsBean>();
try {
List list = faqsDAO.findAll();
for (Iterator it = list.iterator(); it.hasNext();) {
faqs = (Faqs) it.next();
faqsBean = new FaqsBean(faqs);
vFaqsBeans.add(faqsBean);
}
} catch (Exception e) {
System.out.println(e);
}
return vFaqsBeans;
}
public FaqsBean viewFaqsbyId(int id) throws CommonException {
Faqs Faqs = null;
FaqsBean faqsBean = null;
try {
Faqs = faqsDAO.findById(id);
faqsBean = new FaqsBean(Faqs);
} catch (Exception e) {
System.out.println(e);
}
return faqsBean;
}
public boolean deleteFaqs(int parseInt) throws CommonException {
try {
Faqs Faqs = faqsDAO.findById(parseInt);
faqsDAO.delete(Faqs);
return true;
} catch (Exception e) {
System.out.println(e);
return false;
}
}
}
| true |
96bb4f4570e59f3046e963699213889b8d037f38
|
Java
|
Gingmin/springboot-mybatis-test
|
/src/main/java/com/example/demo/security/MemberService.java
|
UTF-8
| 3,130 | 2.5 | 2 |
[] |
no_license
|
package com.example.demo.security;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.model.dao.MemberMapper;
import com.example.demo.model.dto.MemberDTO;
@Service("memberService")
public class MemberService implements UserDetailsService {
private PasswordEncoder passwordEncoder;
private MemberMapper memberMapper;
@Autowired
public MemberService(PasswordEncoder passwordEncoder, MemberMapper memberMapper) {
this.passwordEncoder = passwordEncoder;
this.memberMapper = memberMapper;
}
@Override
/* 상세정보를 조회, 사용자의 계정정보와 권한을 갖는 UserDetails 인터페이스를 반환해아 한다.
* 매개변수는 로그인 시 입력한 아이디, 엔티티 PK가 아니라 유저를 식별할 수 있는 어떤 값을 의미 spring security에서는
* username라는 이름으로 사용, 여기서는 id가 id 로그인하는 form에서 name="username" 으로 요청해야 함
* authorities.add(new SimpleGrantedAuthority() 롤 부여하는 코드, 방식에는 여러가지가 있지만
* 회원가입할 때 role을 정할 수 있도록 role entity를 만들어서 매핑해주는 것이 좋은 방법
* 여기서는 "admin"일 경우에 ADMIN 권한 부여
* new User()
* return은 spring security에서 제공하는 UserDetails를 구현한 User를 반환(org.springframework.security
* .core.user.details.User
* 생성자의 매개변수는 순서대로 아이디, 비밀번호, 권한리스트 */
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
MemberDTO memberDTO = memberMapper.findByEmail(username);
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add((GrantedAuthority) memberMapper.readAuthority(username));
memberDTO.setAuthorities(authorities);
// authorities.add(new SimpleGrantedAuthority(memberDTO.getAuthorities());
return new User(memberDTO.getId(), memberDTO.getPwd(), memberDTO.getAuthorities());
}
/* JPA 회원가입을 처리하는 메서드 비밀번호를 암호화하여 저장 */
// @Transactional
// public Long joinUser(MemberDTO memberDTO) {
// BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// memberDTO.setPwd(passwordEncoder.encode(memberDTO.getPwd()));
//
// return memberRepository.save(memberDTO.toEntity()).getNo();
// }
}
| true |
14a21e5dd40a3c9541b7e1b0329f34fc050bdab4
|
Java
|
natanaelsantosbr/android-tcc-bolso-casal
|
/app/src/main/java/br/android/bolsocasalapp/usuario/servicos/ICallbackBuscarIdDoCasal.java
|
UTF-8
| 189 | 1.859375 | 2 |
[] |
no_license
|
package br.android.bolsocasalapp.usuario.servicos;
public interface ICallbackBuscarIdDoCasal {
void onSucesso(boolean retorno, String idDoCasal) ;
void onErro(String mensagem);
}
| true |
86be27ac0b49242a1413d613875c1b2bd7c85352
|
Java
|
igorsan98v2/RandomUsers
|
/app/src/main/java/com/ygs/netronic/repositories/impl/RandomUsersRepositoryImpl.java
|
UTF-8
| 6,535 | 2.0625 | 2 |
[] |
no_license
|
package com.ygs.netronic.repositories.impl;
import android.content.Context;
import android.database.SQLException;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.ygs.netronic.annotations.NetworkType;
import com.ygs.netronic.converters.JsonResponseToInstanceConverter;
import com.ygs.netronic.database.AppDatabase;
import com.ygs.netronic.database.DatabaseManager;
import com.ygs.netronic.database.RandomUserDatabase;
import com.ygs.netronic.database.entities.Location;
import com.ygs.netronic.database.entities.PictureUrl;
import com.ygs.netronic.database.entities.User;
import com.ygs.netronic.database.samples.UserRowSample;
import com.ygs.netronic.models.network.response.UserResponseModel;
import com.ygs.netronic.models.ui.UserRowModel;
import com.ygs.netronic.repositories.interfaces.RandomUsersRepository;
import com.ygs.netronic.repositories.interfaces.UserApiRepository;
import androidx.annotation.NonNull;
import io.reactivex.observers.DisposableCompletableObserver;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.sql.SQLDataException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.Completable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Response;
public final class RandomUsersRepositoryImpl implements RandomUsersRepository {
private static final RandomUsersRepositoryImpl mInstance = new RandomUsersRepositoryImpl();
private final UserApiRepository mRepository = new UserApiRepositoryImpl();
private final AtomicBoolean mInUpdate = new AtomicBoolean(false);
MutableLiveData<List<UserRowModel>> mData = new MutableLiveData<>();
private Executor executor = (runnable) -> new Thread(runnable).start();
private AppDatabase mDatabase;
private ConnectivityManager mManager;
private RandomUsersRepositoryImpl() {
}
@Override
public LiveData<List<UserRowModel>> getUsersList(int usersCount) {
runInCompletable(() -> {
if (!mInUpdate.get()) {
mInUpdate.set(true);
updateDatabase(mDatabase, usersCount);
List<UserRowSample> samples = mDatabase.userDao().selectRowSamples().blockingGet();
List<UserRowModel> rows = samples.stream().map(UserRowSample::mapToUserRowModel).collect(Collectors.toList());
mData.postValue(rows);
mInUpdate.compareAndSet(true, false);
}
});
return mData;
}
@Override
public LiveData<List<UserRowModel>> getOfflineUsersList() {
runInCompletable(() -> {
if (!mInUpdate.get()) {
AppDatabase database = DatabaseManager.getInstance().getCurrentDatabase();
List<UserRowSample> samples = database.userDao().selectRowSamples().blockingGet();
List<UserRowModel> rows = samples.stream().map(UserRowSample::mapToUserRowModel).collect(Collectors.toList());
mData.postValue(rows);
}
});
return mData;
}
private UserResponseModel convertToResponseModel(JsonObject jsonObject) {
return JsonResponseToInstanceConverter
.convertToInstance(jsonObject, UserResponseModel.class);
}
private void updateDatabase(@NonNull final AppDatabase database, int usersCount) {
if (isInternetAvailable()) {
try {
database.userDao().clear().blockingAwait();
List<Location> locations = new LinkedList();
List<PictureUrl> pictureUrls = new LinkedList();
Response<JsonElement> response = mRepository.getUsers(usersCount).execute();
if (response.isSuccessful() && response.body() instanceof JsonObject) {
UserResponseModel model = convertToResponseModel((JsonObject) response.body());
List<UserResponseModel.UserData> userDataList = model.userDataList;
userDataList.forEach(userData -> {
database.runInTransaction(() -> {
User user = (User) userData.mapToLocal();
long userId = database.userDao().insert(user).blockingGet();
userData.location.appendToLocalList(userId, locations);
userData.picture.appendToLocalList(userId, pictureUrls);
}
);
});
database.locationDao().insert(locations).blockingGet();
database.pictureUrlDao().insert(pictureUrls).blockingGet();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static RandomUsersRepository getInstance(Context context) {
if (DatabaseManager.getInstance().getCurrentDatabase() == null) {
mInstance.mManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
AppDatabase database = RandomUserDatabase.getInstance(context);
DatabaseManager.getInstance().setCurrentDatabase(database);
mInstance.mDatabase = database;
}
return mInstance;
}
private void runInCompletable(Runnable runnable) {
Completable.fromRunnable(runnable)
.subscribeOn(Schedulers.io())
.subscribe();
}
private boolean isInternetAvailable() {
return mInstance.isInternetAvailable(NetworkType.CELLULAR) ||
mInstance.isInternetAvailable(NetworkType.WIFI);
}
private boolean isInternetAvailable(int type) {
Network[] networks = mManager.getAllNetworks();
for (Network network : networks) {
NetworkInfo info = mManager.getNetworkInfo(network);
NetworkCapabilities capabilities = mManager.getNetworkCapabilities(network);
if ((info != null) && info.isConnected() &&
(capabilities != null) && capabilities.hasTransport(type)) {
return true;
}
}
return false;
}
}
| true |
826eeb3f702fe2ecf439acd6c8a37fb32622ed45
|
Java
|
Mr-Yeliang/SignIn
|
/SignIn/src/main/java/com/example/entity/Student.java
|
UTF-8
| 756 | 2.671875 | 3 |
[] |
no_license
|
package com.example.entity;
import java.io.Serializable;
public class Student implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 姓名
*/
private String name;
/**
* 签到状态
*/
private boolean state;
public Student() {
}
public Student(String name, boolean state) {
this.name = name;
this.state = state;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean getState() {
return state;
}
public void setState(boolean state) {
this.state = state;
}
@Override
public String toString() {
return "Student [name=" + name + ", state=" + state + "]";
}
}
| true |
25de3b1c3a745f93bdb9cdab24cc6e47527926b3
|
Java
|
hiyoo/HiyooWeb
|
/src/com/hiyoo/test/TestUser.java
|
GB18030
| 928 | 2.375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.hiyoo.test;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.hiyoo.domain.SystemPermission;
import com.hiyoo.domain.User;
import com.hiyoo.service.impl.UserServiceImpl;
public class TestUser {
public static void main(String[] args) {
byte i=127;
System.out.println(i);
SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=new Date(); //ȡһDate
String punchTime = f.format(date); //ʽʱ
System.out.println(punchTime);
User user=new User();
user.setUid("10000001");
user.setPwd("123456");
UserServiceImpl service=new UserServiceImpl(user);
service.login();
for(int j=0;j<user.getPermission().size();j++) {
System.out.println("id:"+((SystemPermission)user.getPermission().get(j)).getMenu_id()+
" iQuery:"+((SystemPermission)user.getPermission().get(j)).getiQuery());
}
}
}
| true |
88d959f37547fdc0af44a71f58031039cbeac168
|
Java
|
IBMPCjr/Metalurgy
|
/java/com/ThatKerbonaut/VanillaPlusMore/util/handlers/TileEntityHandler.java
|
UTF-8
| 509 | 2.046875 | 2 |
[] |
no_license
|
package com.ThatKerbonaut.VanillaPlusMore.util.handlers;
import com.ThatKerbonaut.VanillaPlusMore.blocks.ballmill.TileEntityBallMill;
import com.ThatKerbonaut.VanillaPlusMore.util.Reference;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class TileEntityHandler {
public static void registerTileEntities(){
GameRegistry.registerTileEntity(TileEntityBallMill.class, new ResourceLocation(Reference.MOD_ID + ":ball_mill"));
}
}
| true |
e2202501881c321c1bf0e337beec699c5f03120c
|
Java
|
KartikPatelOfficial/BillMK
|
/app/src/main/java/com/deucate/kartik/billmk/Spent/SpentAdapter.java
|
UTF-8
| 2,308 | 2.21875 | 2 |
[] |
no_license
|
package com.deucate.kartik.billmk.Spent;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.deucate.kartik.billmk.R;
import java.util.List;
public class SpentAdapter extends ArrayAdapter<SpentGs> {
String type;
public SpentAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<SpentGs> objects) {
super(context, resource, objects);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if (convertView==null){
convertView = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.spent_list,parent,false);
}
TextView rsTv = convertView.findViewById(R.id.listSpentRS);
TextView dateTv = convertView.findViewById(R.id.listSpentDate);
TextView timeTv = convertView.findViewById(R.id.listSpentTime);
TextView reasonTv = convertView.findViewById(R.id.listSpentReason);
ImageView imageView = convertView.findViewById(R.id.listSpentImage);
SpentGs spentGs = getItem(position);
assert spentGs != null;
switch (spentGs.getCategory()){
case 0:{
imageView.setImageResource(R.drawable.electronic);
}break;
case 1:{
imageView.setImageResource(R.drawable.food);
}break;
case 2:{
imageView.setImageResource(R.drawable.cloths);
}break;
case 3:{
imageView.setImageResource(R.drawable.grocery);
}break;
case 4:{
imageView.setImageResource(R.drawable.bill);
}break;
case 5:{
imageView.setImageResource(R.drawable.other);
}break;
}
rsTv.setText(spentGs.getRs()+"");
dateTv.setText(spentGs.getDate());
timeTv.setText(spentGs.getTime());
reasonTv.setText(spentGs.getReason());
return convertView;
}
}
| true |
6e20dbe608c5e5efc716933e8a4992fe952c0de5
|
Java
|
thanhtung1993/CTT2019
|
/app/src/main/java/com/example/ctt2019/Adapter/AdapterLichSu/AdapterLichSuNapTien.java
|
UTF-8
| 3,864 | 2.1875 | 2 |
[] |
no_license
|
package com.example.ctt2019.Adapter.AdapterLichSu;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.ctt2019.Model.Lichsunaptien.ModelLichSuNapTien;
import com.example.ctt2019.R;
import java.util.List;
public class AdapterLichSuNapTien extends RecyclerView.Adapter {
private List<ModelLichSuNapTien> LichSuNapTienList;
private Context context;
public AdapterLichSuNapTien(List<ModelLichSuNapTien> lichSuNapTienList, Context context) {
this.LichSuNapTienList = lichSuNapTienList;
this.context = context;
}
public class RowViewHolder extends RecyclerView.ViewHolder
{
protected TextView txtSTT;
protected TextView txtNgay;
protected TextView txtSoTien;
protected TextView txtTrangThai;
public RowViewHolder(@NonNull View itemView) {
super(itemView);
txtSTT=itemView.findViewById(R.id.txtSTTLichSuNapTien);
txtNgay=itemView.findViewById(R.id.txtNgay);
txtSoTien=itemView.findViewById(R.id.txtSoTien);
txtTrangThai=itemView.findViewById(R.id.txtTrangThai);
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.table_list_itemnaptien,viewGroup,false);
return new RowViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
RowViewHolder rowViewHolderNapTien= (RowViewHolder) viewHolder;
int row=rowViewHolderNapTien.getAdapterPosition();
if (row ==0)
{
rowViewHolderNapTien.txtSTT.setBackgroundResource(R.drawable.table_header_cell_bg);
rowViewHolderNapTien.txtNgay.setBackgroundResource(R.drawable.table_header_cell_bg);
rowViewHolderNapTien.txtSoTien.setBackgroundResource(R.drawable.table_header_cell_bg);
rowViewHolderNapTien.txtTrangThai.setBackgroundResource(R.drawable.table_header_cell_bg);
rowViewHolderNapTien.txtSTT.setText("STT");
rowViewHolderNapTien.txtNgay.setText("Ngày");
rowViewHolderNapTien.txtSoTien.setText("Số tiền");
rowViewHolderNapTien.txtTrangThai.setText("Trạng thái");
}
else
{
ModelLichSuNapTien model=LichSuNapTienList.get(row-1);
rowViewHolderNapTien.txtSTT.setBackgroundResource(R.drawable.table_content_cell_bg);
rowViewHolderNapTien.txtNgay.setBackgroundResource(R.drawable.table_content_cell_bg);
rowViewHolderNapTien.txtSoTien.setBackgroundResource(R.drawable.table_content_cell_bg);
rowViewHolderNapTien.txtTrangThai.setBackgroundResource(R.drawable.table_content_cell_bg);
try {
rowViewHolderNapTien.txtSTT.setText(model.getSTT());
rowViewHolderNapTien.txtNgay.setText(model.getDATE_LOG());
rowViewHolderNapTien.txtSoTien.setText(model.getTOTAL_AMOUNT());
if (model.getRESULT().equals("Thành công"))
{
rowViewHolderNapTien.txtTrangThai.setText("Thành công");
}
else
{rowViewHolderNapTien.txtTrangThai.setText("Thất bại");}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
@Override
public int getItemCount() {
return LichSuNapTienList.size()+1;
}
}
| true |
d19522989787c11c4737bcd115663df5bb198118
|
Java
|
CruGlobal/opendq-ws-client
|
/src/test/java/org/ccci/obiee/client/init/ServiceFactoryTest.java
|
UTF-8
| 1,467 | 1.804688 | 2 |
[] |
no_license
|
package org.ccci.obiee.client.init;
import com.infosolve.openmdm.webservices.provider.impl.DataManagementWSImpl;
import com.infosolve.openmdm.webservices.provider.impl.DataManagementWSImplService;
import com.infosolve.openmdm.webservices.provider.impl.RealTimeObjectActionDTO;
import com.infosolvetech.rtmatch.pdi4.RuntimeMatchWS;
import com.infosolvetech.rtmatch.pdi4.RuntimeMatchWSService;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import plugin.com.infosolvetech.ap.di.pdi4.AddressWS;
import plugin.com.infosolvetech.ap.di.pdi4.AddressWSService;
import plugin.org.pentaho.di.drools.jboss.pdi4.DroolsPluginWSService;
public class ServiceFactoryTest
{
ServiceFactory factory;
@BeforeMethod
public void setup()
{
factory = new ServiceFactory();
}
@Test
public void testDataManagementWSImplServiceCreation()
{
factory.buildService(DataManagementWSImplService.class).getDataManagementWSImplPort();
}
@Test
public void testRuntimeMatchWSServiceCreation()
{
factory.buildService(RuntimeMatchWSService.class).getRuntimeMatchWSPort();
}
@Test
public void testAddressWSServiceCreation()
{
factory.buildService(AddressWSService.class).getAddressWSPort();
}
@Test
public void testDroolsPluginWSServiceCreation()
{
factory.buildService(DroolsPluginWSService.class).getDroolsPluginWSPort();
}
}
| true |
d90d2e9dc5886c268d37c27548330a3164fd8afb
|
Java
|
15539158137/TestBoxDesign
|
/app/src/main/java/com/example/administrator/testboxdesign/MainActivity.java
|
UTF-8
| 180,121 | 2.0625 | 2 |
[] |
no_license
|
package com.example.administrator.testboxdesign;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.example.administrator.testboxdesign.beans.OneBoxItem;
import com.zhy.android.percent.support.PercentRelativeLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
//当前右侧绘图区域的所有box
List<OneBoxItem> allBox;
@BindView(R.id.i1)
ImageView i1;
@BindView(R.id.i2)
ImageView i2;
@BindView(R.id.i3)
ImageView i3;
@BindView(R.id.i4)
ImageView i4;
@BindView(R.id.i5)
ImageView i5;
@BindView(R.id.i6)
ImageView i6;
@BindView(R.id.i7)
ImageView i7;
@BindView(R.id.i8)
ImageView i8;
@BindView(R.id.i9)
ImageView i9;
@BindView(R.id.i10)
ImageView i10;
@BindView(R.id.i11)
ImageView i11;
@BindView(R.id.example_onebox)
ImageView example;
@BindView(R.id.box_one)
ImageView touch1;
//右侧的画图区域
@BindView(R.id.drawview)
PercentRelativeLayout drawView;
@BindView(R.id.main)
PercentRelativeLayout mainView;
@OnClick(R.id.next)
void next(){
SaveUtilS.allBox=new ArrayList<OneBoxItem>();
SaveUtilS.allBox.addAll(allBox);
SaveUtilS.Temp="123";
startActivity(new Intent(MainActivity.this,NextActivity.class));
}
/*不管是左侧实例的拖拽还是右侧实际表箱的拖拽,这个拖拽所操作的虚拟的view 都是新增的;down的时候添加,up的时候删除这个虚拟的
*
*对于跳转到下一页,需要保存本页的设置:每个表箱 给予他左上角在坐标系中的坐标;单个表箱的每个格子,给予他所在这个表箱的编号,这个编号统一是自左往右,自上往下数..对于同一个表箱 的不同格子,他的nowTime数值是相同的.
* 所以在遍历时候拿到type,再找出time相同的,再找出是第一个的,就可以了.
* */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(MainActivity.this);
initView();
}
//左侧实例的宽高
int ExampleWidth;
int ExampleHeight;
int BoxWidth;
int BoxHeight;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
boolean hadGet;//是否已经获取到尺寸了,获取到了之后就不需要
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hadGet == false) {
//实际需要添加的大小
BoxWidth = touch1.getRight() - touch1.getLeft();
BoxHeight = touch1.getBottom() - touch1.getTop();
//左侧例子的大小
ExampleWidth = example.getRight() - example.getLeft();
ExampleHeight = example.getBottom() - example.getTop();
//对画布区域进行分格子处理
//以区域的左上角的坐标原点
//先获取右侧区域的坐标,
float x = drawView.getLeft();
float y = drawView.getTop();
//再获取右侧区域的大小
float width = drawView.getRight() - drawView.getLeft();
float height = drawView.getBottom() - drawView.getTop();
//对于这个区域,需要一个边沿的空白,这个区域的大小为左侧实例box的1/4宽,及examplewidth/4.实例的宽度为百分之五宽度,右侧绘图区域的大小是百分之8
//算出在X,Y方向上所能容纳的个数
double temp = ((width - ExampleWidth / 2) / BoxWidth);
double temp1 = (height - ExampleHeight / 2) / BoxHeight;
Log.e("横向上可以容纳的数量",temp+"");
int X_canuse = splitDouble(temp);
Log.e("横向上可以容纳的数量-实际",X_canuse+"");
int Y_canuse = splitDouble(temp1);
//从左往右,横向的加
//因为存在留白区域,所以对于实际显示区域的起始坐标,需要计算下
double startX = x + (ExampleWidth / 4);
double startY = y + (ExampleHeight / 4);
for (int i = 0; i < Y_canuse; i++) {
for (int j = 0; j < X_canuse; j++) {
//从第一行的第一个开始,向右走,然后第二行...
OneBoxItem oneBoxItem = new OneBoxItem();
//这里的j表示从左往右的第几行
oneBoxItem.setX(startX + BoxWidth * j);
//这里的i表示从上网下的第几列
oneBoxItem.setY(startY + BoxHeight * i);
oneBoxItem.setID(i + "s" + j);
if (allBox == null || allBox.size() == 0) {
allBox = new ArrayList<OneBoxItem>();
}
ImageView uu = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth ;
layoutParams.height = BoxHeight;
uu.setAlpha(0.1f);
uu.setLayoutParams(layoutParams);
uu.setX((float) oneBoxItem.getX());
uu.setY((float) oneBoxItem.getY());
uu.setBackground(getResources().getDrawable(R.drawable.i1x1));
mainView.addView(uu);
allBox.add(oneBoxItem);
}
}
//设置完毕后置空
hadGet = true;
} else {
}
}
/**
* 这个是左侧区域的拖拽处理===左侧===左侧===左侧===左侧===左侧===左侧===左侧===左侧===左侧===左侧===左侧===左侧===左侧===左侧===左侧===左侧===左侧===左侧
*/
//这个imageview是在拖拽的时候显示的图片,设置完毕这个就删除了
ImageView showImage_Left;
private void setTouchEvent_Left(View imageview_left, final String boxType) {
imageview_left.setOnTouchListener(new View.OnTouchListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
showImage_Left = new ImageView(MainActivity.this);
showImage_Left.setAlpha(0.3f);
PercentRelativeLayout.LayoutParams layoutParamsShow = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//对不同的表箱类型进行判断
if (boxType.equals(BoxTypes.Old_1_X)) {
layoutParamsShow.width = ExampleWidth;
layoutParamsShow.height = ExampleHeight;
showImage_Left.setLayoutParams(layoutParamsShow);
showImage_Left.setBackground(getResources().getDrawable(R.drawable.i1x1));
} else if (boxType.equals(BoxTypes.Old_A_New_2_X)) {
//横向双表
layoutParamsShow.width = ExampleWidth * 2;
layoutParamsShow.height = ExampleHeight;
showImage_Left.setLayoutParams(layoutParamsShow);
showImage_Left.setBackground(getResources().getDrawable(R.drawable.i1x2));
} else if (boxType.equals(BoxTypes.Old_2_Y)) {
//纵向双表
layoutParamsShow.width = ExampleWidth;
layoutParamsShow.height = ExampleHeight * 2;
showImage_Left.setLayoutParams(layoutParamsShow);
showImage_Left.setBackground(getResources().getDrawable(R.drawable.i2x1));
} else if (boxType.equals(BoxTypes.Old_A_New_3_X)) {
//横向的3表
layoutParamsShow.width = ExampleWidth * 3;
layoutParamsShow.height = ExampleHeight;
showImage_Left.setLayoutParams(layoutParamsShow);
showImage_Left.setBackground(getResources().getDrawable(R.drawable.i1x3));
}else if (boxType.equals(BoxTypes.Old_A_New_3_Y)) {
//纵向的3表
layoutParamsShow.width = ExampleWidth ;
layoutParamsShow.height = ExampleHeight*3;
showImage_Left.setLayoutParams(layoutParamsShow);
showImage_Left.setBackground(getResources().getDrawable(R.drawable.i3x1));
}else if(boxType.equals(BoxTypes.New_4_Y)){
//纵行的四表
layoutParamsShow.width = ExampleWidth ;
layoutParamsShow.height = ExampleHeight*4;
showImage_Left.setLayoutParams(layoutParamsShow);
showImage_Left.setBackground(getResources().getDrawable(R.drawable.i4x1));
}else if(boxType.equals(BoxTypes.New_4_X)){
//纵行的四表
layoutParamsShow.width = ExampleWidth*4 ;
layoutParamsShow.height = ExampleHeight;
showImage_Left.setLayoutParams(layoutParamsShow);
showImage_Left.setBackground(getResources().getDrawable(R.drawable.i1x4));
} else if(boxType.equals(BoxTypes.New_4_XY)){
//纵行的四表
layoutParamsShow.width = ExampleWidth*2 ;
layoutParamsShow.height = ExampleHeight*2;
showImage_Left.setLayoutParams(layoutParamsShow);
showImage_Left.setBackground(getResources().getDrawable(R.drawable.i2x2));
}else if(boxType.equals(BoxTypes.Old_A_New_6_Y)){
//纵行的四表
layoutParamsShow.width = ExampleWidth*2 ;
layoutParamsShow.height = ExampleHeight*3;
showImage_Left.setLayoutParams(layoutParamsShow);
showImage_Left.setBackground(getResources().getDrawable(R.drawable.i3x2));
}else if(boxType.equals(BoxTypes.Old_6_X)){
//纵行的四表
layoutParamsShow.width = ExampleWidth*3 ;
layoutParamsShow.height = ExampleHeight*2;
showImage_Left.setLayoutParams(layoutParamsShow);
showImage_Left.setBackground(getResources().getDrawable(R.drawable.i2x3));
}else if(boxType.equals(BoxTypes.Old_A_New_9_XY)){
//纵行的四表
layoutParamsShow.width = ExampleWidth*3 ;
layoutParamsShow.height = ExampleHeight*3;
showImage_Left.setLayoutParams(layoutParamsShow);
showImage_Left.setBackground(getResources().getDrawable(R.drawable.i3x3));
}
showImage_Left.setX(event.getRawX() - layoutParamsShow.width / 2);
showImage_Left.setY(event.getRawY() - layoutParamsShow.height / 2);
mainView.addView(showImage_Left);
break;
case MotionEvent.ACTION_MOVE:
//让这个屏幕上左侧例子的另一个副本进行位置变换
//对不同的表箱类型进行判断
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) showImage_Left.getLayoutParams();
showImage_Left.setX((float) (event.getRawX() - layoutParams.width / 2));
showImage_Left.setY((float) (event.getRawY() - layoutParams.height / 2));
break;
case MotionEvent.ACTION_UP:
//手指抬起后,对这个进行添加表箱的处理
addBoxToDrawview(event.getRawX(), event.getRawY(), showImage_Left, boxType);
break;
}
return true;
}
});
}
private void initView() {
//单表箱类型的表的实例--左侧
example.setVisibility(View.INVISIBLE);
//单表箱类型的表的实例--右侧
touch1.setVisibility(View.INVISIBLE);
setTouchEvent_Left(i1, BoxTypes.Old_1_X);
setTouchEvent_Left(i2, BoxTypes.Old_A_New_2_X);
setTouchEvent_Left(i3, BoxTypes.Old_2_Y);
setTouchEvent_Left(i4, BoxTypes.Old_A_New_3_X);
setTouchEvent_Left(i5, BoxTypes.Old_A_New_3_Y);
setTouchEvent_Left(i6, BoxTypes.New_4_Y);
setTouchEvent_Left(i7, BoxTypes.New_4_X);
setTouchEvent_Left(i8, BoxTypes.New_4_XY);
setTouchEvent_Left(i9, BoxTypes.Old_A_New_6_Y);
setTouchEvent_Left(i10, BoxTypes.Old_6_X);
setTouchEvent_Left(i11, BoxTypes.Old_A_New_9_XY);
setTouchEvent_Right();
}
static int OLE_ONE = 1;
//根据touch事件中传递的X,Y,来判断这个图是应该放在哪,所有类型表公用这一个方法
/**
* @param x 点击事件X轴的坐标
* @param y 点击事件Y的坐标
* @param touchImage 点击这个表箱所触发的图片
*/
int anInt;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void addBoxToDrawview(double x, double y, ImageView touchImage, String boxType) {
//可以放置表箱的区域
double startX = drawView.getLeft() + ExampleWidth / 2;
double startY = drawView.getTop() + ExampleHeight / 2;
double endX = drawView.getRight() - ExampleWidth / 2;
double endY = drawView.getBottom() - ExampleHeight / 2;
//先判断这个有没有到画表箱的区域
if (x < startX || x > endX || y < startY || y > endY) {
mainView.removeView(touchImage);
showImage_Left = null;
return;
}
//对于这个表箱类型需要做判断
//表示右侧是否有可以容纳的
int userCount = 0;
if (boxType.equals(BoxTypes.Old_1_X)) {
for (OneBoxItem oneBoxItem : allBox) {
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
userCount++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth;
layoutParams.height = BoxHeight;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) oneBoxItem.getX());
addImage.setY((float) oneBoxItem.getY());
addImage.setImageResource(R.drawable.i1x1);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
Log.e("新增了一个view", "===");
mainView.addView(addImage);
//由于nowtime字段是为了区分几个type相同的格子是否为同一个类型的表箱拖出去,这个是单表箱 就不存在
oneBoxItem.setIndex(0);
oneBoxItem.setHadUse(true);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_1_X);
Log.e("设置的类型",oneBoxItem.getBoxType()+"="+allBox.get(0).getBoxType());
//删除这个复制的图片
mainView.removeView(touchImage);
;
showImage_Left = null;
}
}
} else if (boxType.equals(BoxTypes.Old_A_New_2_X)) {
//先拿到所有表格的下标和ID之间的对应关系
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
}
//把这个点当做是两个表箱左侧的这个,如果这个格子右边还有空余的,就放置,没有就取消
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
//横向两个表箱的判断,假设这个是两个表箱左侧的这个,呢么另一个的ID应该是X+1sY
//获得这个表格右侧的ID
Log.e("两横表箱 左侧的id", oneBoxItem.getID());
//1s1
String ID_Right = oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) + 1);
Log.e("两横表箱 右侧的id", ID_Right);
try {
int index = (int) map.get(ID_Right);
anInt = index;
if (allBox.get(index).isHadUse() == false) {
double time = System.currentTimeMillis();
userCount++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth * 2;
layoutParams.height = BoxHeight;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) oneBoxItem.getX());
addImage.setY((float) oneBoxItem.getY());
addImage.setImageResource(R.drawable.i1x2);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
Log.e("新增了一个二表箱", "===");
mainView.addView(addImage);
//左侧这个的数据设置
oneBoxItem.setHadUse(true);
oneBoxItem.setIndex(0);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_A_New_2_X);
//右侧这个数据的设置
allBox.get(index).setHadUse(true);
allBox.get(index).setIndex(1);
allBox.get(index).setNowTime(time);
allBox.get(index).setImageView(addImage);
allBox.get(index).setBoxType(BoxTypes.Old_A_New_2_X);
Log.e("右侧这个表箱现在的状态是什么", allBox.get(index).isHadUse() + "==" + allBox.get(index).getBoxType() + "==" + allBox.get(index).getX() + "=" + BoxWidth);
//删除这个复制的图片
mainView.removeView(touchImage);
;
showImage_Left = null;
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
} else if (boxType.equals(BoxTypes.Old_2_Y)) {
//拖动过来的是纵向二表的表箱,还是遍历所有表格,遇到一个空的,就去查询他下面的那个表格是否被使用.默认这个拖拽点是上面的那个表箱
//先拿到所有表格的下标和ID之间的对应关系
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
//纵向两个表箱的判断,假设这个是两个表箱上部的这个,呢么另一个的ID应该是XsY+1,对应ID中的数据AsB为 A+1,B
//1s1
String ID_Right = String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s"))) + 1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())));
try {
int index = (int) map.get(ID_Right);
anInt = index;
if (allBox.get(index).isHadUse() == false) {
double time = System.currentTimeMillis();
userCount++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth;
layoutParams.height = BoxHeight * 2;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) oneBoxItem.getX());
addImage.setY((float) oneBoxItem.getY());
addImage.setImageResource(R.drawable.i2x1);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
mainView.addView(addImage);
//上部这个的数据设置
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setIndex(0);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_2_Y);
//下部这个数据的设置
allBox.get(index).setHadUse(true);
allBox.get(index).setIndex(1);
allBox.get(index).setNowTime(time);
allBox.get(index).setImageView(addImage);
allBox.get(index).setBoxType(BoxTypes.Old_2_Y);
//删除这个复制的图片
mainView.removeView(touchImage);
;
showImage_Left = null;
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
} else if (boxType.equals(BoxTypes.Old_A_New_3_X)) {
//如果是横向的3,这里和2表箱的区别是,假设点击点的坐标是中间那个的坐标
//先拿到所有表格的下标和ID之间的对应关系
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
//纵向两个表箱的判断,假设这个是两个表箱上部的这个,呢么另一个的ID应该是XsY+1,对应ID中的数据AsB为 A+1,B
//右侧的这个
String ID_Right = oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) + 1);
//左侧的这个
String ID_Left = oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) - 1);
try {
int indexRight = (int) map.get(ID_Right);
int indexLeft = (int) map.get(ID_Left);
//判断左右两个是不是为空
if (allBox.get(indexRight).isHadUse() == false && allBox.get(indexLeft).isHadUse() == false) {
double time = System.currentTimeMillis();
userCount++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth * 3;
layoutParams.height = BoxHeight;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexLeft).getX());
addImage.setY((float) allBox.get(indexLeft).getY());
addImage.setImageResource(R.drawable.i1x3);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
mainView.addView(addImage);
//中间这个的数据设置
oneBoxItem.setHadUse(true);
oneBoxItem.setIndex(1);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_A_New_3_X);
//右侧这个数据的设置
allBox.get(indexRight).setIndex(2);
allBox.get(indexRight).setHadUse(true);
allBox.get(indexRight).setNowTime(time);
allBox.get(indexRight).setImageView(addImage);
allBox.get(indexRight).setBoxType(BoxTypes.Old_A_New_3_X);
//左侧这个
allBox.get(indexLeft).setIndex(0);
allBox.get(indexLeft).setHadUse(true);
allBox.get(indexLeft).setNowTime(time);
allBox.get(indexLeft).setImageView(addImage);
allBox.get(indexLeft).setBoxType(BoxTypes.Old_A_New_3_X);
//删除这个复制的图片
mainView.removeView(touchImage);
;
showImage_Left = null;
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}else if(boxType.equals(BoxTypes.Old_A_New_3_Y)){
//纵3的添加,以触摸点为中间那个
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
//点击点为中间
//上侧的这个
String ID_Top =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下侧的这个
String ID_Bottom =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
try {
int indexTop = (int) map.get(ID_Top);
int indexBottom = (int) map.get(ID_Bottom);
//判断左右两个是不是为空
if (allBox.get(indexTop).isHadUse() == false && allBox.get(indexBottom).isHadUse() == false) {
double time = System.currentTimeMillis();
userCount++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth ;
layoutParams.height = BoxHeight* 3;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexTop).getX());
addImage.setY((float) allBox.get(indexTop).getY());
addImage.setImageResource(R.drawable.i3x1);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
mainView.addView(addImage);
//左侧这个的数据设置
oneBoxItem.setIndex(1);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_A_New_3_Y);
//上侧这个数据的设置
allBox.get(indexTop).setIndex(0);
allBox.get(indexTop).setHadUse(true);
allBox.get(indexTop).setNowTime(time);
allBox.get(indexTop).setImageView(addImage);
allBox.get(indexTop).setBoxType(BoxTypes.Old_A_New_3_Y);
//左侧这个
allBox.get(indexBottom).setIndex(2);
allBox.get(indexBottom).setHadUse(true);
allBox.get(indexBottom).setNowTime(time);
allBox.get(indexBottom).setImageView(addImage);
allBox.get(indexBottom).setBoxType(BoxTypes.Old_A_New_3_Y);
//删除这个复制的图片
mainView.removeView(touchImage);
;
showImage_Left = null;
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}else if(boxType.equals(BoxTypes.New_4_Y)){
//纵4,以从上开始数的第二个作为这个点击的
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
//纵向两个表箱的判断,假设这个是两个表箱上部的这个,呢么另一个的ID应该是XsY+1,对应ID中的数据AsB为 A+1,B
//上部的这个
String ID_Top =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下部第一个
String ID_Bottom =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下部第二个
String ID_Bottom_2 =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+2) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
try {
int indexTop = (int) map.get(ID_Top);
int indexBottom = (int) map.get(ID_Bottom);
int indexBottom_2 = (int) map.get(ID_Bottom_2);
//判断左右两个是不是为空
if (allBox.get(indexTop).isHadUse() == false && allBox.get(indexBottom).isHadUse() == false&& allBox.get(indexBottom_2).isHadUse() == false) {
double time = System.currentTimeMillis();
userCount++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth ;
layoutParams.height = BoxHeight* 4;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexTop).getX());
addImage.setY((float) allBox.get(indexTop).getY());
addImage.setImageResource(R.drawable.i4x1);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
mainView.addView(addImage);
//设置新增的数据
oneBoxItem.setHadUse(true);
oneBoxItem.setIndex(1);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.New_4_Y);
//
allBox.get(indexTop).setIndex(0);
allBox.get(indexTop).setHadUse(true);
allBox.get(indexTop).setNowTime(time);
allBox.get(indexTop).setImageView(addImage);
allBox.get(indexTop).setBoxType(BoxTypes.New_4_Y);
//
allBox.get(indexBottom).setIndex(2);
allBox.get(indexBottom).setHadUse(true);
allBox.get(indexBottom).setNowTime(time);
allBox.get(indexBottom).setImageView(addImage);
allBox.get(indexBottom).setBoxType(BoxTypes.New_4_Y);
allBox.get(indexBottom_2).setIndex(3);
allBox.get(indexBottom_2).setHadUse(true);
allBox.get(indexBottom_2).setNowTime(time);
allBox.get(indexBottom_2).setImageView(addImage);
allBox.get(indexBottom_2).setBoxType(BoxTypes.New_4_Y);
//删除这个复制的图片
mainView.removeView(touchImage);
;
showImage_Left = null;
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}else if(boxType.equals(BoxTypes.New_4_X)){
//横4,以从上开始数的第二个作为这个点击的
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
//点击点作为第一行第二个
//左侧部的这个
String ID_Left =oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
//第一个右侧
String ID_Right =oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))+1 );
//右侧第二个
String ID_Right_2 =oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))+2 );
try {
int index_Left = (int) map.get(ID_Left);
int index_Right = (int) map.get(ID_Right);
int index_Right_2 = (int) map.get(ID_Right_2);
//判断左右两个是不是为空
if (allBox.get(index_Left).isHadUse() == false && allBox.get(index_Right).isHadUse() == false&& allBox.get(index_Right_2).isHadUse() == false) {
double time = System.currentTimeMillis();
userCount++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth* 4 ;
layoutParams.height = BoxHeight;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(index_Left).getX());
addImage.setY((float) allBox.get(index_Left).getY());
addImage.setImageResource(R.drawable.i1x4);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
mainView.addView(addImage);
//设置新增的数据
oneBoxItem.setIndex(1);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.New_4_X);
//
allBox.get(index_Left).setIndex(0);
allBox.get(index_Left).setHadUse(true);
allBox.get(index_Left).setNowTime(time);
allBox.get(index_Left).setImageView(addImage);
allBox.get(index_Left).setBoxType(BoxTypes.New_4_X);
//
allBox.get(index_Right).setIndex(2);
allBox.get(index_Right).setHadUse(true);
allBox.get(index_Right).setNowTime(time);
allBox.get(index_Right).setImageView(addImage);
allBox.get(index_Right).setBoxType(BoxTypes.New_4_X);
allBox.get(index_Right_2).setIndex(3);
allBox.get(index_Right_2).setHadUse(true);
allBox.get(index_Right_2).setNowTime(time);
allBox.get(index_Right_2).setImageView(addImage);
allBox.get(index_Right_2).setBoxType(BoxTypes.New_4_X);
//删除这个复制的图片
mainView.removeView(touchImage);
;
showImage_Left = null;
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}else if(boxType.equals(BoxTypes.New_4_XY)){
//田子4,以从上开始数的第一个作为这个点击的,及左上角
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
//点击点为左上角
//上部的这个
String ID_Top_Right =oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
//下部第一个
String ID_Bottom_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下部第二个
String ID_Bottom_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
try {
int indexTop_Right = (int) map.get(ID_Top_Right);
int indexBottom_Left = (int) map.get(ID_Bottom_Left);
int indexBottom_Right = (int) map.get(ID_Bottom_Right);
//判断左右两个是不是为空
if (allBox.get(indexTop_Right).isHadUse() == false && allBox.get(indexBottom_Left).isHadUse() == false&& allBox.get(indexBottom_Right).isHadUse() == false) {
double time = System.currentTimeMillis();
userCount++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth*2 ;
layoutParams.height = BoxHeight* 2;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) oneBoxItem.getX());
addImage.setY((float) oneBoxItem.getY());
addImage.setImageResource(R.drawable.i2x2);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
mainView.addView(addImage);
//设置新增的数据
oneBoxItem.setHadUse(true);
oneBoxItem.setIndex(0);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.New_4_XY);
//
allBox.get(indexTop_Right).setIndex(1);
allBox.get(indexTop_Right).setHadUse(true);
allBox.get(indexTop_Right).setNowTime(time);
allBox.get(indexTop_Right).setImageView(addImage);
allBox.get(indexTop_Right).setBoxType(BoxTypes.New_4_XY);
//
allBox.get(indexBottom_Left).setIndex(2);
allBox.get(indexBottom_Left).setHadUse(true);
allBox.get(indexBottom_Left).setNowTime(time);
allBox.get(indexBottom_Left).setImageView(addImage);
allBox.get(indexBottom_Left).setBoxType(BoxTypes.New_4_XY);
allBox.get(indexBottom_Right).setIndex(3);
allBox.get(indexBottom_Right).setHadUse(true);
allBox.get(indexBottom_Right).setNowTime(time);
allBox.get(indexBottom_Right).setImageView(addImage);
allBox.get(indexBottom_Right).setBoxType(BoxTypes.New_4_XY);
//删除这个复制的图片
mainView.removeView(touchImage);
;
showImage_Left = null;
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}else if(boxType.equals(BoxTypes.Old_A_New_6_Y)){
//田子6,纵向的,这个触摸点为左侧第二排的格子
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
//当前为第二排左侧
//上部左侧
String ID_Top_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//上部的右侧
String ID_Top_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
//正右侧
String ID_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
//下部第一个
String ID_Bottom_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下部第二个
String ID_Bottom_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
try {
int indexTop_Left = (int) map.get(ID_Top_Left);
int indexTop_Right = (int) map.get(ID_Top_Right);
int indexRight = (int) map.get(ID_Right);
int indexBottom_Left = (int) map.get(ID_Bottom_Left);
int indexBottom_Right = (int) map.get(ID_Bottom_Right);
//判断左右两个是不是为空
if (allBox.get(indexTop_Left).isHadUse() == false && allBox.get(indexTop_Right).isHadUse() == false&& allBox.get(indexRight).isHadUse() == false&&allBox.get(indexBottom_Left).isHadUse() == false&&allBox.get(indexBottom_Right).isHadUse() == false) {
double time = System.currentTimeMillis();
userCount++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth*2 ;
layoutParams.height = BoxHeight* 3;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexTop_Left).getX());
addImage.setY((float) allBox.get(indexTop_Left).getY());
addImage.setImageResource(R.drawable.i3x2);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
mainView.addView(addImage);
//设置新增的数据
oneBoxItem.setIndex(2);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_A_New_6_Y);
//
allBox.get(indexTop_Left).setIndex(0);
allBox.get(indexTop_Left).setHadUse(true);
allBox.get(indexTop_Left).setNowTime(time);
allBox.get(indexTop_Left).setImageView(addImage);
allBox.get(indexTop_Left).setBoxType(BoxTypes.Old_A_New_6_Y);
//
allBox.get(indexTop_Right).setIndex(1);
allBox.get(indexTop_Right).setHadUse(true);
allBox.get(indexTop_Right).setNowTime(time);
allBox.get(indexTop_Right).setImageView(addImage);
allBox.get(indexTop_Right).setBoxType(BoxTypes.Old_A_New_6_Y);
allBox.get(indexRight).setIndex(3);
allBox.get(indexRight).setHadUse(true);
allBox.get(indexRight).setNowTime(time);
allBox.get(indexRight).setImageView(addImage);
allBox.get(indexRight).setBoxType(BoxTypes.Old_A_New_6_Y);
allBox.get(indexBottom_Left).setIndex(4);
allBox.get(indexBottom_Left).setHadUse(true);
allBox.get(indexBottom_Left).setNowTime(time);
allBox.get(indexBottom_Left).setImageView(addImage);
allBox.get(indexBottom_Left).setBoxType(BoxTypes.Old_A_New_6_Y);
allBox.get(indexBottom_Right).setIndex(5);
allBox.get(indexBottom_Right).setHadUse(true);
allBox.get(indexBottom_Right).setNowTime(time);
allBox.get(indexBottom_Right).setImageView(addImage);
allBox.get(indexBottom_Right).setBoxType(BoxTypes.Old_A_New_6_Y);
//删除这个复制的图片
mainView.removeView(touchImage);
;
showImage_Left = null;
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}else if(boxType.equals(BoxTypes.Old_6_X)){
//田子6,横向的,这个触摸点为第一排第二个的格子
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
//当前为第一排第二个
//上部左侧
String ID_Top_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
//上部的右侧
String ID_Top_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
//下部正右
String ID_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下部第一个
String ID_Bottom_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
//下部第二个
String ID_Bottom_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
try {
int indexTop_Left = (int) map.get(ID_Top_Left);
int indexTop_Right = (int) map.get(ID_Top_Right);
int indexRight = (int) map.get(ID_Right);
int indexBottom_Left = (int) map.get(ID_Bottom_Left);
int indexBottom_Right = (int) map.get(ID_Bottom_Right);
//判断左右两个是不是为空
if (allBox.get(indexTop_Left).isHadUse() == false && allBox.get(indexTop_Right).isHadUse() == false&& allBox.get(indexRight).isHadUse() == false&&allBox.get(indexBottom_Left).isHadUse() == false&&allBox.get(indexBottom_Right).isHadUse() == false) {
double time = System.currentTimeMillis();
userCount++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth*3 ;
layoutParams.height = BoxHeight* 2;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexTop_Left).getX());
addImage.setY((float) allBox.get(indexTop_Left).getY());
addImage.setImageResource(R.drawable.i2x3);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
mainView.addView(addImage);
//设置新增的数据
oneBoxItem.setIndex(1);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_6_X);
//
allBox.get(indexTop_Left).setIndex(0);
allBox.get(indexTop_Left).setHadUse(true);
allBox.get(indexTop_Left).setNowTime(time);
allBox.get(indexTop_Left).setImageView(addImage);
allBox.get(indexTop_Left).setBoxType(BoxTypes.Old_6_X);
//
allBox.get(indexTop_Right).setIndex(2);
allBox.get(indexTop_Right).setHadUse(true);
allBox.get(indexTop_Right).setNowTime(time);
allBox.get(indexTop_Right).setImageView(addImage);
allBox.get(indexTop_Right).setBoxType(BoxTypes.Old_6_X);
allBox.get(indexRight).setIndex(3);
allBox.get(indexRight).setHadUse(true);
allBox.get(indexRight).setNowTime(time);
allBox.get(indexRight).setImageView(addImage);
allBox.get(indexRight).setBoxType(BoxTypes.Old_6_X);
allBox.get(indexBottom_Left).setIndex(4);
allBox.get(indexBottom_Left).setHadUse(true);
allBox.get(indexBottom_Left).setNowTime(time);
allBox.get(indexBottom_Left).setImageView(addImage);
allBox.get(indexBottom_Left).setBoxType(BoxTypes.Old_6_X);
allBox.get(indexBottom_Right).setIndex(5);
allBox.get(indexBottom_Right).setHadUse(true);
allBox.get(indexBottom_Right).setNowTime(time);
allBox.get(indexBottom_Right).setImageView(addImage);
allBox.get(indexBottom_Right).setBoxType(BoxTypes.Old_6_X);
//删除这个复制的图片
mainView.removeView(touchImage);
;
showImage_Left = null;
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}else if(boxType.equals(BoxTypes.Old_A_New_9_XY)){
//田子9,这个触摸点为最中间
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
//当前为第二排第二个
//上部左侧
String ID_Top_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
String ID_Top_Zhong =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//上部的右侧
String ID_Top_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
//中间的一左一右
String ID_Zhong_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
String ID_Zhong_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))+1 );
//下部第一个
String ID_Bottom_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
//下部正中
String ID_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下部第二个
String ID_Bottom_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
try {
int indexTop_Left = (int) map.get(ID_Top_Left);
int indexTop_Right = (int) map.get(ID_Top_Right);
int indexRight = (int) map.get(ID_Right);
//新增的
int indexTop_Zhong = (int) map.get(ID_Top_Zhong);
int indexZhong_Left = (int) map.get(ID_Zhong_Left);
int indexZhong_Right = (int) map.get(ID_Zhong_Right);
//
int indexBottom_Left = (int) map.get(ID_Bottom_Left);
int indexBottom_Right = (int) map.get(ID_Bottom_Right);
//判断左右两个是不是为空
if (allBox.get(indexTop_Left).isHadUse() == false &&
allBox.get(indexTop_Right).isHadUse() == false&&
allBox.get(indexRight).isHadUse() == false&&
allBox.get(indexBottom_Left).isHadUse() == false&&
allBox.get(indexBottom_Right).isHadUse() == false&&
allBox.get(indexTop_Zhong).isHadUse() == false&&
allBox.get(indexZhong_Left).isHadUse() == false&&
allBox.get(indexZhong_Right).isHadUse() == false) {
double time = System.currentTimeMillis();
userCount++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth*3 ;
layoutParams.height = BoxHeight*3;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexTop_Left).getX());
addImage.setY((float) allBox.get(indexTop_Left).getY());
addImage.setImageResource(R.drawable.i3x3);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
mainView.addView(addImage);
//设置新增的数据
oneBoxItem.setIndex(4);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_A_New_9_XY);
//
allBox.get(indexTop_Zhong).setIndex(1);
allBox.get(indexTop_Zhong).setHadUse(true);
allBox.get(indexTop_Zhong).setNowTime(time);
allBox.get(indexTop_Zhong).setImageView(addImage);
allBox.get(indexTop_Zhong).setBoxType(BoxTypes.Old_A_New_9_XY);
//
allBox.get(indexZhong_Left).setIndex(3);
allBox.get(indexZhong_Left).setHadUse(true);
allBox.get(indexZhong_Left).setNowTime(time);
allBox.get(indexZhong_Left).setImageView(addImage);
allBox.get(indexZhong_Left).setBoxType(BoxTypes.Old_A_New_9_XY);
//
allBox.get(indexZhong_Right).setIndex(5);
allBox.get(indexZhong_Right).setHadUse(true);
allBox.get(indexZhong_Right).setNowTime(time);
allBox.get(indexZhong_Right).setImageView(addImage);
allBox.get(indexZhong_Right).setBoxType(BoxTypes.Old_A_New_9_XY);
//
allBox.get(indexTop_Left).setIndex(0);
allBox.get(indexTop_Left).setHadUse(true);
allBox.get(indexTop_Left).setNowTime(time);
allBox.get(indexTop_Left).setImageView(addImage);
allBox.get(indexTop_Left).setBoxType(BoxTypes.Old_A_New_9_XY);
//
allBox.get(indexTop_Right).setIndex(2);
allBox.get(indexTop_Right).setHadUse(true);
allBox.get(indexTop_Right).setNowTime(time);
allBox.get(indexTop_Right).setImageView(addImage);
allBox.get(indexTop_Right).setBoxType(BoxTypes.Old_A_New_9_XY);
//底部正中
allBox.get(indexRight).setIndex(7);
allBox.get(indexRight).setHadUse(true);
allBox.get(indexRight).setNowTime(time);
allBox.get(indexRight).setImageView(addImage);
allBox.get(indexRight).setBoxType(BoxTypes.Old_A_New_9_XY);
allBox.get(indexZhong_Right).setIndex(6);
allBox.get(indexBottom_Left).setHadUse(true);
allBox.get(indexBottom_Left).setNowTime(time);
allBox.get(indexBottom_Left).setImageView(addImage);
allBox.get(indexBottom_Left).setBoxType(BoxTypes.Old_A_New_9_XY);
allBox.get(indexBottom_Right).setIndex(8);
allBox.get(indexBottom_Right).setHadUse(true);
allBox.get(indexBottom_Right).setNowTime(time);
allBox.get(indexBottom_Right).setImageView(addImage);
allBox.get(indexBottom_Right).setBoxType(BoxTypes.Old_A_New_9_XY);
//删除这个复制的图片
mainView.removeView(touchImage);
;
showImage_Left = null;
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}
//类型判断完毕
if (userCount > 0) {
} else {
Toast.makeText(MainActivity.this, "位置错误", Toast.LENGTH_LONG).show();
mainView.removeView(touchImage);
;
showImage_Left = null;
}
}
//把小数转为整数,只取整数部分
private int splitDouble(double d) {
String temp = String.valueOf(d);
int result = 0;
if (temp.length() > 2) {
String temp2 = temp.substring(0, temp.indexOf("."));
result = Integer.parseInt(temp2);
}
return result;
}
/*
这个是右侧绘图区域的点击和拖拽处理===右侧===右侧===右侧===右侧===右侧===右侧===右侧===右侧===右侧===右侧===右侧===右侧===右侧===右侧===右侧===右侧
*/
//给右侧的绘图区域设置点击事件
//这个参数用来表示 在出发down之后 是否还需要出发他的move.当点到的是表箱的时候,才会出发move
boolean needToMove = false;
//需要触发move事件的这个表箱
OneBoxItem TheBoxT = null;
//这个是右侧区域拖动时候显示的图片,每次都新建,完成后删除
ImageView showImage_Right = null;
private void setTouchEvent_Right() {
drawView.setOnTouchListener(new View.OnTouchListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.e("右侧点击", event.getRawX() + "第一个的坐标" + allBox.get(0).getX() + "==" + allBox.get(1).getX());
//注意,这里也需要对不同的表箱类型进行相应的判断
Log.e("点击的位置", event.getRawX() + "==" + allBox.get(anInt).getBoxType() + "==" + allBox.get(anInt).getX());
float x = event.getRawX();
float y = event.getRawY();
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x > oneBoxItem.getX() && x < oneBoxItem.getX() + BoxWidth && y > oneBoxItem.getY() && y < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == true) {
Log.e("这个地方有表箱", "====");
//表示这个位置有表箱,呢就显示新增个虚拟的表箱吧
showImage_Right = new ImageView(MainActivity.this);
showImage_Right.setAlpha(0.3f);
PercentRelativeLayout.LayoutParams layoutParamsShow = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//类型判断
if (oneBoxItem.getBoxType().equals(BoxTypes.Old_1_X)) {
//对于单表箱的,直接一个判断就可以了
layoutParamsShow.width = BoxWidth;
layoutParamsShow.height = BoxHeight;
showImage_Right.setX(event.getRawX() - BoxWidth / 2);
showImage_Right.setY(event.getRawY() - BoxHeight / 2);
showImage_Right.setBackground(getResources().getDrawable(R.drawable.i1x1));
needToMove = true;
TheBoxT = oneBoxItem;
} else if (oneBoxItem.getBoxType().equals(BoxTypes.Old_A_New_2_X)) {
//表示是横向二表箱,就需要把他当左或者右来处理
layoutParamsShow.width = BoxWidth * 2;
layoutParamsShow.height = BoxHeight;
showImage_Right.setX(event.getRawX() - layoutParamsShow.width / 2);
showImage_Right.setY(event.getRawY() - layoutParamsShow.height / 2);
showImage_Right.setBackground(getResources().getDrawable(R.drawable.i1x2));
needToMove = true;
TheBoxT = oneBoxItem;
} else if (oneBoxItem.getBoxType().equals(BoxTypes.Old_2_Y)) {
//表示是纵向的2表箱,创建一个拖动的虚影子
layoutParamsShow.width = BoxWidth;
layoutParamsShow.height = BoxHeight * 2;
showImage_Right.setX(event.getRawX() - layoutParamsShow.width / 2);
showImage_Right.setY(event.getRawY() - layoutParamsShow.height / 2);
showImage_Right.setBackground(getResources().getDrawable(R.drawable.i2x1));
needToMove = true;
TheBoxT = oneBoxItem;
} else if (oneBoxItem.getBoxType().equals(BoxTypes.Old_A_New_3_X)) {
//表示是横向的3表箱,创建一个拖动的虚影子
layoutParamsShow.width = BoxWidth * 3;
layoutParamsShow.height = BoxHeight;
showImage_Right.setX(event.getRawX() - layoutParamsShow.width / 2);
showImage_Right.setY(event.getRawY() - layoutParamsShow.height / 2);
showImage_Right.setBackground(getResources().getDrawable(R.drawable.i1x3));
needToMove = true;
TheBoxT = oneBoxItem;
}else if (oneBoxItem.getBoxType().equals(BoxTypes.Old_A_New_3_Y)) {
//表示是横向的3表箱,创建一个拖动的虚影子
layoutParamsShow.width = BoxWidth;
layoutParamsShow.height = BoxHeight * 3;
showImage_Right.setX(event.getRawX() - layoutParamsShow.width / 2);
showImage_Right.setY(event.getRawY() - layoutParamsShow.height / 2);
showImage_Right.setBackground(getResources().getDrawable(R.drawable.i3x1));
needToMove = true;
TheBoxT = oneBoxItem;
}else if (oneBoxItem.getBoxType().equals(BoxTypes.New_4_Y)) {
//表示是横向的3表箱,创建一个拖动的虚影子
layoutParamsShow.width = BoxWidth;
layoutParamsShow.height = BoxHeight * 4;
showImage_Right.setX(event.getRawX() - layoutParamsShow.width / 2);
showImage_Right.setY(event.getRawY() - layoutParamsShow.height / 2);
showImage_Right.setBackground(getResources().getDrawable(R.drawable.i4x1));
needToMove = true;
TheBoxT = oneBoxItem;
}else if (oneBoxItem.getBoxType().equals(BoxTypes.New_4_X)) {
//表示是横向的3表箱,创建一个拖动的虚影子
layoutParamsShow.width = BoxWidth * 4;
layoutParamsShow.height = BoxHeight;
showImage_Right.setX(event.getRawX() - layoutParamsShow.width / 2);
showImage_Right.setY(event.getRawY() - layoutParamsShow.height / 2);
showImage_Right.setBackground(getResources().getDrawable(R.drawable.i1x4));
needToMove = true;
TheBoxT = oneBoxItem;
}else if (oneBoxItem.getBoxType().equals(BoxTypes.New_4_XY)) {
//表示是横向的3表箱,创建一个拖动的虚影子
layoutParamsShow.width = BoxWidth * 2;
layoutParamsShow.height = BoxHeight* 2;
showImage_Right.setX(event.getRawX() - layoutParamsShow.width / 2);
showImage_Right.setY(event.getRawY() - layoutParamsShow.height / 2);
showImage_Right.setBackground(getResources().getDrawable(R.drawable.i2x2));
needToMove = true;
TheBoxT = oneBoxItem;
}else if (oneBoxItem.getBoxType().equals(BoxTypes.Old_A_New_6_Y)) {
//表示是横向的3表箱,创建一个拖动的虚影子
layoutParamsShow.width = BoxWidth * 2;
layoutParamsShow.height = BoxHeight* 3;
showImage_Right.setX(event.getRawX() - layoutParamsShow.width / 2);
showImage_Right.setY(event.getRawY() - layoutParamsShow.height / 2);
showImage_Right.setBackground(getResources().getDrawable(R.drawable.i3x2));
needToMove = true;
TheBoxT = oneBoxItem;
}else if (oneBoxItem.getBoxType().equals(BoxTypes.Old_6_X)) {
//表示是横向的3表箱,创建一个拖动的虚影子
layoutParamsShow.width = BoxWidth * 3;
layoutParamsShow.height = BoxHeight* 2;
showImage_Right.setX(event.getRawX() - layoutParamsShow.width / 2);
showImage_Right.setY(event.getRawY() - layoutParamsShow.height / 2);
showImage_Right.setBackground(getResources().getDrawable(R.drawable.i2x3));
needToMove = true;
TheBoxT = oneBoxItem;
}else if (oneBoxItem.getBoxType().equals(BoxTypes.Old_A_New_9_XY)) {
//表示是横向的3表箱,创建一个拖动的虚影子
layoutParamsShow.width = BoxWidth * 3;
layoutParamsShow.height = BoxHeight* 3;
showImage_Right.setX(event.getRawX() - layoutParamsShow.width / 2);
showImage_Right.setY(event.getRawY() - layoutParamsShow.height / 2);
showImage_Right.setBackground(getResources().getDrawable(R.drawable.i3x3));
needToMove = true;
TheBoxT = oneBoxItem;
}
showImage_Right.setLayoutParams(layoutParamsShow);
mainView.addView(showImage_Right);
}
}
break;
case MotionEvent.ACTION_MOVE:
if (needToMove) {
if (TheBoxT == null || TheBoxT.getBoxType().equals("")) {
Log.e("在获取表箱类型时候出现异常", "====");
break;
}
withRightOnTuch(event.getRawX(), event.getRawY(), TheBoxT);
}
break;
case MotionEvent.ACTION_UP:
if (needToMove) {
if (TheBoxT == null || TheBoxT.getBoxType().equals("")) {
Log.e("up事件拿表箱类型异常", "====");
mainView.removeView(showImage_Right);
} else {
//如果超出右侧区域,表示是想删除这个表箱.注意,这个虽然存在右侧区域上下左右1/2间隔的问题,但是这个问题会在判断放置的位置是否有空格的时候被解决
if (event.getRawX() <= drawView.getLeft() || event.getRawY() <= drawView.getTop() || event.getRawX() >= drawView.getRight() || event.getRawY() >= drawView.getBottom()) {
//超出了区域,表示是需要删除了.注意:还需要判断是哪张类型.这个传过来的是一定要删的
mainView.removeView(TheBoxT.getImageView());
TheBoxT.setHadUse(false);
if (TheBoxT.getBoxType().equals(BoxTypes.Old_1_X)) {
} else {
//超过一个的,就存在多个了
List<Integer> needDelte = new ArrayList();
for (int i = 0; i < allBox.size(); i++) {
if (allBox.get(i).getNowTime() == TheBoxT.getNowTime() && !allBox.get(i).getID().equals(TheBoxT.getID())) {
needDelte.add(i);
}
}
if (needDelte.size() < 1) {
Toast.makeText(MainActivity.this, "删除失败,请重试", Toast.LENGTH_SHORT).show();
} else {
for (int del : needDelte) {
allBox.get(del).setHadUse(false);
}
}
}
mainView.removeView(showImage_Right);
} else {
/**
* 拖动到右侧可绘制的区域内部
*/
//还在区域内,就需要判断,拖动位置是否空余,在不空余的时候,如果这个ID和现在的ID相同,就表示还是在老地方,位置不变
float x1 = event.getRawX();
float y1 = event.getRawY();
int canUse = 0;
if (TheBoxT.getBoxType().equals(BoxTypes.Old_1_X)) {
for (OneBoxItem oneBoxItem : allBox) {
if (x1 > oneBoxItem.getX() && x1 < oneBoxItem.getX() + BoxWidth && y1 > oneBoxItem.getY() && y1 < oneBoxItem.getY() + BoxHeight
&& oneBoxItem.isHadUse() == false) {
//表示放置的位置是个空白
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth;
layoutParams.height = BoxHeight;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) oneBoxItem.getX());
addImage.setY((float) oneBoxItem.getY());
addImage.setImageResource(R.drawable.i1x1);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
mainView.addView(addImage);
oneBoxItem.setHadUse(true);
oneBoxItem.setIndex(0);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_1_X);
TheBoxT.setHadUse(false);
//让原来的位置的状态变为可用,并删除之前的内容.对于新增的这个半透明的图片,一并删除
mainView.removeView(TheBoxT.getImageView());
mainView.removeView(showImage_Right);
canUse++;
}
}
} else if (TheBoxT.getBoxType().equals(BoxTypes.Old_A_New_2_X)) {
//先拿到所有表格的下标和ID之间的对应关系
Map map = new HashMap();
//再找到另外那个存放的表格位置
int otherTableIndex = 0;
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
if (allBox.get(i).getNowTime() == TheBoxT.getNowTime() && !allBox.get(i).getID().equals(TheBoxT.getID())) {
otherTableIndex = i;
}
}
//把这个点当做是两个表箱左侧的这个,如果这个格子右边还有空余的,就放置,没有就取消
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x1 > oneBoxItem.getX() && x1 < oneBoxItem.getX() + BoxWidth && y1 > oneBoxItem.getY() && y1 < oneBoxItem.getY() + BoxHeight) {
//如果他在这个区域内部
//算出需要的两个格子的位置.一个就是现在的onBoxItem,另一个就需要计算了
String ID_Right = oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) + 1);
try {
int index = (int) map.get(ID_Right);
if ((oneBoxItem.getNowTime() == TheBoxT.getNowTime() || oneBoxItem.isHadUse() == false) && (allBox.get(index).getNowTime() == TheBoxT.getNowTime() || allBox.get(index).isHadUse() == false)) {
double time = System.currentTimeMillis();
canUse++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth * 2;
layoutParams.height = BoxHeight;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) oneBoxItem.getX());
addImage.setY((float) oneBoxItem.getY());
addImage.setImageResource(R.drawable.i1x2);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
//因为可能存在覆盖的情况,所以先删除老数据,再写入新数据
//把之前的盛放的view给置空
TheBoxT.setHadUse(false);
allBox.get(otherTableIndex).setHadUse(false);
TheBoxT.setHadUse(false);
//删除这个复制的图片
mainView.removeView(TheBoxT.getImageView());
mainView.removeView(showImage_Right);
//加入新数据
//左侧这个的数据设置
oneBoxItem.setHadUse(true);
oneBoxItem.setIndex(0);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_A_New_2_X);
//右侧这个数据的设置
allBox.get(index).setIndex(1);
allBox.get(index).setHadUse(true);
allBox.get(index).setNowTime(time);
allBox.get(index).setImageView(addImage);
allBox.get(index).setBoxType(BoxTypes.Old_A_New_2_X);
mainView.addView(addImage);
//把这个置空,
showImage_Right = null;
}
} catch (Exception e) {
}
}
}
} else if (TheBoxT.getBoxType().equals(BoxTypes.Old_2_Y)) {
//先拿到所有表格的下标和ID之间的对应关系
Map map = new HashMap();
//再找到另外那个存放的表格位置
int otherTableIndex = 0;
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
if (allBox.get(i).getNowTime() == TheBoxT.getNowTime() && !allBox.get(i).getID().equals(TheBoxT.getID())) {
otherTableIndex = i;
}
}
//把这个点当做是两个表箱上侧的这个,如果这个格子右边还有空余的,就放置,没有就取消
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
//只需要判断相关联的box是false或者为相同的就可以了
if (x1 > oneBoxItem.getX() && x1 < oneBoxItem.getX() + BoxWidth && y1 > oneBoxItem.getY() && y1 < oneBoxItem.getY() + BoxHeight) {
//这个是纵向2的底部
String ID_Right = String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s"))) + 1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())));
try {
int index = (int) map.get(ID_Right);
if ((oneBoxItem.getNowTime() == TheBoxT.getNowTime() || oneBoxItem.isHadUse() == false) && (allBox.get(index).getNowTime() == TheBoxT.getNowTime() || allBox.get(index).isHadUse() == false)) {
double time = System.currentTimeMillis();
canUse++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth;
layoutParams.height = BoxHeight * 2;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) oneBoxItem.getX());
addImage.setY((float) oneBoxItem.getY());
addImage.setImageResource(R.drawable.i2x1);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
//先置空,再新增
//把之前的盛放的view给置空
TheBoxT.setHadUse(false);
allBox.get(otherTableIndex).setHadUse(false);
TheBoxT.setHadUse(false);
//删除这个原图和虚拟的图
mainView.removeView(TheBoxT.getImageView());
mainView.removeView(showImage_Right);
//更新下页面和数据
mainView.addView(addImage);
oneBoxItem.setHadUse(true);
oneBoxItem.setIndex(0);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_2_Y);
allBox.get(index).setHadUse(true);
allBox.get(index).setNowTime(time);
allBox.get(index).setIndex(1);
allBox.get(index).setImageView(addImage);
allBox.get(index).setBoxType(BoxTypes.Old_2_Y);
showImage_Right = null;
}
} catch (Exception e) {
}
}
}
} else if (TheBoxT.getBoxType().equals(BoxTypes.Old_A_New_3_X)) {
//表示拖动的是个横向的3表箱,进行位置判断吧
//先拿到所有表格的下标和ID之间的对应关系
//这里还需要找到需要删除的那两个
List<Integer> list = new ArrayList<Integer>();
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
if (allBox.get(i).getNowTime() == TheBoxT.getNowTime() && !allBox.get(i).getID().equals(TheBoxT.getID())) {
list.add(i);
}
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if(x1 > oneBoxItem.getX() && x1 < oneBoxItem.getX() + BoxWidth && y1 > oneBoxItem.getY() && y1 < oneBoxItem.getY() + BoxHeight){
//表示是个格子
//右侧的这个
String ID_Right = oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) + 1);
//左侧的这个
String ID_Left = oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) - 1);
try {
int indexRight = (int) map.get(ID_Right);
int indexLeft = (int) map.get(ID_Left);
//判断左右两个是不是为空
if ((allBox.get(indexRight).isHadUse() == false||allBox.get(indexRight).getNowTime()==TheBoxT.getNowTime()) && (allBox.get(indexLeft).isHadUse() == false||allBox.get(indexLeft).getNowTime()==TheBoxT.getNowTime())
&&(oneBoxItem.isHadUse() == false||oneBoxItem.getNowTime()==TheBoxT.getNowTime())) {
double time = System.currentTimeMillis();
canUse++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth * 3;
layoutParams.height = BoxHeight;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexLeft).getX());
addImage.setY((float) allBox.get(indexLeft).getY());
addImage.setImageResource(R.drawable.i1x3);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
//先清除 在新增
//把之前的盛放的view给置空
TheBoxT.setHadUse(false);
for (int index_delete : list) {
allBox.get(index_delete).setHadUse(false);
allBox.get(index_delete).setHadUse(false);
}
TheBoxT.setHadUse(false);
//删除这个复制的图片
mainView.removeView(TheBoxT.getImageView());
mainView.removeView(showImage_Right);
//新增数据
mainView.addView(addImage);
//左侧这个的数据设置
oneBoxItem.setIndex(1);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_A_New_3_X);
//右侧这个数据的设置
allBox.get(indexRight).setIndex(2);
allBox.get(indexRight).setHadUse(true);
allBox.get(indexRight).setNowTime(time);
allBox.get(indexRight).setImageView(addImage);
allBox.get(indexRight).setBoxType(BoxTypes.Old_A_New_3_X);
//左侧这个
allBox.get(indexLeft).setIndex(0);
allBox.get(indexLeft).setHadUse(true);
allBox.get(indexLeft).setNowTime(time);
allBox.get(indexLeft).setImageView(addImage);
allBox.get(indexLeft).setBoxType(BoxTypes.Old_A_New_3_X);
//删除这个复制的图片
mainView.removeView(showImage_Right);
showImage_Right = null;
}
} catch (Exception e) {
Log.e("这个不合适三横表箱", "===");
}
}
}
}else if(TheBoxT.getBoxType().equals(BoxTypes.Old_A_New_3_Y)){
//表示拖动的是个横向的3表箱,进行位置判断吧
//先拿到所有表格的下标和ID之间的对应关系
//这里还需要找到需要删除的那两个
List<Integer> list = new ArrayList<Integer>();
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
if (allBox.get(i).getNowTime() == TheBoxT.getNowTime() && !allBox.get(i).getID().equals(TheBoxT.getID())) {
list.add(i);
}
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if(x1 > oneBoxItem.getX() && x1 < oneBoxItem.getX() + BoxWidth && y1 > oneBoxItem.getY() && y1 < oneBoxItem.getY() + BoxHeight){
//表示是个格子
//右侧的这个
String ID_Top =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//左侧的这个
String ID_Bottom =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
try {
int indexTop = (int) map.get(ID_Top);
int indexBottom = (int) map.get(ID_Bottom);
//判断左右两个是不是为空
if ((allBox.get(indexTop).isHadUse() == false||allBox.get(indexTop).getNowTime()==TheBoxT.getNowTime()) && (allBox.get(indexBottom).isHadUse() == false||allBox.get(indexBottom).getNowTime()==TheBoxT.getNowTime())
&&(oneBoxItem.isHadUse() == false||oneBoxItem.getNowTime()==TheBoxT.getNowTime())) {
double time = System.currentTimeMillis();
canUse++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth ;
layoutParams.height = BoxHeight* 3;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexTop).getX());
addImage.setY((float) allBox.get(indexTop).getY());
addImage.setImageResource(R.drawable.i3x1);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
//先清除 在新增
//把之前的盛放的view给置空
TheBoxT.setHadUse(false);
for (int index_delete : list) {
allBox.get(index_delete).setHadUse(false);
allBox.get(index_delete).setHadUse(false);
}
TheBoxT.setHadUse(false);
//删除这个复制的图片
mainView.removeView(TheBoxT.getImageView());
mainView.removeView(showImage_Right);
//新增数据
mainView.addView(addImage);
//左侧这个的数据设置
oneBoxItem.setHadUse(true);
oneBoxItem.setIndex(1);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_A_New_3_Y);
//右侧这个数据的设置
allBox.get(indexTop).setIndex(0);
allBox.get(indexTop).setHadUse(true);
allBox.get(indexTop).setNowTime(time);
allBox.get(indexTop).setImageView(addImage);
allBox.get(indexTop).setBoxType(BoxTypes.Old_A_New_3_Y);
//左侧这个
allBox.get(indexBottom).setIndex(2);
allBox.get(indexBottom).setHadUse(true);
allBox.get(indexBottom).setNowTime(time);
allBox.get(indexBottom).setImageView(addImage);
allBox.get(indexBottom).setBoxType(BoxTypes.Old_A_New_3_Y);
//删除这个复制的图片
mainView.removeView(showImage_Right);
showImage_Right = null;
}
} catch (Exception e) {
Log.e("这个不合适三竖表箱", "===");
}
}
}
}else if(TheBoxT.getBoxType().equals(BoxTypes.New_4_Y)){
//现在点击的位置是纵向4个的第二个,算出其他三个的位置
List<Integer> list = new ArrayList<Integer>();
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
if (allBox.get(i).getNowTime() == TheBoxT.getNowTime() && !allBox.get(i).getID().equals(TheBoxT.getID())) {
list.add(i);
}
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if(x1 > oneBoxItem.getX() && x1 < oneBoxItem.getX() + BoxWidth && y1 > oneBoxItem.getY() && y1 < oneBoxItem.getY() + BoxHeight){
//表示是个格子
//顶部的这个
String ID_Top =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下一的这个
String ID_Bottom =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下部第二个
String ID_Bottom_2 =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+2) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
try {
int indexTop = (int) map.get(ID_Top);
int indexBottom = (int) map.get(ID_Bottom);
int indexBottom_2 = (int) map.get(ID_Bottom_2);
//判断左右两个是不是为空
if ((allBox.get(indexTop).isHadUse() == false||allBox.get(indexTop).getNowTime()==TheBoxT.getNowTime()) && (allBox.get(indexBottom).isHadUse() == false||allBox.get(indexBottom).getNowTime()==TheBoxT.getNowTime())
&&(oneBoxItem.isHadUse() == false||oneBoxItem.getNowTime()==TheBoxT.getNowTime())&&(allBox.get(indexBottom_2).isHadUse() == false||allBox.get(indexBottom_2).getNowTime()==TheBoxT.getNowTime())) {
double time = System.currentTimeMillis();
canUse++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth ;
layoutParams.height = BoxHeight* 4;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexTop).getX());
addImage.setY((float) allBox.get(indexTop).getY());
addImage.setImageResource(R.drawable.i4x1);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
//先清除 在新增
//把之前的盛放的view给置空
TheBoxT.setHadUse(false);
for (int index_delete : list) {
allBox.get(index_delete).setHadUse(false);
allBox.get(index_delete).setHadUse(false);
}
TheBoxT.setHadUse(false);
//删除这个复制的图片
mainView.removeView(TheBoxT.getImageView());
mainView.removeView(showImage_Right);
//新增数据
mainView.addView(addImage);
//左侧这个的数据设置
oneBoxItem.setIndex(1);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.New_4_Y);
allBox.get(indexTop).setIndex(0);
allBox.get(indexTop).setHadUse(true);
allBox.get(indexTop).setNowTime(time);
allBox.get(indexTop).setImageView(addImage);
allBox.get(indexTop).setBoxType(BoxTypes.New_4_Y);
//纵3
allBox.get(indexBottom).setIndex(2);
allBox.get(indexBottom).setHadUse(true);
allBox.get(indexBottom).setNowTime(time);
allBox.get(indexBottom).setImageView(addImage);
allBox.get(indexBottom).setBoxType(BoxTypes.New_4_Y);
allBox.get(indexBottom_2).setIndex(3);
allBox.get(indexBottom_2).setHadUse(true);
allBox.get(indexBottom_2).setNowTime(time);
allBox.get(indexBottom_2).setImageView(addImage);
allBox.get(indexBottom_2).setBoxType(BoxTypes.New_4_Y);
//删除这个复制的图片
mainView.removeView(showImage_Right);
showImage_Right = null;
}
} catch (Exception e) {
Log.e("这个不合适三竖表箱", "===");
}
}
}
}else if(TheBoxT.getBoxType().equals(BoxTypes.New_4_X)){
//现在点击的位置是横向4个的第二个,算出其他三个的位置
List<Integer> list = new ArrayList<Integer>();
//横4,以从上开始数的第二个作为这个点击的
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
if (allBox.get(i).getNowTime() == TheBoxT.getNowTime() && !allBox.get(i).getID().equals(TheBoxT.getID())) {
list.add(i);
}
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x1 > oneBoxItem.getX() && x1 < oneBoxItem.getX() + BoxWidth && y1 > oneBoxItem.getY() && y1 < oneBoxItem.getY() + BoxHeight) {
//纵向两个表箱的判断,假设这个是两个表箱上部的这个,呢么另一个的ID应该是XsY+1,对应ID中的数据AsB为 A+1,B
//左侧部的这个
String ID_Left =oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
//第一个右侧
String ID_Right =oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))+1 );
//右侧第二个
String ID_Right_2 =oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))+2 );
try {
int index_Left = (int) map.get(ID_Left);
int index_Right = (int) map.get(ID_Right);
int index_Right_2 = (int) map.get(ID_Right_2);
//判断左右两个是不是为空
if ((allBox.get(index_Left).isHadUse() == false||allBox.get(index_Left).getNowTime()==TheBoxT.getNowTime()) && (allBox.get(index_Right).isHadUse() == false||allBox.get(index_Right).getNowTime()==TheBoxT.getNowTime())
&&(oneBoxItem.isHadUse() == false||oneBoxItem.getNowTime()==TheBoxT.getNowTime())&&(allBox.get(index_Right_2).isHadUse() == false||allBox.get(index_Right_2).getNowTime()==TheBoxT.getNowTime())) {
double time = System.currentTimeMillis();
canUse++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth* 4 ;
layoutParams.height = BoxHeight;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(index_Left).getX());
addImage.setY((float) allBox.get(index_Left).getY());
addImage.setImageResource(R.drawable.i1x4);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
//先删除老数据
TheBoxT.setHadUse(false);
for (int index_delete : list) {
allBox.get(index_delete).setHadUse(false);
allBox.get(index_delete).setHadUse(false);
}
TheBoxT.setHadUse(false);
//删除这个复制的图片
mainView.removeView(TheBoxT.getImageView());
mainView.removeView(showImage_Right);
//删除完毕
mainView.addView(addImage);
//设置新增的数据
oneBoxItem.setIndex(1);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.New_4_X);
//
allBox.get(index_Left).setIndex(0);
allBox.get(index_Left).setHadUse(true);
allBox.get(index_Left).setNowTime(time);
allBox.get(index_Left).setImageView(addImage);
allBox.get(index_Left).setBoxType(BoxTypes.New_4_X);
//
allBox.get(index_Right).setIndex(2);
allBox.get(index_Right).setHadUse(true);
allBox.get(index_Right).setNowTime(time);
allBox.get(index_Right).setImageView(addImage);
allBox.get(index_Right).setBoxType(BoxTypes.New_4_X);
allBox.get(index_Right_2).setIndex(3);
allBox.get(index_Right_2).setHadUse(true);
allBox.get(index_Right_2).setNowTime(time);
allBox.get(index_Right_2).setImageView(addImage);
allBox.get(index_Right_2).setBoxType(BoxTypes.New_4_X);
//删除这个复制的图片
mainView.removeView(showImage_Right);
;
showImage_Right = null;
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}else if(TheBoxT.getBoxType().equals(BoxTypes.New_4_XY)){
//田子4,以从上开始数的第一个作为这个点击的,及左上角
List<Integer> list = new ArrayList<Integer>();
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
if (allBox.get(i).getNowTime() == TheBoxT.getNowTime() && !allBox.get(i).getID().equals(TheBoxT.getID())) {
list.add(i);
}
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x1 > oneBoxItem.getX() && x1 < oneBoxItem.getX() + BoxWidth && y1 > oneBoxItem.getY() && y1 < oneBoxItem.getY() + BoxHeight) {
//纵向两个表箱的判断,假设这个是两个表箱上部的这个,呢么另一个的ID应该是XsY+1,对应ID中的数据AsB为 A+1,B
//上部的这个
String ID_Top_Right =oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
//下部第一个
String ID_Bottom_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下部第二个
String ID_Bottom_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
try {
int indexTop_Right = (int) map.get(ID_Top_Right);
int indexBottom_Left = (int) map.get(ID_Bottom_Left);
int indexBottom_Right = (int) map.get(ID_Bottom_Right);
//判断左右两个是不是为空
if ((allBox.get(indexTop_Right).isHadUse() == false||allBox.get(indexTop_Right).getNowTime()==TheBoxT.getNowTime()) && (allBox.get(indexBottom_Left).isHadUse() == false||allBox.get(indexBottom_Left).getNowTime()==TheBoxT.getNowTime())
&&(oneBoxItem.isHadUse() == false||oneBoxItem.getNowTime()==TheBoxT.getNowTime())&&(allBox.get(indexBottom_Right).isHadUse() == false||allBox.get(indexBottom_Right).getNowTime()==TheBoxT.getNowTime())) {
double time = System.currentTimeMillis();
canUse++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth*2 ;
layoutParams.height = BoxHeight* 2;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) oneBoxItem.getX());
addImage.setY((float) oneBoxItem.getY());
addImage.setImageResource(R.drawable.i2x2);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
//清空操作
//先删除老数据
TheBoxT.setHadUse(false);
for (int index_delete : list) {
allBox.get(index_delete).setHadUse(false);
allBox.get(index_delete).setHadUse(false);
}
TheBoxT.setHadUse(false);
//删除这个复制的图片
mainView.removeView(TheBoxT.getImageView());
mainView.removeView(showImage_Right);
showImage_Right = null;
//删除完毕
mainView.addView(addImage);
//设置新增的数据
oneBoxItem.setIndex(0);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.New_4_XY);
//
allBox.get(indexTop_Right).setIndex(1);
allBox.get(indexTop_Right).setHadUse(true);
allBox.get(indexTop_Right).setNowTime(time);
allBox.get(indexTop_Right).setImageView(addImage);
allBox.get(indexTop_Right).setBoxType(BoxTypes.New_4_XY);
//
allBox.get(indexBottom_Left).setIndex(2);
allBox.get(indexBottom_Left).setHadUse(true);
allBox.get(indexBottom_Left).setNowTime(time);
allBox.get(indexBottom_Left).setImageView(addImage);
allBox.get(indexBottom_Left).setBoxType(BoxTypes.New_4_XY);
allBox.get(indexBottom_Right).setIndex(3);
allBox.get(indexBottom_Right).setHadUse(true);
allBox.get(indexBottom_Right).setNowTime(time);
allBox.get(indexBottom_Right).setImageView(addImage);
allBox.get(indexBottom_Right).setBoxType(BoxTypes.New_4_XY);
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}else if(TheBoxT.getBoxType().equals(BoxTypes.Old_A_New_6_Y)){
List<Integer> list = new ArrayList<Integer>();
//田子6,纵向的,这个触摸点为左侧第二排的格子
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
if (allBox.get(i).getNowTime() == TheBoxT.getNowTime() && !allBox.get(i).getID().equals(TheBoxT.getID())) {
list.add(i);
}
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x1 > oneBoxItem.getX() && x1 < oneBoxItem.getX() + BoxWidth && y1 > oneBoxItem.getY() && y1 < oneBoxItem.getY() + BoxHeight) {
//当前为第二排左侧
//上部左侧
String ID_Top_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//上部的右侧
String ID_Top_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
//正右侧
String ID_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
//下部第一个
String ID_Bottom_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下部第二个
String ID_Bottom_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
try {
int indexTop_Left = (int) map.get(ID_Top_Left);
int indexTop_Right = (int) map.get(ID_Top_Right);
int indexRight = (int) map.get(ID_Right);
int indexBottom_Left = (int) map.get(ID_Bottom_Left);
int indexBottom_Right = (int) map.get(ID_Bottom_Right);
//判断左右两个是不是为空
if ((allBox.get(indexTop_Left).isHadUse() == false||allBox.get(indexTop_Left).getNowTime()==TheBoxT.getNowTime()) &&
(allBox.get(indexTop_Right).isHadUse() == false||allBox.get(indexTop_Right).getNowTime()==TheBoxT.getNowTime())&&
(oneBoxItem.isHadUse() == false||oneBoxItem.getNowTime()==TheBoxT.getNowTime())&&
(allBox.get(indexRight).isHadUse() == false||allBox.get(indexRight).getNowTime()==TheBoxT.getNowTime())&&
(allBox.get(indexBottom_Left).isHadUse() == false||allBox.get(indexBottom_Left).getNowTime()==TheBoxT.getNowTime()) &&
(allBox.get(indexBottom_Right).isHadUse() == false||allBox.get(indexBottom_Right).getNowTime()==TheBoxT.getNowTime())
) {
double time = System.currentTimeMillis();
canUse++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth*2 ;
layoutParams.height = BoxHeight* 3;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexTop_Left).getX());
addImage.setY((float) allBox.get(indexTop_Left).getY());
addImage.setImageResource(R.drawable.i3x2);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
//清空操作
//先删除老数据
TheBoxT.setHadUse(false);
for (int index_delete : list) {
allBox.get(index_delete).setHadUse(false);
allBox.get(index_delete).setHadUse(false);
}
TheBoxT.setHadUse(false);
//删除这个复制的图片
mainView.removeView(TheBoxT.getImageView());
mainView.removeView(showImage_Right);
showImage_Right = null;
//删除完毕
//清空完毕
mainView.addView(addImage);
//设置新增的数据
oneBoxItem.setIndex(2);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_A_New_6_Y);
//
allBox.get(indexTop_Left).setIndex(0);
allBox.get(indexTop_Left).setHadUse(true);
allBox.get(indexTop_Left).setNowTime(time);
allBox.get(indexTop_Left).setImageView(addImage);
allBox.get(indexTop_Left).setBoxType(BoxTypes.Old_A_New_6_Y);
//
allBox.get(indexTop_Right).setIndex(1);
allBox.get(indexTop_Right).setHadUse(true);
allBox.get(indexTop_Right).setNowTime(time);
allBox.get(indexTop_Right).setImageView(addImage);
allBox.get(indexTop_Right).setBoxType(BoxTypes.Old_A_New_6_Y);
allBox.get(indexRight).setIndex(3);
allBox.get(indexRight).setHadUse(true);
allBox.get(indexRight).setNowTime(time);
allBox.get(indexRight).setImageView(addImage);
allBox.get(indexRight).setBoxType(BoxTypes.Old_A_New_6_Y);
allBox.get(indexBottom_Left).setIndex(4);
allBox.get(indexBottom_Left).setHadUse(true);
allBox.get(indexBottom_Left).setNowTime(time);
allBox.get(indexBottom_Left).setImageView(addImage);
allBox.get(indexBottom_Left).setBoxType(BoxTypes.Old_A_New_6_Y);
allBox.get(indexBottom_Right).setIndex(5);
allBox.get(indexBottom_Right).setHadUse(true);
allBox.get(indexBottom_Right).setNowTime(time);
allBox.get(indexBottom_Right).setImageView(addImage);
allBox.get(indexBottom_Right).setBoxType(BoxTypes.Old_A_New_6_Y);
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}else if(TheBoxT.getBoxType().equals(BoxTypes.Old_6_X)){
List<Integer> list = new ArrayList<Integer>();
//田子6,纵向的,这个触摸点为第一排第二个的格子
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
if (allBox.get(i).getNowTime() == TheBoxT.getNowTime() && !allBox.get(i).getID().equals(TheBoxT.getID())) {
list.add(i);
}
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x1 > oneBoxItem.getX() && x1 < oneBoxItem.getX() + BoxWidth && y1 > oneBoxItem.getY() && y1 < oneBoxItem.getY() + BoxHeight
) {
//当前为第一排第二个
//上部左侧
String ID_Top_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
//上部的右侧
String ID_Top_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
//下部正右
String ID_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下部第一个
String ID_Bottom_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
//下部第二个
String ID_Bottom_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
try {
int indexTop_Left = (int) map.get(ID_Top_Left);
int indexTop_Right = (int) map.get(ID_Top_Right);
int indexRight = (int) map.get(ID_Right);
int indexBottom_Left = (int) map.get(ID_Bottom_Left);
int indexBottom_Right = (int) map.get(ID_Bottom_Right);
//判断左右两个是不是为空
if ((allBox.get(indexTop_Left).isHadUse() == false||allBox.get(indexTop_Left).getNowTime()==TheBoxT.getNowTime()) &&
(allBox.get(indexTop_Right).isHadUse() == false||allBox.get(indexTop_Right).getNowTime()==TheBoxT.getNowTime())&&
(oneBoxItem.isHadUse() == false||oneBoxItem.getNowTime()==TheBoxT.getNowTime())&&
(allBox.get(indexRight).isHadUse() == false||allBox.get(indexRight).getNowTime()==TheBoxT.getNowTime())&&
(allBox.get(indexBottom_Left).isHadUse() == false||allBox.get(indexBottom_Left).getNowTime()==TheBoxT.getNowTime()) &&
(allBox.get(indexBottom_Right).isHadUse() == false||allBox.get(indexBottom_Right).getNowTime()==TheBoxT.getNowTime())
) {
double time = System.currentTimeMillis();
canUse++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth*3 ;
layoutParams.height = BoxHeight* 2;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexTop_Left).getX());
addImage.setY((float) allBox.get(indexTop_Left).getY());
addImage.setImageResource(R.drawable.i2x3);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
//清空操作
//先删除老数据
TheBoxT.setHadUse(false);
for (int index_delete : list) {
allBox.get(index_delete).setHadUse(false);
allBox.get(index_delete).setHadUse(false);
}
TheBoxT.setHadUse(false);
//删除这个复制的图片
mainView.removeView(TheBoxT.getImageView());
mainView.removeView(showImage_Right);
showImage_Right = null;
//删除完毕
mainView.addView(addImage);
//设置新增的数据
oneBoxItem.setIndex(1);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_6_X);
//
allBox.get(indexTop_Left).setIndex(0);
allBox.get(indexTop_Left).setHadUse(true);
allBox.get(indexTop_Left).setNowTime(time);
allBox.get(indexTop_Left).setImageView(addImage);
allBox.get(indexTop_Left).setBoxType(BoxTypes.Old_6_X);
//
allBox.get(indexTop_Right).setIndex(2);
allBox.get(indexTop_Right).setHadUse(true);
allBox.get(indexTop_Right).setNowTime(time);
allBox.get(indexTop_Right).setImageView(addImage);
allBox.get(indexTop_Right).setBoxType(BoxTypes.Old_6_X);
allBox.get(indexRight).setIndex(4);
allBox.get(indexRight).setHadUse(true);
allBox.get(indexRight).setNowTime(time);
allBox.get(indexRight).setImageView(addImage);
allBox.get(indexRight).setBoxType(BoxTypes.Old_6_X);
allBox.get(indexBottom_Left).setIndex(3);
allBox.get(indexBottom_Left).setHadUse(true);
allBox.get(indexBottom_Left).setNowTime(time);
allBox.get(indexBottom_Left).setImageView(addImage);
allBox.get(indexBottom_Left).setBoxType(BoxTypes.Old_6_X);
allBox.get(indexBottom_Right).setIndex(5);
allBox.get(indexBottom_Right).setHadUse(true);
allBox.get(indexBottom_Right).setNowTime(time);
allBox.get(indexBottom_Right).setImageView(addImage);
allBox.get(indexBottom_Right).setBoxType(BoxTypes.Old_6_X);
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}else if(TheBoxT.getBoxType().equals(BoxTypes.Old_A_New_9_XY)){
List<Integer> list = new ArrayList<Integer>();
//田子9,这个触摸点为最中间
Map map = new HashMap();
for (int i = 0; i < allBox.size(); i++) {
map.put(allBox.get(i).getID(), i);
if (allBox.get(i).getNowTime() == TheBoxT.getNowTime() && !allBox.get(i).getID().equals(TheBoxT.getID())) {
list.add(i);
}
}
for (int i = 0; i < allBox.size(); i++) {
OneBoxItem oneBoxItem = allBox.get(i);
if (x1 > oneBoxItem.getX() && x1 < oneBoxItem.getX() + BoxWidth && y1> oneBoxItem.getY() && y1 < oneBoxItem.getY() + BoxHeight
) {
//当前为第一排第二个
//上部左侧
String ID_Top_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
String ID_Top_Zhong =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))-1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//上部的右侧
String ID_Top_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
//中间的一左一右
String ID_Zhong_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
String ID_Zhong_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))+1 );
//下部第一个
String ID_Bottom_Left =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length()))-1 );
//下部正中
String ID_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) );
//下部第二个
String ID_Bottom_Right =String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(0, oneBoxItem.getID().indexOf("s")))+1) + "s" + String.valueOf(Integer.parseInt(oneBoxItem.getID().substring(oneBoxItem.getID().indexOf("s") + 1, oneBoxItem.getID().length())) +1);
try {
int indexTop_Left = (int) map.get(ID_Top_Left);
int indexTop_Right = (int) map.get(ID_Top_Right);
int indexRight = (int) map.get(ID_Right);
//新增的
int indexTop_Zhong = (int) map.get(ID_Top_Zhong);
int indexZhong_Left = (int) map.get(ID_Zhong_Left);
int indexZhong_Right = (int) map.get(ID_Zhong_Right);
//
int indexBottom_Left = (int) map.get(ID_Bottom_Left);
int indexBottom_Right = (int) map.get(ID_Bottom_Right);
//判断左右两个是不是为空
if ((allBox.get(indexTop_Left).isHadUse() == false||allBox.get(indexTop_Left).getNowTime()==TheBoxT.getNowTime()) &&
(allBox.get(indexTop_Right).isHadUse() == false||allBox.get(indexTop_Right).getNowTime()==TheBoxT.getNowTime())&&
(oneBoxItem.isHadUse() == false||oneBoxItem.getNowTime()==TheBoxT.getNowTime())&&
(allBox.get(indexRight).isHadUse() == false||allBox.get(indexRight).getNowTime()==TheBoxT.getNowTime())&&
(allBox.get(indexTop_Zhong).isHadUse() == false||allBox.get(indexTop_Zhong).getNowTime()==TheBoxT.getNowTime()) &&
(allBox.get(indexZhong_Left).isHadUse() == false||allBox.get(indexZhong_Left).getNowTime()==TheBoxT.getNowTime())&&
(allBox.get(indexZhong_Right).isHadUse() == false||allBox.get(indexZhong_Right).getNowTime()==TheBoxT.getNowTime())&&
(allBox.get(indexBottom_Left).isHadUse() == false||allBox.get(indexBottom_Left).getNowTime()==TheBoxT.getNowTime())&&
(allBox.get(indexBottom_Right).isHadUse() == false||allBox.get(indexBottom_Right).getNowTime()==TheBoxT.getNowTime())
) {
double time = System.currentTimeMillis();
canUse++;
//实例出来一个新的表箱,用来添加到右侧页面上
ImageView addImage = new ImageView(MainActivity.this);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.width = BoxWidth*3 ;
layoutParams.height = BoxHeight*3;
addImage.setLayoutParams(layoutParams);
addImage.setX((float) allBox.get(indexTop_Left).getX());
addImage.setY((float) allBox.get(indexTop_Left).getY());
addImage.setImageResource(R.drawable.i3x3);
addImage.setBackground(getResources().getDrawable(R.drawable.shape_rect));
//清空老数据
TheBoxT.setHadUse(false);
for (int index_delete : list) {
allBox.get(index_delete).setHadUse(false);
allBox.get(index_delete).setHadUse(false);
}
TheBoxT.setHadUse(false);
//删除这个复制的图片
mainView.removeView(TheBoxT.getImageView());
mainView.removeView(showImage_Right);
showImage_Right = null;
//设置新增的数据
oneBoxItem.setIndex(4);
mainView.addView(addImage);
oneBoxItem.setHadUse(true);
oneBoxItem.setNowTime(time);
oneBoxItem.setImageView(addImage);
oneBoxItem.setBoxType(BoxTypes.Old_A_New_9_XY);
//
allBox.get(indexTop_Zhong).setIndex(1);
allBox.get(indexTop_Zhong).setHadUse(true);
allBox.get(indexTop_Zhong).setNowTime(time);
allBox.get(indexTop_Zhong).setImageView(addImage);
allBox.get(indexTop_Zhong).setBoxType(BoxTypes.Old_A_New_9_XY);
//
allBox.get(indexZhong_Left).setIndex(3);
allBox.get(indexZhong_Left).setHadUse(true);
allBox.get(indexZhong_Left).setNowTime(time);
allBox.get(indexZhong_Left).setImageView(addImage);
allBox.get(indexZhong_Left).setBoxType(BoxTypes.Old_A_New_9_XY);
//
allBox.get(indexZhong_Left).setIndex(5);
allBox.get(indexZhong_Right).setHadUse(true);
allBox.get(indexZhong_Right).setNowTime(time);
allBox.get(indexZhong_Right).setImageView(addImage);
allBox.get(indexZhong_Right).setBoxType(BoxTypes.Old_A_New_9_XY);
//
allBox.get(indexTop_Left).setIndex(0);
allBox.get(indexTop_Left).setHadUse(true);
allBox.get(indexTop_Left).setNowTime(time);
allBox.get(indexTop_Left).setImageView(addImage);
allBox.get(indexTop_Left).setBoxType(BoxTypes.Old_A_New_9_XY);
//
allBox.get(indexTop_Right).setIndex(2);
allBox.get(indexTop_Right).setHadUse(true);
allBox.get(indexTop_Right).setNowTime(time);
allBox.get(indexTop_Right).setImageView(addImage);
allBox.get(indexTop_Right).setBoxType(BoxTypes.Old_A_New_9_XY);
allBox.get(indexRight).setIndex(7);
allBox.get(indexRight).setHadUse(true);
allBox.get(indexRight).setNowTime(time);
allBox.get(indexRight).setImageView(addImage);
allBox.get(indexRight).setBoxType(BoxTypes.Old_A_New_9_XY);
allBox.get(indexBottom_Left).setIndex(6);
allBox.get(indexBottom_Left).setHadUse(true);
allBox.get(indexBottom_Left).setNowTime(time);
allBox.get(indexBottom_Left).setImageView(addImage);
allBox.get(indexBottom_Left).setBoxType(BoxTypes.Old_A_New_9_XY);
allBox.get(indexBottom_Right).setIndex(8);
allBox.get(indexBottom_Right).setHadUse(true);
allBox.get(indexBottom_Right).setNowTime(time);
allBox.get(indexBottom_Right).setImageView(addImage);
allBox.get(indexBottom_Right).setBoxType(BoxTypes.Old_A_New_9_XY);
}
} catch (Exception e) {
Log.e("这个不合适二横表箱", "===");
}
}
}
}//这里写下一个
if (canUse == 0) {
mainView.removeView(showImage_Right);
Toast.makeText(MainActivity.this, "该位置无效,请重试", Toast.LENGTH_SHORT).show();
}
}
}
}
needToMove = false;
TheBoxT = null;
break;
}
return true;
}
});
}
/**
* 当从右侧往左侧拖动表箱时候的操作,根据表箱的类型,实现不同类型图片的显示
*
* @param x 触摸点的X
* @param y 触摸点的Y
* @param boxTYpe 这个表箱实例的类型
* @return
*/
private void withRightOnTuch(float x, float y, OneBoxItem boxTYpe) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) showImage_Right.getLayoutParams();
showImage_Right.setX(x - layoutParams.width / 2);
showImage_Right.setY(y - layoutParams.height / 2);
}
}
| true |
9c39e23e7193a09cd20000d625551a0e5e910e95
|
Java
|
Kishan242/InfoNepalNew
|
/app/src/main/java/com/drac_android/infonepal/ServerResponse/ActivationResponse.java
|
UTF-8
| 702 | 2.046875 | 2 |
[] |
no_license
|
package com.drac_android.infonepal.ServerResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
public class ActivationResponse {
@SerializedName("Success")
public boolean success;
@SerializedName("ErrorCode")
public int errorCode;
@SerializedName("ErrorMessage")
public String error;
@SerializedName("Data")
public String activationcode;
public static ActivationResponse parseActivation(String loginJson){
Gson gson = new GsonBuilder().create();
ActivationResponse response = gson.fromJson(loginJson, ActivationResponse.class);
return response;
}
}
| true |
fedc0264b9acbaaa241ea5206fe7109033cfdf3b
|
Java
|
luism94/Mastermind
|
/src/codes/Computer.java
|
UTF-8
| 1,179 | 3.015625 | 3 |
[] |
no_license
|
package codes;
import static codes.GameMode.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import static codes.Colors.*;
public class Computer {
private GameMode gm;
private Combination secretComb;
public Computer(GameMode mode) {
gm = mode;
secretComb = new Combination(gm);
if (!gm.repeatedColors()) {
secretComb.createSecretCombinationNoRepetition();
} else {
secretComb.createSecretCombinationWithRepetition();
}
System.out.println(secretComb); //se muestra en pantalla para pruebas
}
public Combination getSecretComb() {
return secretComb;
}
private void setSecretComb(Combination secretComb) {
this.secretComb = secretComb;
}
public String compareCombinations(Combination playerComb) {
//En la comb de la respuesta se coloca una ficha roja, blanca o nada en la posicion oportuna
String solution = "";
if (gm.repeatedColors()) {
solution = secretComb.checkPlayerCombinationWithRepetition(playerComb);
} else {
solution = secretComb.checkPlayerCombinationNoRepetition(playerComb);
}
return solution;
}
}
| true |
11b6c1a88e47b179cc4035b4b2775b9f8aab177b
|
Java
|
Lakaz720/ML_project
|
/app/src/main/java/com/kimhyemi/bombelab/lakaz/monstar_lab_test/HomeItem.java
|
UTF-8
| 1,698 | 2.28125 | 2 |
[] |
no_license
|
package com.kimhyemi.bombelab.lakaz.monstar_lab_test;
import java.net.URL;
/**
* Created by Pomiring on 2017-07-26.
*/
public class HomeItem {
//int image;
public String image;
public String story;
/*public String color_set;
public String image_url;
public String sns_code;
public String user_id;
public String company;*/
public HomeItem(){}
public String getImage() {
return this.image;
}
public String getStory() {return this.story;}
/*public String getColor_set(){return color_set;}
public String getImage_url(){return image_url;}
public String getSns_code(){return sns_code;}
public String getUser_id(){return user_id;}
public String getCompany(){return company;}*/
//String getStory(){return this.story;}
/*String[] getColor(){return this.color_set;}
URL getImage_url(){return this.image_url;}
String getSns_code(){return this.sns_code;}
String getUser_id(){return this.user_id;}*/
/*HomeItem(int image, String title, String[] color_set,
URL image_url, String sns_code, String user_id) {*/
/*public HomeItem(String image, String story, String color_set,String image_url
, String sns_code, String user_id, String company) {*/
public HomeItem(String image, String story) {
this.image = image;
this.story = story;
/*this.color_set = color_set;
this.image_url = image_url;
this.sns_code = sns_code;
this.user_id = user_id;
this.company = company;*/
/*this.color_set = color_set;
this.image_url = image_url;
this.sns_code = sns_code;
this.user_id = user_id;*/
}
}
| true |
7744fa86726f90893d1405dbe147d442d9b7c651
|
Java
|
Maryam-G/AP-MidtermProject-Phase3
|
/Insomnia-3/src/com/company/jurl/Main.java
|
UTF-8
| 542 | 2.6875 | 3 |
[] |
no_license
|
package com.company.jurl;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import com.company.jurl.Jurl;
import javax.imageio.ImageIO;
/**
* A class for testing JurlApp and get input
*
* @author Maryam Goli
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String newLine;
while(true){
newLine = scanner.nextLine();
Jurl jurl = new Jurl(newLine);
}
}
}
| true |
495f99b7a567fb554764c183d1dd39dedd4672fb
|
Java
|
bar47ney/laba_two
|
/src/Maybe/WorkersListWindow.java
|
UTF-8
| 2,829 | 2.84375 | 3 |
[] |
no_license
|
package Maybe;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Created by Сергей on 04.04.2019.
*/
public class WorkersListWindow
{
private int x;
private int y = 2;
public void display(Stage primaryStage, ArrayList<Worker> wl)
{
Stage getInfoStage = new Stage();
getInfoStage.setResizable(false);
BorderPane root = new BorderPane();
Scene scene = new Scene(root,1200,700);
GridPane gridpane = new GridPane();
gridpane.setPadding(new Insets(10));
gridpane.setHgap(44);
gridpane.setVgap(5);
getInfoStage.initModality(Modality.WINDOW_MODAL);
getInfoStage.initOwner(primaryStage);
Label label = new Label("Рабочие");
gridpane.add(label,2,0);
label = new Label("Имя");
gridpane.add(label,0,1);
label = new Label("Фамилия");
gridpane.add(label,1,1);
label = new Label("Улица");
gridpane.add(label,2,1);
label = new Label("Квартира");
gridpane.add(label,3,1);
label = new Label("Дом");
gridpane.add(label,4,1);
label = new Label("Место работы");
gridpane.add(label,5,1);
label = new Label("Статус");
gridpane.add(label,6,1);
Iterator<Worker> iter = wl.iterator();
while (iter.hasNext())
{
Worker wor = iter.next();
x = 0;
label = new Label(wor.getFirstName());
gridpane.add(label,x,y);
x++;
label = new Label(wor.getLastName());
gridpane.add(label,x,y);
label = new Label(wor.getActivity());
gridpane.add(label,5,y);
label = new Label(wor.getStatus());
gridpane.add(label,6,y);
if(wor.address != null)
{
x++;
label = new Label(wor.address.getStreet());
gridpane.add(label,x,y);
x++;
label = new Label(wor.address.getHouse());
gridpane.add(label,x,y);
x++;
label = new Label(wor.address.getFlat());
gridpane.add(label,x,y);
}
else
{
label = new Label("Нет адреса");
gridpane.add(label,3,y);
}
y++;
}
root.setCenter(gridpane);
getInfoStage.setScene(scene);
getInfoStage.show();
}
}
| true |
c2073b87cc28258ac6af33f750777e7a0ca4526d
|
Java
|
fabiorapanelo/ecommerce
|
/business/src/main/java/com/fabiorapanelo/order/Order.java
|
UTF-8
| 1,005 | 2.390625 | 2 |
[] |
no_license
|
package com.fabiorapanelo.order;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "TB_ORDER")
@XmlRootElement(name = "order")
public class Order {
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "ORDER_ID")
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "order")
private Set<OrderItem> items = new HashSet<OrderItem>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<OrderItem> getItems() {
return items;
}
public void setItems(Set<OrderItem> items) {
this.items = items;
}
}
| true |
790577d6e754a0ce9cf9c388777eff6b7eb715fa
|
Java
|
DaniloJevtovic/poslovnaInformatika
|
/project/app/models/NaseljenoMesto.java
|
UTF-8
| 1,191 | 2.140625 | 2 |
[] |
no_license
|
package models;
import java.util.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import models.constants.KonstanteNaseljenogMjesta;
import play.data.validation.Max;
import play.db.jpa.Model;
@Entity
public class NaseljenoMesto extends Model {
public String oznaka;
@Column(unique=false, nullable=false, length=KonstanteNaseljenogMjesta.MAKSIMALNA_DUZINA_NAZIV)
public String naziv;
@Column(unique=false, nullable=false, length=KonstanteNaseljenogMjesta.MAKSIMALNA_DUZINA_PTT)
public String postanskiBroj;
@ManyToOne
public Drzava drzava;
@OneToMany(mappedBy = "naseljenoMjesto")
public List<AnalitikaIzvoda> analitikeIzvoda;
public NaseljenoMesto(String oznaka, String naziv, String postanskiBroj, Drzava drzava) {
// TODO Auto-generated constructor stub
super();
this.oznaka = oznaka;
this.naziv = naziv;
this.postanskiBroj = postanskiBroj;
this.drzava = drzava;
}
public NaseljenoMesto(String oznaka, String naziv, String pb) {
// TODO Auto-generated constructor stub
super();
this.oznaka = oznaka;
this.naziv = naziv;
this.postanskiBroj = pb;
}
}
| true |
cf384ee046aec5c37ec42091b5ad7790b7443ec6
|
Java
|
Cyecize/TimeReporter
|
/src/main/java/com/cyecize/reporter/app/bindingModels/CreateTaskBindingModel.java
|
UTF-8
| 2,233 | 2.21875 | 2 |
[] |
no_license
|
package com.cyecize.reporter.app.bindingModels;
import com.cyecize.reporter.app.dataAdapters.IdToProjectAdapter;
import com.cyecize.reporter.app.dataAdapters.IdToTaskAdapter;
import com.cyecize.reporter.app.entities.Project;
import com.cyecize.reporter.app.entities.Task;
import com.cyecize.reporter.common.dataAdapters.LocalDateAdapter;
import com.cyecize.summer.areas.validation.annotations.ConvertedBy;
import com.cyecize.summer.areas.validation.constraints.MaxLength;
import com.cyecize.summer.areas.validation.constraints.NotNull;
import java.time.LocalDateTime;
import static com.cyecize.reporter.common.ValidationConstants.MAX_NAME_LENGTH;
import static com.cyecize.reporter.common.ValidationMessageConstants.EMPTY_FIELD;
import static com.cyecize.reporter.common.ValidationMessageConstants.TEXT_TOO_LONG;
public class CreateTaskBindingModel {
@NotNull(message = EMPTY_FIELD)
@MaxLength(length = MAX_NAME_LENGTH, message = TEXT_TOO_LONG)
private String taskName;
@NotNull(message = EMPTY_FIELD)
@ConvertedBy(LocalDateAdapter.class)
private LocalDateTime startDate;
@ConvertedBy(LocalDateAdapter.class)
private LocalDateTime endDate;
@NotNull(message = EMPTY_FIELD)
@ConvertedBy(IdToProjectAdapter.class)
private Project project;
@ConvertedBy(IdToTaskAdapter.class)
private Task parentTask;
public CreateTaskBindingModel() {
}
public String getTaskName() {
return this.taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public LocalDateTime getStartDate() {
return this.startDate;
}
public void setStartDate(LocalDateTime startDate) {
this.startDate = startDate;
}
public LocalDateTime getEndDate() {
return this.endDate;
}
public void setEndDate(LocalDateTime endDate) {
this.endDate = endDate;
}
public Project getProject() {
return this.project;
}
public void setProject(Project project) {
this.project = project;
}
public Task getParentTask() {
return this.parentTask;
}
public void setParentTask(Task parentTask) {
this.parentTask = parentTask;
}
}
| true |
cfdcac33d2ed149d64eb2d4903b709afdd71e7cc
|
Java
|
ZRonchy/Algorithms
|
/src/main/java/leetcode/TreeTrie/BalancedBinaryTree.java
|
UTF-8
| 1,635 | 4.03125 | 4 |
[] |
no_license
|
package leetcode.TreeTrie;
// Given a binary tree, determine if it is height-balanced.
// For this problem, a height-balanced binary tree is defined as
// a binary tree in which the depth of the two subtrees of every node
// never differ by more than 1.
public class BalancedBinaryTree {
/*Solution 1*/
public boolean isBalanced(TreeNode root) {
if (root == null)
return true;
if (getHeight(root) == -1)
return false;
return true;
}
public int getHeight(TreeNode root) {
if (root == null)
return 0;
int left = getHeight(root.left);
int right = getHeight(root.right);
if (left == -1 || right == -1)
return -1;
if (Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
/**
* Solution 2
* the difference of min depth and max depth should not exceed 1,
* since the difference of the min and the max depth is the maximum distance difference
* possible in the tree.
*/
public static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1+Math.max(maxDepth(root.left), maxDepth(root.right));
}
public static int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1+Math.min(minDepth(root.left), minDepth(root.right));
}
public static boolean isBalanced1(TreeNode root) {
return (maxDepth(root) - minDepth(root) <= 1);
}
}
| true |
9c32e43d07a267b3622235327c85b8b3990f0554
|
Java
|
sanghyukAnim/Counter_App
|
/src/main/java/com/example/moon/counter/Spends.java
|
UTF-8
| 612 | 2.859375 | 3 |
[] |
no_license
|
package com.example.moon.counter;
import android.graphics.drawable.Drawable;
/**
* Created by moon on 2017. 6. 7..
*/
public class Spends {
private String name;
public int total;
public Spends(String name) {
this.name = name;
}
public void setTotal(int total) {
this.total = this.total+total;
}
public String getName() {
return this.name;
}
public int getTotal() {
return this.total;
}
@Override
public String toString() {
Integer num = total;
String str = Integer.toString(num);
return str;
}
}
| true |
30634f585aba4bf41be088369505b54421d941bf
|
Java
|
zhuanglm/HostBridge
|
/epoctest/src/main/java/com/epocal/epoctest/analyticalmanager/AMFileUtil.java
|
UTF-8
| 6,273 | 2.109375 | 2 |
[] |
no_license
|
package com.epocal.epoctest.analyticalmanager;
import com.epocal.common.globaldi.GloabalObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import android.util.Log;
/**
* DEBUG utility class to write byte stream to file and read byte stream from file.
*
* These methods are used to write protocol buffer encoded data to a file for DEBUGGING purposes.
* File is written to device's internal storage: Android/data/com.epocal.host4/files/
*/
public class AMFileUtil {
private static final String AMTAG = AnalyticalManager.class.getSimpleName();
// The name of subfolder where files are saved in the internal storage under the root folder of this app.
private static final String SUBFOLDER_NAME = "AM";
// The name of files where method request (serialized request) are stored.
private static final String REQ_FILE_CHECK_FOR_EARLY_INJECTION = "CheckForEarlyInjectionRequest.buf";
private static final String REQ_FILE_PERFORM_REALTIME_QC = "PerformRealtimeQCRequest.buf";
private static final String REQ_FILE_CALCULATE_BGE = "CalculateBGERequest.buf";
private static final String REQ_FILE_COMPUTE_CALCULATED_RESULTS = "ComputeCalculatedResultsRequest.buf";
private static final String REQ_FILE_COMPUTE_CORRECTED_RESULTS = "ComputeCorrectedResultsRequest.buf";
// The name of files where method response (serialized request) are stored.
private static final String RESP_FILE_CHECK_FOR_EARLY_INJECTION = "CheckForEarlyInjectionResponse.buf";
private static final String RESP_FILE_PERFORM_REALTIME_QC = "PerformRealtimeQCResponse.buf";
private static final String RESP_FILE_CALCULATE_BGE = "CalculateBGEResponse.buf";
private static final String RESP_FILE_COMPUTE_CALCULATED_RESULTS = "ComputeCalculatedResultsResponse.buf";
private static final String RESP_FILE_COMPUTE_CORRECTED_RESULTS = "ComputeCorrectedResultsResponse.buf";
// Enum to define which method's buffer is being read from, or writen to
public enum AMMethod {
bgeCheckForEarlyInjection,
bgePerformRealTimeQC,
bgeCalculateBGE,
bgeComputeCalculatedResults,
bgeComputeCorrectedResults;
}
private static final Map<AMMethod, String> REQ_BUFFER_FILENAME;
static {
Map<AMMethod, String> map = new HashMap<>();
map.put(AMMethod.bgeCheckForEarlyInjection, REQ_FILE_CHECK_FOR_EARLY_INJECTION);
map.put(AMMethod.bgePerformRealTimeQC, REQ_FILE_PERFORM_REALTIME_QC);
map.put(AMMethod.bgeCalculateBGE, REQ_FILE_CALCULATE_BGE);
map.put(AMMethod.bgeComputeCalculatedResults, REQ_FILE_COMPUTE_CALCULATED_RESULTS);
map.put(AMMethod.bgeComputeCorrectedResults, REQ_FILE_COMPUTE_CORRECTED_RESULTS);
REQ_BUFFER_FILENAME = Collections.unmodifiableMap(map);
}
private static final Map<AMMethod, String> RESP_BUFFER_FILENAME;
static {
Map<AMMethod, String> map = new HashMap<>();
map.put(AMMethod.bgeCheckForEarlyInjection, RESP_FILE_CHECK_FOR_EARLY_INJECTION);
map.put(AMMethod.bgePerformRealTimeQC, RESP_FILE_PERFORM_REALTIME_QC);
map.put(AMMethod.bgeCalculateBGE, RESP_FILE_CALCULATE_BGE);
map.put(AMMethod.bgeComputeCalculatedResults, RESP_FILE_COMPUTE_CALCULATED_RESULTS);
map.put(AMMethod.bgeComputeCorrectedResults, RESP_FILE_COMPUTE_CORRECTED_RESULTS);
RESP_BUFFER_FILENAME = Collections.unmodifiableMap(map);
}
private static byte[] readBufferFromFile(String subFolder, String fileName) {
File dir = GloabalObject.getApplication().getApplicationContext().getExternalFilesDir(subFolder);
if (!dir.exists()) {
return null;
}
File file = new File(dir, fileName);
if (!file.exists()) {
return null;
}
FileInputStream fileInputStream = null;
byte[] bFile = new byte[(int) file.length()];
try {
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bFile;
}
private static boolean writeBufferToFile(String subFolder, String fileName, byte[] bFile) {
FileOutputStream fileOuputStream = null;
try {
File dir = GloabalObject.getApplication().getApplicationContext().getExternalFilesDir(subFolder);
if (!dir.exists()) {
return false;
}
File file = new File(dir, fileName);
fileOuputStream = new FileOutputStream(file);
fileOuputStream.write(bFile);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (fileOuputStream != null) {
try {
fileOuputStream.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
return true;
}
public static void writeBufferToFile(AMMethod amMethod, byte[] requestBuffer) {
String bufferFilename = REQ_BUFFER_FILENAME.get(amMethod);
if (requestBuffer != null) {
if (writeBufferToFile(SUBFOLDER_NAME, bufferFilename, requestBuffer)) {
Log.i(AMTAG, "File written: " + bufferFilename);
}
}
}
public static byte[] readBufferFromFile(AMMethod amMethod) {
byte[] requestBuffer = new byte[0];
String bufferFilename = RESP_BUFFER_FILENAME.get(amMethod);
byte[] tmpSerializedInputData = readBufferFromFile(SUBFOLDER_NAME, bufferFilename);
if (tmpSerializedInputData != null) {
requestBuffer = tmpSerializedInputData;
Log.i(AMTAG, "File read: " + bufferFilename);
}
return requestBuffer;
}
}
| true |
56b041d566f7c35f46896d37854c18af34646f12
|
Java
|
sergiosson/test
|
/src/com/gos/veleta/WeatherAsynctask.java
|
UTF-8
| 4,576 | 2.25 | 2 |
[] |
no_license
|
package com.gos.veleta;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
public class WeatherAsynctask extends AsyncTask<String, Void, WindInfo> {
// private static final String HTTP_ICANHAZIP_COM = "http://icanhazip.com/";
private static final String TAG_WINDSPEED_KMPH = "/data/current_condition/windspeedKmph";
private static final String TAG_WINDSPEED_MILES = "/data/current_condition/windspeedMiles";
private static final String TAG_WINDDIR_DEGREE = "/data/current_condition/winddirDegree";
private static final String TAG_AREA_NAME = "/data/nearest_area/areaName";
private static final String TAG_COUNTRY = "/data/nearest_area/country";
private static final String TAG_REGION = "/data/nearest_area/region";
private static final String TAG_PROVIDER = "/data/provider";
private static final String TAG_ERROR = "/veleta/error/message";
Context ctx;
public WeatherAsynctask(Context ctx) {
this.ctx = ctx;
}
/**
* The system calls this to perform work in a worker thread and delivers it
* the parameters given to AsyncTask.execute()
*/
protected WindInfo doInBackground(String... urls) {
WindInfo windInfo = new WindInfo();
try {
checkInetConnection();
// String ip = getIp();
String weatherHttpUrl = urls[0]; // + ip;
String xml = doCallWeatehrApi(weatherHttpUrl);
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
Document document = null;
try {
db = dbf.newDocumentBuilder();
document = db.parse(new ByteArrayInputStream(xml.getBytes()));
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new ErrorInfo(R.string.ERR_CANT_GET_HTTP_INFO);
}
String error = getFirstTag(TAG_ERROR, document, xPath);
if (error != null && error.length() > 0) {
throw new ErrorInfo(error);
}
String winddirDegree = getFirstTag(TAG_WINDDIR_DEGREE, document,
xPath);
String windSpeedKm = getFirstTag(TAG_WINDSPEED_KMPH, document,
xPath);
String provider = getFirstTag(TAG_PROVIDER, document, xPath);
windInfo.setProvider(provider);
String windSpeedMiles = getFirstTag(TAG_WINDSPEED_MILES, document,
xPath);
String areaName = getFirstTag(TAG_AREA_NAME, document, xPath);
windInfo.setAreaName(areaName);
String country = getFirstTag(TAG_COUNTRY, document, xPath);
windInfo.setCountry(country);
String region = getFirstTag(TAG_REGION, document, xPath);
windInfo.setRegion(region);
int degrees = getNumber(winddirDegree);
if (degrees < 0) {
throw new ErrorInfo(R.string.ERR_CANT_GET_HTTP_INFO);
}
windInfo.setDegrees(degrees);
int speedKm = getNumber(windSpeedKm);
windInfo.setSpeedKm(speedKm);
int speedMiles = getNumber(windSpeedMiles);
windInfo.setSpeedMiles(speedMiles);
} catch (ErrorInfo e) {
windInfo.setError(e);
}
return windInfo;
}
private void checkInetConnection() throws ErrorInfo {
ConnectivityManager connectivityManager = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
throw new ErrorInfo(R.string.ERR_NO_INET);
}
}
private int getNumber(String str) {
if (str == null || str.trim().length() == 0) {
return -1;
} else {
return Integer.parseInt(str);
}
}
private String getFirstTag(String xpathExpr, Document document, XPath xPath) {
String result;
try {
return xPath.evaluate(xpathExpr, document);
} catch (XPathExpressionException e) {
result = null;
}
return result;
}
private String doCallWeatehrApi(String urlStr) throws ErrorInfo {
RestClient rc = new RestClient(urlStr);
rc.executeRequest();
return rc.getResponse();
}
// public static String getIp() throws ErrorInfo {
//
// RestClient rc = new RestClient(HTTP_ICANHAZIP_COM);
// rc.executeRequest();
// return rc.getResponse().replace("\n", "");
// }
}
| true |
ecfa2528ec9000daaf04bddd3c8e04b6a33ff25a
|
Java
|
little-whale/easy-manage
|
/easy-manage-modules/src/main/java/com/github/littlewhale/easymanage/modules/config/mvc/GlobalErrorController.java
|
UTF-8
| 3,194 | 2.09375 | 2 |
[
"MIT"
] |
permissive
|
package com.github.littlewhale.easymanage.modules.config.mvc;
import com.github.littlewhale.easymanage.modules.commom.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 参考:BasicErrorController
* 4xx,5xx 错误处理逻辑,默认的处理逻辑
* <p>
* ErrorMvcAutoConfiguration
* </p>
*
* @author cjp
* @date 2019/1/8
*/
@Slf4j
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class GlobalErrorController extends AbstractErrorController {
private final ErrorProperties errorProperties;
/**
* 构造方法初始化ErrorProperties,参考:ErrorMvcAutoConfiguration的构造方法实现
*
* @param errorAttributes
* @param serverProperties
*/
public GlobalErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
super(errorAttributes);
Assert.notNull(serverProperties, "ServerProperties must not be null");
this.errorProperties = serverProperties.getError();
}
@Override
public String getErrorPath() {
return errorProperties.getPath();
}
@RequestMapping
@ResponseBody
public Result error(HttpServletRequest request) {
HttpStatus status = getStatus(request);
Map<String, Object> errorMap = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
errorLog(errorMap);
return Result.instance(status.value(), status.getReasonPhrase(), errorMap);
}
/**
* 输出错误请求日志
*
* @param errorMap
*/
private void errorLog(Map<String, Object> errorMap) {
log.error("error request====>url:{},status:{},errorMsg:{},time:{}",
errorMap.get("path"), errorMap.get("status"), errorMap.get("message"), errorMap.get("timestamp"));
}
/**
* Determine if the stacktrace attribute should be included.
*
* @param request the source request
* @param produces the media type produced (or {@code MediaType.ALL})
* @return if the stacktrace attribute should be included
*/
protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
ErrorProperties.IncludeStacktrace include = errorProperties.getIncludeStacktrace();
if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
return true;
}
if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
return getTraceParameter(request);
}
return false;
}
}
| true |
bb8a3141ff1d082410dd5329996d67b43260b3ae
|
Java
|
androidx/androidx
|
/emoji2/emoji2-bundled/src/androidTest/java/androidx/emoji2/bundled/util/EmojiMatcher.java
|
UTF-8
| 9,252 | 2.0625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.emoji2.bundled.util;
import static org.mockito.ArgumentMatchers.argThat;
import android.text.Spanned;
import android.text.TextUtils;
import androidx.annotation.RequiresApi;
import androidx.emoji2.text.EmojiSpan;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.mockito.ArgumentMatcher;
/**
* Utility class that includes matchers specific to emojis and EmojiSpans.
*/
@RequiresApi(19)
public class EmojiMatcher {
public static Matcher<CharSequence> hasEmojiAt(final int id, final int start,
final int end) {
return new EmojiResourceMatcher(id, start, end);
}
public static Matcher<CharSequence> hasEmojiAt(final Emoji.EmojiMapping emojiMapping,
final int start, final int end) {
return new EmojiResourceMatcher(emojiMapping.id(), start, end);
}
public static Matcher<CharSequence> hasEmojiAt(final int start, final int end) {
return new EmojiResourceMatcher(-1, start, end);
}
public static Matcher<CharSequence> hasEmoji(final int id) {
return new EmojiResourceMatcher(id, -1, -1);
}
public static Matcher<CharSequence> hasEmoji(final Emoji.EmojiMapping emojiMapping) {
return new EmojiResourceMatcher(emojiMapping.id(), -1, -1);
}
public static Matcher<CharSequence> hasEmoji() {
return new EmojiSpanMatcher();
}
public static Matcher<CharSequence> hasEmojiCount(final int count) {
return new EmojiCountMatcher(count);
}
public static <T extends CharSequence> T sameCharSequence(final T expected) {
return argThat(new ArgumentMatcher<T>() {
@Override
public boolean matches(T o) {
if (o instanceof CharSequence) {
return TextUtils.equals(expected, o);
}
return false;
}
@Override
public String toString() {
return "doesn't match " + expected;
}
});
}
private static class EmojiSpanMatcher extends TypeSafeMatcher<CharSequence> {
private EmojiSpan[] mSpans;
EmojiSpanMatcher() {
}
@Override
public void describeTo(Description description) {
description.appendText("should have EmojiSpans");
}
@Override
protected void describeMismatchSafely(final CharSequence charSequence,
Description mismatchDescription) {
mismatchDescription.appendText(" has no EmojiSpans");
}
@Override
protected boolean matchesSafely(final CharSequence charSequence) {
if (charSequence == null) return false;
if (!(charSequence instanceof Spanned)) return false;
mSpans = ((Spanned) charSequence).getSpans(0, charSequence.length(), EmojiSpan.class);
return mSpans.length != 0;
}
}
private static class EmojiCountMatcher extends TypeSafeMatcher<CharSequence> {
private final int mCount;
private EmojiSpan[] mSpans;
EmojiCountMatcher(final int count) {
mCount = count;
}
@Override
public void describeTo(Description description) {
description.appendText("should have ").appendValue(mCount).appendText(" EmojiSpans");
}
@Override
protected void describeMismatchSafely(final CharSequence charSequence,
Description mismatchDescription) {
mismatchDescription.appendText(" has ");
if (mSpans == null) {
mismatchDescription.appendValue("no");
} else {
mismatchDescription.appendValue(mSpans.length);
}
mismatchDescription.appendText(" EmojiSpans");
}
@Override
protected boolean matchesSafely(final CharSequence charSequence) {
if (charSequence == null) return false;
if (!(charSequence instanceof Spanned)) return false;
mSpans = ((Spanned) charSequence).getSpans(0, charSequence.length(), EmojiSpan.class);
return mSpans.length == mCount;
}
}
private static class EmojiResourceMatcher extends TypeSafeMatcher<CharSequence> {
private static final int ERR_NONE = 0;
private static final int ERR_SPANNABLE_NULL = 1;
private static final int ERR_NO_SPANS = 2;
private static final int ERR_WRONG_INDEX = 3;
private final int mResId;
private final int mStart;
private final int mEnd;
private int mError = ERR_NONE;
private int mActualStart = -1;
private int mActualEnd = -1;
EmojiResourceMatcher(int resId, int start, int end) {
mResId = resId;
mStart = start;
mEnd = end;
}
@Override
public void describeTo(final Description description) {
if (mResId == -1) {
description.appendText("should have EmojiSpan at ")
.appendValue("[" + mStart + "," + mEnd + "]");
} else if (mStart == -1 && mEnd == -1) {
description.appendText("should have EmojiSpan with resource id ")
.appendValue(Integer.toHexString(mResId));
} else {
description.appendText("should have EmojiSpan with resource id ")
.appendValue(Integer.toHexString(mResId))
.appendText(" at ")
.appendValue("[" + mStart + "," + mEnd + "]");
}
}
@Override
protected void describeMismatchSafely(final CharSequence charSequence,
Description mismatchDescription) {
int offset = 0;
mismatchDescription.appendText("[");
while (offset < charSequence.length()) {
int codepoint = Character.codePointAt(charSequence, offset);
mismatchDescription.appendText(Integer.toHexString(codepoint));
offset += Character.charCount(codepoint);
if (offset < charSequence.length()) {
mismatchDescription.appendText(",");
}
}
mismatchDescription.appendText("]");
switch (mError) {
case ERR_NO_SPANS:
mismatchDescription.appendText(" had no spans");
break;
case ERR_SPANNABLE_NULL:
mismatchDescription.appendText(" was null");
break;
case ERR_WRONG_INDEX:
mismatchDescription.appendText(" had Emoji at ")
.appendValue("[" + mActualStart + "," + mActualEnd + "]");
break;
default:
mismatchDescription.appendText(" does not have an EmojiSpan with given "
+ "resource id ");
}
}
@Override
protected boolean matchesSafely(final CharSequence charSequence) {
if (charSequence == null) {
mError = ERR_SPANNABLE_NULL;
return false;
}
if (!(charSequence instanceof Spanned)) {
mError = ERR_NO_SPANS;
return false;
}
Spanned spanned = (Spanned) charSequence;
final EmojiSpan[] spans = spanned.getSpans(0, charSequence.length(), EmojiSpan.class);
if (spans.length == 0) {
mError = ERR_NO_SPANS;
return false;
}
if (mStart == -1 && mEnd == -1) {
for (int index = 0; index < spans.length; index++) {
if (mResId == spans[index].getId()) {
return true;
}
}
return false;
} else {
for (int index = 0; index < spans.length; index++) {
if (mResId == -1 || mResId == spans[index].getId()) {
mActualStart = spanned.getSpanStart(spans[index]);
mActualEnd = spanned.getSpanEnd(spans[index]);
if (mActualStart == mStart && mActualEnd == mEnd) {
return true;
}
}
}
if (mActualStart != -1 && mActualEnd != -1) {
mError = ERR_WRONG_INDEX;
}
return false;
}
}
}
}
| true |
a9174a143baf7395560915f1367d7b5914e3129e
|
Java
|
OowuzhioO/Banking_System_2.0
|
/src/main/java/com/hwj/banking/Entity/Loan.java
|
UTF-8
| 1,932 | 2.3125 | 2 |
[] |
no_license
|
package com.hwj.banking.Entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "LOAN")
@SequenceGenerator(name = "loan_SG", allocationSize = 1, initialValue = 1, sequenceName = "loan_sg")
public class Loan {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "loan_SG")
@Column(name = "lid")
private int id;
@Column(name = "lBlance")
private long balance;
@Column(name = "lRemark")
private String remark;
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
@JoinTable(name = "Loan_Customer", joinColumns = {@JoinColumn(name = "lid")}, inverseJoinColumns = {@JoinColumn(name = "cid")})
@JsonIgnore
private List<Customer> customer_loan = new ArrayList<>();
public Loan() {
}
public Loan(long balance, String remark, List<Customer> customer_loan) {
this.balance = balance;
this.remark = remark;
this.customer_loan = customer_loan;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getBalance() {
return balance;
}
public void setBalance(long balance) {
this.balance = balance;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public List<Customer> getCustomer_loan() {
return customer_loan;
}
public void setCustomer_loan(List<Customer> customer_loan) {
this.customer_loan = customer_loan;
}
@Override
public String toString() {
return "Loan{" +
"id=" + id +
", balance=" + balance +
", remark='" + remark + '\'' +
", customer_loan=" + customer_loan +
'}';
}
}
| true |
1cab016193dcc180d315efdb983deb1cacf65d5b
|
Java
|
mim3009/lessons
|
/уроки/java/Java/lab4/src/lab4/Facult.java
|
UTF-8
| 619 | 2.75 | 3 |
[] |
no_license
|
package lab4;
public class Facult {
private String Name;
private int KolGroup;
private int KolPrep;
public String getName(){
return Name;
}
public void setName(String name){
Name = name;
}
public int getKolGroup() {
return KolGroup;
}
public void setKolGroup(int kolgroup) {
KolGroup = kolgroup;
}
public int getKolPrep() {
return KolPrep;
}
public void setCntHouse(int kolprep) {
KolPrep = kolprep;
}
public Facult(String name, int kolgroup, int kolprep) {
super();
Name = name;
KolGroup = kolgroup;
KolPrep = kolprep;
}
}
| true |
39ff83133f5fb4ff42bf2598350c21f2d77373b1
|
Java
|
wangjun/PolymerizedDcit
|
/src/com/polymerized/pagefilter/FilterDictall.java
|
UTF-8
| 3,434 | 2.515625 | 3 |
[] |
no_license
|
package com.polymerized.pagefilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.polymerized.bean.DictFilter;
import com.polymerized.bean.MetaMeaning;
/**
* 分析www.dictall.com的网页内容,过滤信息之后存储到词典义对象中
*
* @author edgar
*
*/
public class FilterDictall implements DictFilter {
public final String reqUrl = "http://dictall.com/dictall/result.jsp?cd=UTF-8&keyword=";
@SuppressWarnings("deprecation")
public List<MetaMeaning> getMeansBykeyword(String keyword) {
keyword = java.net.URLEncoder.encode(keyword);
Document doc = null;
try {
doc = Jsoup.connect(reqUrl + keyword).get();
} catch (IOException e) {
System.out.println("访问地址失败");
e.printStackTrace();
}
return getMeanFromJsoupDoc(doc);
}
/**
* 通过一个Jsoup对象返回MetaMeaning对象列表
*
* @param doc
*/
private List<MetaMeaning> getMeanFromJsoupDoc(Document doc) {
List<MetaMeaning> relList = new ArrayList<MetaMeaning>();
MetaMeaning meaning = null;
Elements elems = doc.getElementById("catelist").children();
ListIterator<Element> ite = elems.listIterator();
while (ite.hasNext()) {
Element element = ite.next();
meaning = new MetaMeaning();
Element en = element.select("div.en").first();
// 英文键
String keyString = en.child(0).html();
keyString = keyString.substring(keyString.lastIndexOf("p;") + 2,
keyString.length());
// System.out.println(keyString);
meaning.setKey(keyString);
// 音标
String phnString = en.select("span.pho").html();
phnString = phnString.replace(" ", " ");
// System.out.println(phnString);
meaning.setPhnmic(phnString);
// 中文简要翻译
Element cn = element.select("div.cn").first();
// System.out.println(cn.html());
List<String> baseExp = new ArrayList<String>();
baseExp.add(cn.html());
meaning.setBaseExplain(baseExp);
// 例句
Elements en_sen = element.select("div.en_sen");
Elements cn_sen = element.select("div.cn_sen");
int size = en_sen.size();
Map<String, String> expMap = new HashMap<String, String>();
for (int i = 0; i < size; i++) {
String enString = en_sen.get(i).html();
int endtagIndex = enString.indexOf("<s");
if (endtagIndex != -1)
enString = enString.substring(0, enString.indexOf("<s"));
enString = enString.replace("\n", "");
enString = enString.replace("<font color=\"#FF0000\">", "{");
enString = enString.replace("</font>", "}");
enString = enString.trim();
// System.out.println("--" + i + "---" + enString);
String cnString = cn_sen.get(i).html();
cnString = cnString.replace("<font color=\"#FF0000\">", "{");
cnString = cnString.replace("</font>", "}");
cnString = cnString.replace("\n", "");
cnString = cnString.trim();
// System.out.println("--" + i + "---" + cnString);
expMap.put(enString, cnString);
}
meaning.setExample(expMap);
// 扩展内容
Element expUrl = element.select("div.more_st").first();
if (expUrl != null) {
meaning.setExtension("host"
+ expUrl.select("a").first().attr("href"));
}
relList.add(meaning);
}
return relList;
}
}
| true |
756737ba57ace233407d1ebf13d08e4e32f880f8
|
Java
|
PleoSoft/flowable-feign-client
|
/src/main/java/com/pleosoft/feign/flowable/decision/DecisionDeploymentApi.java
|
UTF-8
| 7,745 | 1.9375 | 2 |
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2019 Pleo Soft d.o.o. (pleosoft.com)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pleosoft.feign.flowable.decision;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import com.pleosoft.feign.flowable.decision.model.DataResponseDmnDeploymentResponse;
import com.pleosoft.feign.flowable.decision.model.DmnDeploymentResponse;
public interface DecisionDeploymentApi {
/**
* Delete a decision table deployment
*
* <p>
* </p>
*
*
* @param deploymentId
* ("",required=true)
* @return value = { <br/>
* code = 204, message = "Indicates the deployment was found and has
* been deleted. Response-body is intentionally empty."),<br/>
* code = 404, message = "Indicates the requested deployment was not
* found.")<br/>
* }
*
*/
@RequestMapping(value = "/dmn-repository/deployments/{deploymentId}", produces = "application/json", method = RequestMethod.DELETE)
ResponseEntity<Void> deleteDecisionTableDeployment(@PathVariable("deploymentId") String deploymentId);
/**
* Get a decision table deployment
*
* <p>
* </p>
*
*
* @param deploymentId
* ("",required=true)
* @return value = { <br/>
* code = 200, message = "Indicates the deployment was found and
* returned.", response = DmnDeploymentResponse.class),<br/>
* code = 404, message = "Indicates the requested deployment was not
* found.")<br/>
* }
*
*/
@RequestMapping(value = "/dmn-repository/deployments/{deploymentId}", produces = "application/json", method = RequestMethod.GET)
ResponseEntity<DmnDeploymentResponse> getDecisionTableDeployment(@PathVariable("deploymentId") String deploymentId);
/**
* Get a decision table deployment resource content
*
* <p>
* The response body will contain the binary resource-content for the
* requested resource. The response content-type will be the same as the
* type returned in the resources mimeType property. Also, a
* content-disposition header is set, allowing browsers to download the file
* instead of displaying it.
* </p>
*
*
* @param deploymentId
* ("",required=true)
* @param resourceName
* ("",required=true)
* @return value = { <br/>
* code = 200, message = "Indicates both deployment and resource
* have been found and the resource data has been returned.",
* response = byte[].class, responseContainer = "List"),<br/>
* code = 404, message = "Indicates the requested deployment was not
* found or there is no resource with the given id present in the
* deployment. The status-description contains additional
* information.")<br/>
* }
*
*/
@RequestMapping(value = "/dmn-repository/deployments/{deploymentId}/resourcedata/{resourceName}", method = RequestMethod.GET)
ResponseEntity<List<byte[]>> getDecisionTableDeploymentResource(@PathVariable("deploymentId") String deploymentId,
@PathVariable("resourceName") String resourceName);
/**
* List of decision table deployments
*
* <p>
* </p>
*
*
* @param name
* ("Only return decision table deployments with the given
* name.")
* @param nameLike
* ("Only return decision table deployments with a name like the
* given name.")
* @param category
* ("Only return decision table deployments with the given
* category.")
* @param categoryNotEquals
* ("Only return decision table deployments which don?t have the
* given category.")
* @param tenantId
* ("Only return decision table deployments with the given
* tenantId.")
* @param tenantIdLike
* ("Only return decision table deployments with a tenantId like
* the given value.")
* @param withoutTenantId
* ("If true, only returns decision table deployments without a
* tenantId set. If false, the withoutTenantId parameter is
* ignored.")
* @param sort
* ("Property to sort on, to be used together with the order.",
* allowableValues = "id, name, deployTime, tenantId")
* @return value = { <br/>
* code = 200, message = "Indicates the request was successful.",
* response = DataResponseDmnDeploymentResponse.class)<br/>
* }
*
*/
@RequestMapping(value = "/dmn-repository/deployments", produces = "application/json", method = RequestMethod.GET)
ResponseEntity<DataResponseDmnDeploymentResponse> listDecisionTableDeployments(
@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "nameLike", required = false) String nameLike,
@RequestParam(value = "category", required = false) String category,
@RequestParam(value = "categoryNotEquals", required = false) String categoryNotEquals,
@RequestParam(value = "tenantId", required = false) String tenantId,
@RequestParam(value = "tenantIdLike", required = false) String tenantIdLike,
@RequestParam(value = "withoutTenantId", required = false) Boolean withoutTenantId,
@RequestParam(value = "sort", required = false) String sort);
/**
* Create a new decision table deployment
*
* <p>
* The request body should contain data of type multipart/form-data. There
* should be exactly one file in the request, any additional files will be
* ignored. The deployment name is the name of the file-field passed in. If
* multiple resources need to be deployed in a single deployment, compress
* the resources in a zip and make sure the file-name ends with .bar or
* .zip. An additional parameter (form-field) can be passed in the request
* body with name tenantId. The value of this field will be used as the id
* of the tenant this deployment is done in.
* </p>
*
*
* @param tenantId
* ("")
* @param file
* (value = "")
* @return value = { <br/>
* code = 200, message = "successful operation", response =
* DmnDeploymentResponse.class),<br/>
* code = 201, message = "Indicates the deployment was
* created."),<br/>
* code = 400, message = "Indicates there was no content present in
* the request body or the content mime-type is not supported for
* deployment. The status-description contains additional
* information.")<br/>
* }
*
*/
@RequestMapping(value = "/dmn-repository/deployments", produces = "application/json", consumes = "multipart/form-data", method = RequestMethod.POST)
ResponseEntity<DmnDeploymentResponse> uploadDecisionTableDeployment(
@RequestParam(value = "tenantId", required = false) String tenantId,
@RequestPart("file") MultipartFile file);
}
| true |
181d5313fb6fbe0886c15e474e9e3932bbd34d38
|
Java
|
r-friedman/openmrs-module-integration
|
/api/src/test/java/org/openmrs/module/integration/api/DhisMetadataUtilsTest.java
|
UTF-8
| 3,119 | 1.851563 | 2 |
[] |
no_license
|
package org.openmrs.module.integration.api;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import org.hibernate.metadata.ClassMetadata;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openmrs.api.context.Context;
import org.openmrs.module.integration.IntegrationServer;
import org.openmrs.module.integration.UndefinedCohortDefinition;
import org.openmrs.module.integration.api.DhisService;
import org.openmrs.module.integration.api.db.DhisDAO;
import org.openmrs.module.integration.api.db.DhisMetadataUtils;
import org.openmrs.module.integration.api.db.IntegrationException;
import org.openmrs.module.integration.api.db.ServerMetadata;
import org.openmrs.module.reporting.cohort.definition.AllPatientsCohortDefinition;
import org.openmrs.module.reporting.cohort.definition.CohortDefinition;
import org.openmrs.module.reporting.cohort.definition.service.CohortDefinitionService;
import org.openmrs.test.BaseModuleContextSensitiveTest;
import org.springframework.test.annotation.Rollback;
public class DhisMetadataUtilsTest extends BaseModuleContextSensitiveTest {
IntegrationServer is;
DhisService ds;
// @Override
// public Boolean useInMemoryDatabase() {
// return false;
// }
@Before
public void setup() {
is = new IntegrationServer();
is.setServerName("dhis");
is.setServerDescription("DHIS demo server");
is.setUrl("http://apps.dhis2.org/demo");
is.setUserName("admin");
is.setPassword("district");
ds=Context.getService(DhisService.class);
try {
super.authenticate();
} catch (Exception e) {
}
}
@Test
public void DhisMetadataUtils_shouldGetStatusOfDemoServer() {
String s = DhisMetadataUtils.testConnection(is);
Assert.assertNull(s);
}
@Test
public void createNewServer_shouldWorkForResources(){
String s="";
ServerMetadata sm = new ServerMetadata();
try {
DhisMetadataUtils.getServerMetadata("MasterTemplate.xml", "cats.xml", "opts.xml");
sm.buildDBObjects("MasterTemplate");
} catch (Exception e) {
s=e.getMessage();
}
Integer nde=sm.getDataElements().size();
Integer ndis=sm.getDisaggregations().size();
Integer nrt=sm.getReportTemplates().size();
Integer ncat=sm.getCats().size();
Integer nopt=sm.getOpts().size();
Assert.assertNotNull("Master is null", sm.getMaster() );
Assert.assertNotNull("Categories is null", sm.getCats());
Assert.assertNotNull("Options is null", sm.getOpts());
Assert.assertTrue("DataElements is empty", nde!=0);
Assert.assertTrue("Disaggregations is empty", ndis!=0);
Assert.assertTrue("ReportTemplates is empty", nrt!=0);
Assert.assertTrue("Categories is empty", ncat!=0);
Assert.assertTrue("Options is empty", nopt!=0);
Assert.assertEquals("Exception returned","",s);
}
@Rollback(false)
@Test
public void createNewServer_shouldWorkForAPI(){
String s="";
try {
DhisMetadataUtils.getServerMetadata(is);
ServerMetadata sm = new ServerMetadata();
sm.buildDBObjects(is.getServerName());
} catch (Exception e) {
s=e.getMessage();
}
Assert.assertEquals("Exception returned","",s);
}
}
| true |
c0da58929e9d9a78c54b2a1cb914560d5299bf2f
|
Java
|
souless94/main
|
/src/test/java/seedu/address/logic/commands/AddGroupCommandTest.java
|
UTF-8
| 7,138 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
package seedu.address.logic.commands;
import static java.util.Objects.requireNonNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Predicate;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import javafx.collections.ObservableList;
import seedu.address.logic.CommandHistory;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.AddressBook;
import seedu.address.model.Entity;
import seedu.address.model.Model;
import seedu.address.model.ReadOnlyAddressBook;
import seedu.address.model.group.Group;
import seedu.address.model.person.Person;
import seedu.address.testutil.GroupBuilder;
public class AddGroupCommandTest {
private static final CommandHistory EMPTY_COMMAND_HISTORY = new CommandHistory();
@Rule
public ExpectedException thrown = ExpectedException.none();
private CommandHistory commandHistory = new CommandHistory();
@Test
public void constructor_nullGroup_throwsNullPointerException() {
thrown.expect(NullPointerException.class);
new AddGroupCommand(null);
}
@Test
public void execute_groupAcceptedByModel_addSuccessful() throws Exception {
ModelStubAcceptingGroupAdded modelStub = new ModelStubAcceptingGroupAdded();
Group validGroup = new GroupBuilder().build();
CommandResult commandResult = new AddGroupCommand(validGroup)
.execute(modelStub, commandHistory);
assertEquals(String.format(AddGroupCommand.MESSAGE_SUCCESS, validGroup),
commandResult.feedbackToUser);
assertEquals(Arrays.asList(validGroup), modelStub.groupsAdded);
assertEquals(EMPTY_COMMAND_HISTORY, commandHistory);
}
@Test
public void execute_duplicateGroup_throwsCommandException() throws Exception {
Group validGroup = new GroupBuilder().build();
AddGroupCommand addGroupCommand = new AddGroupCommand(validGroup);
ModelStub modelStub = new ModelStubWithGroup(validGroup);
thrown.expect(CommandException.class);
thrown.expectMessage(AddGroupCommand.MESSAGE_DUPLICATE_GROUP);
addGroupCommand.execute(modelStub, commandHistory);
}
@Test
public void equals() {
Group family = new GroupBuilder().withName("Family").build();
Group friends = new GroupBuilder().withName("Friends").build();
AddGroupCommand addFamilyCommand = new AddGroupCommand(family);
AddGroupCommand addFriendsCommand = new AddGroupCommand(friends);
// same object -> returns true
assertTrue(addFamilyCommand.equals(addFamilyCommand));
// same values -> returns true
AddGroupCommand addFamilyCommandCopy = new AddGroupCommand(family);
assertTrue(addFamilyCommand.equals(addFamilyCommandCopy));
// different types -> returns false
assertFalse(addFamilyCommand.equals(1));
// null -> returns false
assertFalse(addFamilyCommand.equals(null));
// different person -> returns false
assertFalse(addFamilyCommand.equals(addFriendsCommand));
}
/**
* A default model stub that have all of the methods failing.
*/
private class ModelStub implements Model {
@Override
public void add(Entity key) {
throw new AssertionError("This method should not be called.");
}
@Override
public void delete(Entity key) {
throw new AssertionError("This method should not be called.");
}
@Override
public boolean has(Entity key) {
throw new AssertionError("This method should not be called.");
}
@Override
public void update(Entity target, Entity edited) {
throw new AssertionError("This method should not be called.");
}
@Override
public void resetData(ReadOnlyAddressBook newData) {
throw new AssertionError("This method should not be called.");
}
@Override
public ReadOnlyAddressBook getAddressBook() {
throw new AssertionError("This method should not be called.");
}
@Override
public ObservableList<Person> getFilteredPersonList() {
throw new AssertionError("This method should not be called.");
}
@Override
public void updateFilteredPersonList(Predicate<Person> predicate) {
throw new AssertionError("This method should not be called.");
}
@Override
public ObservableList<Group> getFilteredGroupList() {
throw new AssertionError("This method should not be called.");
}
@Override
public void updateFilteredGroupList(Predicate<Group> predicate) {}
@Override
public boolean canUndoAddressBook() {
throw new AssertionError("This method should not be called.");
}
@Override
public boolean canRedoAddressBook() {
throw new AssertionError("This method should not be called.");
}
@Override
public void undoAddressBook() {
throw new AssertionError("This method should not be called.");
}
@Override
public void redoAddressBook() {
throw new AssertionError("This method should not be called.");
}
@Override
public void commitAddressBook() {
throw new AssertionError("This method should not be called.");
}
}
/**
* A Model stub that contains a single group.
*/
private class ModelStubWithGroup extends ModelStub {
private final Group group;
ModelStubWithGroup(Group group) {
requireNonNull(group);
this.group = group;
}
@Override
public boolean has(Entity target) {
requireNonNull(target);
if (target instanceof Group) {
return this.group.isSame(target);
}
return false;
}
}
/**
* A Model stub that always accept the group being added.
*/
private class ModelStubAcceptingGroupAdded extends ModelStub {
final ArrayList<Group> groupsAdded = new ArrayList<>();
@Override
public boolean has(Entity target) {
requireNonNull(target);
if (target instanceof Group) {
return groupsAdded.stream().anyMatch(target::isSame);
}
return false;
}
@Override
public void add(Entity target) {
requireNonNull(target);
if (target instanceof Group) {
groupsAdded.add((Group) target);
}
}
@Override
public void commitAddressBook() {
// called by {@code AddGroupCommand#execute()}
}
@Override
public ReadOnlyAddressBook getAddressBook() {
return new AddressBook();
}
}
}
| true |
3bff14316f027afa096c91b3fa9ad54c7075a72a
|
Java
|
C1220G2-Org/C1220G2-Repo-BE
|
/spring_boot/src/main/java/com/codegym/spring_boot_sprint_1/model/dto/UserDto.java
|
UTF-8
| 2,338 | 2.484375 | 2 |
[] |
no_license
|
package com.codegym.spring_boot_sprint_1.model.dto;
public class UserDto {
private Long id;
private String username;
private String password;
private Long department;
private Integer roles;
private String name;
private String email;
private String avatar;
public UserDto() {
}
public UserDto(String username, String password, Long department, Integer roles, String name, String email, String avatar) {
this.username = username;
this.password = password;
this.department = department;
this.roles = roles;
this.name = name;
this.email = email;
this.avatar = avatar;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getDepartment() {
return department;
}
public void setDepartment(Long department) {
this.department = department;
}
public Integer getRoles() {
return roles;
}
public void setRole(Integer roles) {
this.roles = roles;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setRoles(Integer roles) {
this.roles = roles;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
@Override
public String toString() {
return "UserDto{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", department=" + department +
", roles=" + roles +
", name='" + name + '\'' +
", email='" + email + '\'' +
", avatar='" + avatar + '\'' +
'}';
}
}
| true |
a3b39d2a1ec719e399b64e7d3ef3cf76a467bd78
|
Java
|
congzhizhi/monitor26
|
/netty/src/main/java/com/luban/netty/threedome/TestServer.java
|
UTF-8
| 1,849 | 2.40625 | 2 |
[] |
no_license
|
package com.luban.netty.threedome;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import sun.misc.Signal;
import sun.misc.SignalHandler;
public class TestServer {
public static void main(String[] args) {
EventLoopGroup bossGroup=new NioEventLoopGroup();
EventLoopGroup workGroup=new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap=new ServerBootstrap();
serverBootstrap.group(bossGroup,workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.ALLOCATOR,PooledByteBufAllocator.DEFAULT)
.childOption(ChannelOption.ALLOCATOR,PooledByteBufAllocator.DEFAULT)
.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 4096, 65536))//设置缓冲区大小
.handler(new LoggingHandler(LogLevel.DEBUG))
.childHandler(new TestServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(8989).sync();
ChannelFuture closeFuture = channelFuture.channel().closeFuture().sync();
}catch (Exception e){
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
private static String getOSSignalType() {
return "SIG"+ (System.getProperties().getProperty("os.name").toLowerCase().startsWith("win")?"USER1":"TERM");
}
}
| true |
1edac27b7f27df083d7c93d98f0b9e7fe8509a07
|
Java
|
lielran/Java8
|
/src/interfaces/interfaceUnlocking.java
|
UTF-8
| 721 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
package interfaces;
/**
* Created by lielran on 8/15/16.
*/
/**
* output:
* Init
* Default
*/
public class interfaceUnlocking {
public static void main(String[] args) {
Component myComponent = new Component() {
@Override
public String find(String name) {
return name;
}
};
myComponent.init();
System.out.println(myComponent.find(myComponent.getName()));
}
}
interface Component {
public String find(String name);
//default Function
default public String getName(){
return "Default";
}
//default interface
default public void init() {
System.out.println("Init");
}
}
| true |
1a1bbc86feadd1cc4aa5ba9fc0662785ed8c8398
|
Java
|
javaliao/mall
|
/portal/bean/src/main/java/model/TbUserAddressExample.java
|
UTF-8
| 23,997 | 2.09375 | 2 |
[] |
no_license
|
package model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TbUserAddressExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public TbUserAddressExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("Id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("Id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Long value) {
addCriterion("Id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("Id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("Id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("Id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("Id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("Id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Long> values) {
addCriterion("Id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Long> values) {
addCriterion("Id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("Id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("Id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andProvinceIdIsNull() {
addCriterion("province_id is null");
return (Criteria) this;
}
public Criteria andProvinceIdIsNotNull() {
addCriterion("province_id is not null");
return (Criteria) this;
}
public Criteria andProvinceIdEqualTo(Long value) {
addCriterion("province_id =", value, "provinceId");
return (Criteria) this;
}
public Criteria andProvinceIdNotEqualTo(Long value) {
addCriterion("province_id <>", value, "provinceId");
return (Criteria) this;
}
public Criteria andProvinceIdGreaterThan(Long value) {
addCriterion("province_id >", value, "provinceId");
return (Criteria) this;
}
public Criteria andProvinceIdGreaterThanOrEqualTo(Long value) {
addCriterion("province_id >=", value, "provinceId");
return (Criteria) this;
}
public Criteria andProvinceIdLessThan(Long value) {
addCriterion("province_id <", value, "provinceId");
return (Criteria) this;
}
public Criteria andProvinceIdLessThanOrEqualTo(Long value) {
addCriterion("province_id <=", value, "provinceId");
return (Criteria) this;
}
public Criteria andProvinceIdIn(List<Long> values) {
addCriterion("province_id in", values, "provinceId");
return (Criteria) this;
}
public Criteria andProvinceIdNotIn(List<Long> values) {
addCriterion("province_id not in", values, "provinceId");
return (Criteria) this;
}
public Criteria andProvinceIdBetween(Long value1, Long value2) {
addCriterion("province_id between", value1, value2, "provinceId");
return (Criteria) this;
}
public Criteria andProvinceIdNotBetween(Long value1, Long value2) {
addCriterion("province_id not between", value1, value2, "provinceId");
return (Criteria) this;
}
public Criteria andCitiesIdIsNull() {
addCriterion("cities_id is null");
return (Criteria) this;
}
public Criteria andCitiesIdIsNotNull() {
addCriterion("cities_id is not null");
return (Criteria) this;
}
public Criteria andCitiesIdEqualTo(Long value) {
addCriterion("cities_id =", value, "citiesId");
return (Criteria) this;
}
public Criteria andCitiesIdNotEqualTo(Long value) {
addCriterion("cities_id <>", value, "citiesId");
return (Criteria) this;
}
public Criteria andCitiesIdGreaterThan(Long value) {
addCriterion("cities_id >", value, "citiesId");
return (Criteria) this;
}
public Criteria andCitiesIdGreaterThanOrEqualTo(Long value) {
addCriterion("cities_id >=", value, "citiesId");
return (Criteria) this;
}
public Criteria andCitiesIdLessThan(Long value) {
addCriterion("cities_id <", value, "citiesId");
return (Criteria) this;
}
public Criteria andCitiesIdLessThanOrEqualTo(Long value) {
addCriterion("cities_id <=", value, "citiesId");
return (Criteria) this;
}
public Criteria andCitiesIdIn(List<Long> values) {
addCriterion("cities_id in", values, "citiesId");
return (Criteria) this;
}
public Criteria andCitiesIdNotIn(List<Long> values) {
addCriterion("cities_id not in", values, "citiesId");
return (Criteria) this;
}
public Criteria andCitiesIdBetween(Long value1, Long value2) {
addCriterion("cities_id between", value1, value2, "citiesId");
return (Criteria) this;
}
public Criteria andCitiesIdNotBetween(Long value1, Long value2) {
addCriterion("cities_id not between", value1, value2, "citiesId");
return (Criteria) this;
}
public Criteria andAreaIdIsNull() {
addCriterion("area_id is null");
return (Criteria) this;
}
public Criteria andAreaIdIsNotNull() {
addCriterion("area_id is not null");
return (Criteria) this;
}
public Criteria andAreaIdEqualTo(Long value) {
addCriterion("area_id =", value, "areaId");
return (Criteria) this;
}
public Criteria andAreaIdNotEqualTo(Long value) {
addCriterion("area_id <>", value, "areaId");
return (Criteria) this;
}
public Criteria andAreaIdGreaterThan(Long value) {
addCriterion("area_id >", value, "areaId");
return (Criteria) this;
}
public Criteria andAreaIdGreaterThanOrEqualTo(Long value) {
addCriterion("area_id >=", value, "areaId");
return (Criteria) this;
}
public Criteria andAreaIdLessThan(Long value) {
addCriterion("area_id <", value, "areaId");
return (Criteria) this;
}
public Criteria andAreaIdLessThanOrEqualTo(Long value) {
addCriterion("area_id <=", value, "areaId");
return (Criteria) this;
}
public Criteria andAreaIdIn(List<Long> values) {
addCriterion("area_id in", values, "areaId");
return (Criteria) this;
}
public Criteria andAreaIdNotIn(List<Long> values) {
addCriterion("area_id not in", values, "areaId");
return (Criteria) this;
}
public Criteria andAreaIdBetween(Long value1, Long value2) {
addCriterion("area_id between", value1, value2, "areaId");
return (Criteria) this;
}
public Criteria andAreaIdNotBetween(Long value1, Long value2) {
addCriterion("area_id not between", value1, value2, "areaId");
return (Criteria) this;
}
public Criteria andDetailAddressIsNull() {
addCriterion("detail_address is null");
return (Criteria) this;
}
public Criteria andDetailAddressIsNotNull() {
addCriterion("detail_address is not null");
return (Criteria) this;
}
public Criteria andDetailAddressEqualTo(String value) {
addCriterion("detail_address =", value, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressNotEqualTo(String value) {
addCriterion("detail_address <>", value, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressGreaterThan(String value) {
addCriterion("detail_address >", value, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressGreaterThanOrEqualTo(String value) {
addCriterion("detail_address >=", value, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressLessThan(String value) {
addCriterion("detail_address <", value, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressLessThanOrEqualTo(String value) {
addCriterion("detail_address <=", value, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressLike(String value) {
addCriterion("detail_address like", value, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressNotLike(String value) {
addCriterion("detail_address not like", value, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressIn(List<String> values) {
addCriterion("detail_address in", values, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressNotIn(List<String> values) {
addCriterion("detail_address not in", values, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressBetween(String value1, String value2) {
addCriterion("detail_address between", value1, value2, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressNotBetween(String value1, String value2) {
addCriterion("detail_address not between", value1, value2, "detailAddress");
return (Criteria) this;
}
public Criteria andIsDefaultIsNull() {
addCriterion("is_default is null");
return (Criteria) this;
}
public Criteria andIsDefaultIsNotNull() {
addCriterion("is_default is not null");
return (Criteria) this;
}
public Criteria andIsDefaultEqualTo(Long value) {
addCriterion("is_default =", value, "isDefault");
return (Criteria) this;
}
public Criteria andIsDefaultNotEqualTo(Long value) {
addCriterion("is_default <>", value, "isDefault");
return (Criteria) this;
}
public Criteria andIsDefaultGreaterThan(Long value) {
addCriterion("is_default >", value, "isDefault");
return (Criteria) this;
}
public Criteria andIsDefaultGreaterThanOrEqualTo(Long value) {
addCriterion("is_default >=", value, "isDefault");
return (Criteria) this;
}
public Criteria andIsDefaultLessThan(Long value) {
addCriterion("is_default <", value, "isDefault");
return (Criteria) this;
}
public Criteria andIsDefaultLessThanOrEqualTo(Long value) {
addCriterion("is_default <=", value, "isDefault");
return (Criteria) this;
}
public Criteria andIsDefaultIn(List<Long> values) {
addCriterion("is_default in", values, "isDefault");
return (Criteria) this;
}
public Criteria andIsDefaultNotIn(List<Long> values) {
addCriterion("is_default not in", values, "isDefault");
return (Criteria) this;
}
public Criteria andIsDefaultBetween(Long value1, Long value2) {
addCriterion("is_default between", value1, value2, "isDefault");
return (Criteria) this;
}
public Criteria andIsDefaultNotBetween(Long value1, Long value2) {
addCriterion("is_default not between", value1, value2, "isDefault");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("update_time is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("update_time is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(Date value) {
addCriterion("update_time =", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(Date value) {
addCriterion("update_time <>", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(Date value) {
addCriterion("update_time >", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("update_time >=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(Date value) {
addCriterion("update_time <", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(Date value) {
addCriterion("update_time <=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<Date> values) {
addCriterion("update_time in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<Date> values) {
addCriterion("update_time not in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(Date value1, Date value2) {
addCriterion("update_time between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(Date value1, Date value2) {
addCriterion("update_time not between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andIsDeleteIsNull() {
addCriterion("is_delete is null");
return (Criteria) this;
}
public Criteria andIsDeleteIsNotNull() {
addCriterion("is_delete is not null");
return (Criteria) this;
}
public Criteria andIsDeleteEqualTo(Long value) {
addCriterion("is_delete =", value, "isDelete");
return (Criteria) this;
}
public Criteria andIsDeleteNotEqualTo(Long value) {
addCriterion("is_delete <>", value, "isDelete");
return (Criteria) this;
}
public Criteria andIsDeleteGreaterThan(Long value) {
addCriterion("is_delete >", value, "isDelete");
return (Criteria) this;
}
public Criteria andIsDeleteGreaterThanOrEqualTo(Long value) {
addCriterion("is_delete >=", value, "isDelete");
return (Criteria) this;
}
public Criteria andIsDeleteLessThan(Long value) {
addCriterion("is_delete <", value, "isDelete");
return (Criteria) this;
}
public Criteria andIsDeleteLessThanOrEqualTo(Long value) {
addCriterion("is_delete <=", value, "isDelete");
return (Criteria) this;
}
public Criteria andIsDeleteIn(List<Long> values) {
addCriterion("is_delete in", values, "isDelete");
return (Criteria) this;
}
public Criteria andIsDeleteNotIn(List<Long> values) {
addCriterion("is_delete not in", values, "isDelete");
return (Criteria) this;
}
public Criteria andIsDeleteBetween(Long value1, Long value2) {
addCriterion("is_delete between", value1, value2, "isDelete");
return (Criteria) this;
}
public Criteria andIsDeleteNotBetween(Long value1, Long value2) {
addCriterion("is_delete not between", value1, value2, "isDelete");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
| true |
7e0534239f89179aa7c6046d24e57fae7ea0814d
|
Java
|
KalidossRJ/Tamil_Fonts
|
/Tamilfonts/src/com/example/tamilfonts/MainActivity.java
|
UTF-8
| 753 | 2.5 | 2 |
[] |
no_license
|
package com.example.tamilfonts;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv=(TextView)findViewById(R.id.textView1);
String name=" காளிதாஸ் ராஜேந்திரன்";
// Converting String from Unicode for Message Titles
final String strMorning = TamilUtil.convertToTamil(TamilUtil.TSCII, name);
Typeface tfBamini = Typeface.createFromAsset(getAssets(),"fonts/Bamini.ttf");
tv.setTypeface(tfBamini);
tv.setText(strMorning);
}
}
| true |
2a8d542e7375b4a58b6109d4ee281e98cf0c917f
|
Java
|
mgrouse/HbgbWebCamp
|
/src/org/hbgb/webcamp/server/BlobStoreUploadServlet.java
|
UTF-8
| 2,922 | 2.28125 | 2 |
[] |
no_license
|
/*
* Decompiled with CFR 0_115.
*
* Could not load the following classes:
* com.google.appengine.api.blobstore.BlobKey
* com.google.appengine.api.blobstore.BlobstoreService
* com.google.appengine.api.blobstore.BlobstoreServiceFactory
* com.google.appengine.api.images.ImagesService
* com.google.appengine.api.images.ImagesServiceFactory
* com.google.appengine.api.images.ServingUrlOptions
* com.google.appengine.api.images.ServingUrlOptions$Builder
* javax.servlet.ServletException javax.servlet.http.HttpServlet
* javax.servlet.http.HttpServletRequest javax.servlet.http.HttpServletResponse
*/
package org.hbgb.webcamp.server;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ServingUrlOptions;
@SuppressWarnings("serial")
public class BlobStoreUploadServlet extends HttpServlet
{
// private static final Logger log =
// Logger.getLogger(UploadServlet.class.getName());
private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
List<BlobKey> blobKeyList = blobs.get("image");
if (blobKeyList.isEmpty())
{
// Uh ... something went really wrong here
}
else
{
ImagesService imagesService = ImagesServiceFactory.getImagesService();
ServingUrlOptions options = ServingUrlOptions.Builder.withBlobKey(blobKeyList.get(0));
// Get the image serving URL
String imageUrl = imagesService.getServingUrl(options);
// Create the UserPhoto object using the Service
UploadedPhotoServiceImpl photoServ = new UploadedPhotoServiceImpl();
UploadedPhoto photo = new UploadedPhoto();
photo.setCreated(new Date());
photo.setBlobKey(blobKeyList.get(0));
photo.setImageURL(imageUrl);
photoServ.addUploadedPhoto(photo);
res.sendRedirect("/hbgbwebcamp/upload?imageUrl=" + imageUrl);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String imageUrl = req.getParameter("imageUrl");
resp.setHeader("Content-Type", "text/html");
// This is a bit hacky, but it'll work. We'll use this key in an Async
// service to
// fetch the image and image information
resp.getWriter().println(imageUrl);
}
}
| true |
b7e55b022fcec3daea199b3c86448aa0150411ae
|
Java
|
shan7030/collect-chunk
|
/app/src/main/java/com/example/android/logindemo/SecondActivity.java
|
UTF-8
| 3,822 | 2.265625 | 2 |
[] |
no_license
|
package com.example.android.logindemo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class SecondActivity extends AppCompatActivity {
LatLng latLong;
int PLACE_PICKER_REQUEST = 1;
private FirebaseAuth firebaseAuth;
private Button logout;
TextView t;
String address;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
firebaseAuth = FirebaseAuth.getInstance();
t=(TextView)findViewById(R.id.text1);
t.setText("Please Select the address by clicking from above button!!");
}
private void Logout(){
firebaseAuth.signOut();
finish();
startActivity(new Intent(SecondActivity.this, MainActivity.class));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.logoutMenu:{
Logout();
break;
}
case R.id.profileMenu:
startActivity(new Intent(SecondActivity.this, ProfileActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
public void opendailyactivity(View view)
{
DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("Address_of_citizens/"+firebaseAuth.getUid());
databaseReference.child("Latitude/").setValue(latLong.latitude);
databaseReference.child("Longitude/").setValue(latLong.longitude);
databaseReference.child("Address/").setValue(address);
Toast.makeText(SecondActivity.this, "Address saved Succesfully!", Toast.LENGTH_SHORT).show();
Intent intenter = new Intent (SecondActivity.this, DailyActivity.class);
startActivity(intenter);
}
public void selectaddress(View view)
{
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try
{
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
}
catch(GooglePlayServicesRepairableException e)
{
e.printStackTrace();
}
catch (GooglePlayServicesNotAvailableException e)
{
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
address=(String) place.getAddress();
latLong= place.getLatLng();
t.setText(place.getAddress());
}
}
}
}
| true |
f5090994564ae6c3d3aec8ca27292ce384b503cf
|
Java
|
Hackforid/Tomato
|
/Tomato/src/main/java/com/smilehacker/tomato/view/TimeCountView.java
|
UTF-8
| 3,620 | 2.453125 | 2 |
[] |
no_license
|
package com.smilehacker.tomato.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by kleist on 13-9-28.
*/
public class TimeCountView extends View {
private final static String TAG = "TIMER_VIEW";
private final static int DEFAULT_HEIGHT = 500;
private final static int DEFAULT_WIDTH = 500;
private final static int CIRCEL_PAINT_WIDTH = 30;
private Paint mRedPaint;
private Paint mGrayPaint;
private int mWidth = 0;
private int mHeight = 0;
private float mRadius = 0;
private float mCenterX = 0;
private float mCenterY = 0;
private RectF mCircleRect;
private float mStartDegree = -90;
private float mCurrentDegree = 0;
public TimeCountView(Context context, AttributeSet attrs) {
super(context, attrs);
initDraw();
}
private void initDraw() {
mRedPaint = new Paint();
mRedPaint.setColor(Color.RED);
mRedPaint.setStrokeJoin(Paint.Join.BEVEL);
mRedPaint.setStrokeCap(Paint.Cap.SQUARE);
mRedPaint.setAntiAlias(true);
mRedPaint.setDither(true);
mRedPaint.setStyle(Paint.Style.STROKE);
mRedPaint.setStrokeWidth(CIRCEL_PAINT_WIDTH);
mGrayPaint = new Paint();
mGrayPaint.setColor(Color.GRAY);
mGrayPaint.setStrokeJoin(Paint.Join.ROUND);
mGrayPaint.setStrokeCap(Paint.Cap.ROUND);
mGrayPaint.setAntiAlias(true);
mGrayPaint.setDither(true);
mGrayPaint.setStrokeWidth(CIRCEL_PAINT_WIDTH);
mGrayPaint.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
drawGrayCircle(canvas);
drawRedArc(canvas);
}
private void drawGrayCircle(Canvas canvas) {
canvas.drawCircle(mCenterX, mCenterY, mRadius, mGrayPaint);
}
private void drawRedArc(Canvas canvas) {
canvas.drawArc(mCircleRect, mStartDegree, mCurrentDegree, false, mRedPaint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
mWidth = getMeasuredLength(widthMeasureSpec, true);
mHeight = getMeasuredLength(heightMeasureSpec, false);
setMeasuredDimension( mWidth, mHeight);
getCircleParams();
}
private int getMeasuredLength(int length, boolean isWidth) {
int specMode = MeasureSpec.getMode(length);
int specSize = MeasureSpec.getSize(length);
int size;
int padding = isWidth ? getPaddingLeft() + getPaddingRight()
: getPaddingTop() + getPaddingBottom();
if (specMode == MeasureSpec.EXACTLY) {
size = specSize;
} else {
size = isWidth ? padding + DEFAULT_WIDTH : DEFAULT_HEIGHT
+ padding;
if (specMode == MeasureSpec.AT_MOST) {
size = Math.min(size, specSize);
}
}
return size;
}
private void getCircleParams() {
mRadius = Math.min(mWidth, mHeight) / 2 - CIRCEL_PAINT_WIDTH;
mCenterX = mWidth / 2;
mCenterY = mHeight / 2;
float rectTop = mHeight / 2 - mRadius;
float rectLeft = mWidth / 2 - mRadius;
float rectBottom = mHeight - rectTop;
float rectRight = mWidth - rectLeft;
mCircleRect = new RectF(rectLeft, rectTop, rectRight, rectBottom);
}
public void setDegree(float degree) {
mCurrentDegree = degree;
invalidate();
}
}
| true |
f14337c9645d54dbc98e63b23d44d9d3622a074c
|
Java
|
moutainhigh/tproject
|
/java/cn/maitian/trade/warrant/saleContractSign/vo/SysnHouseTo/SaleTraderTo.java
|
UTF-8
| 710 | 1.867188 | 2 |
[] |
no_license
|
package cn.maitian.trade.warrant.saleContractSign.vo.SysnHouseTo;
/**
* 买卖同步交易人类
*/
public class SaleTraderTo {
private String perName; //名字
private String perTel; //电话
private String perIdCard; //证件号
public String getPerName() {
return perName;
}
public void setPerName(String perName) {
this.perName = perName;
}
public String getPerTel() {
return perTel;
}
public void setPerTel(String perTel) {
this.perTel = perTel;
}
public String getPerIdCard() {
return perIdCard;
}
public void setPerIdCard(String perIdCard) {
this.perIdCard = perIdCard;
}
}
| true |
3e8c8a89744fa7194a7aa9870afde061860a5d4c
|
Java
|
djhajjar/ser321examples
|
/Sockets/JavaThreadSock/src/main/java/ThreadedSockServer.java
|
UTF-8
| 3,622 | 3.3125 | 3 |
[] |
no_license
|
import java.net.*;
import java.io.*;
import java.util.*;
/**
* A class for simple client-server connections with a threaded server. This
* example uses Object Input and Output streams to communicate between client
* and server.
*
* Ser321 Foundations of Distributed Software Systems see
* http://pooh.poly.asu.edu/Ser321
*
* @author Tim Lindquist [email protected] Software Engineering, CIDSE,
* IAFSE, ASU Poly
* @version April 2020
*
* @modified-by David Clements <[email protected]> September 2020
*
*/
public class ThreadedSockServer extends Thread {
private Socket conn;
private int id;
private String buf[] = { "The Object class also has support for wait",
"If the timer has expired, the thread continues", "This call can cause some overhead in programs",
"Notify signals a waiting thread to wake up", "Wait blocks the thread and releases the lock" };
public ThreadedSockServer(Socket sock, int id) {
this.conn = sock;
this.id = id;
}
public void run() {
try {
// setup read/write channels for connection
ObjectInputStream in = new ObjectInputStream(conn.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
// read the digit being send
String s = (String) in.readObject();
int index;
// while client hasn't ended
while (!s.equals("end")) {
Boolean validInput = true;
// checks if input only contains digits
if (!s.matches("\\d+")) {
validInput = false;
out.writeObject("Not a number: https://gph.is/2yDymkn");
}
// if it contains only numbers
if (validInput) {
// convert to an integer
index = Integer.valueOf(s);
System.out.println("From client " + id + " get string " + index);
if (index > -1 & index < buf.length) {
// if valid, pull the line from the buffer array above and write it to socket
out.writeObject(buf[index]);
} else if (index == 5) {
// fun surprise for mostly correct
out.writeObject("Close but out of range: https://youtu.be/dQw4w9WgXcQ");
} else {
// really wrong
out.writeObject("index out of range");
}
}
// wait for next token from the user
s = (String) in.readObject();
}
// on close, clean up
System.out.println("Client " + id + " closed connection.");
in.close();
out.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws IOException {
Socket sock = null;
int id = 0;
try {
if (args.length != 1) {
System.out.println("Usage: gradle ThreadedSockServer --args=<port num>");
System.exit(0);
}
int portNo = Integer.parseInt(args[0]);
if (portNo <= 1024)
portNo = 8888;
ServerSocket serv = new ServerSocket(portNo);
while (true) {
System.out.println("Threaded server waiting for connects on port " + portNo);
sock = serv.accept();
System.out.println("Threaded server connected to client-" + id);
// create thread
ThreadedSockServer myServerThread = new ThreadedSockServer(sock, id++);
// run thread and don't care about managing it
myServerThread.start();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sock != null) sock.close();
}
}
}
| true |
b88fdbefbc2e6388b3ccc58cfe23fd3550734a31
|
Java
|
jdh5451/210607-FeederProgram
|
/java-workspace/ClassBasics/src/Main.java
|
UTF-8
| 640 | 3.65625 | 4 |
[] |
no_license
|
public class Main {
//Making this an executable class
public static void main(String[] args) {
Dog myDog;
//Calling our constructor
//invoking our constructor
//running our constructor
//executing our constructor
myDog = new Dog();
//=> creating an object!! In this case a Dog obhect
System.out.println(myDog.name);
System.out.println(myDog.size);
System.out.println(myDog);
myDog.name = "Ruby";
//Call bark on myDog
//System.out.println(myDog.bark());
int myResult = myDog.bark();
System.out.println(myDog.name);
Dog myOtherDog = new Dog();
System.out.println(myOtherDog.name);
}
}
| true |
10a32537cc4ffc68813854bbcb4b37df7d2bec20
|
Java
|
xiao-ren-wu/micro-service
|
/micro-service-order/src/main/java/org/yuwb/dao/OrderMapper.java
|
UTF-8
| 335 | 1.507813 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.yuwb.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.yuwb.model.Order;
/**
* @author WbYu
* e-mail [email protected]
* github https://github.com/xiao-ren-wu
* <p>
* </p>
* @version v1.0.0
* @date 2019/12/26 8:35 上午
* @since java 11
*/
public interface OrderMapper extends BaseMapper<Order> {
}
| true |
87f19cd6be3d1a77dbcb1a67966b20e87c0ba398
|
Java
|
anuraaga/armeria
|
/spring/boot-autoconfigure/src/test/java/com/linecorp/armeria/internal/spring/ArmeriaConfigurationUtilTest.java
|
UTF-8
| 6,167 | 1.5625 | 2 |
[
"BSD-3-Clause",
"EPL-1.0",
"WTFPL",
"MIT",
"JSON",
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2018 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.internal.spring;
import static com.linecorp.armeria.internal.spring.ArmeriaConfigurationUtil.configureAnnotatedServices;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableList;
import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.internal.server.annotation.AnnotatedService;
import com.linecorp.armeria.server.HttpService;
import com.linecorp.armeria.server.Server;
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.server.ServiceRequestContext;
import com.linecorp.armeria.server.SimpleDecoratingHttpService;
import com.linecorp.armeria.server.annotation.Get;
import com.linecorp.armeria.server.annotation.Options;
import com.linecorp.armeria.server.annotation.Path;
import com.linecorp.armeria.server.docs.DocService;
import com.linecorp.armeria.server.docs.DocServiceBuilder;
import com.linecorp.armeria.server.metric.MetricCollectingService;
import com.linecorp.armeria.spring.AnnotatedServiceRegistrationBean;
import com.linecorp.armeria.spring.MeterIdPrefixFunctionFactory;
class ArmeriaConfigurationUtilTest {
@Test
void makesSureDecoratorsAreConfigured() {
final Function<? super HttpService, ? extends HttpService> decorator = spy(new IdentityFunction());
final AnnotatedServiceRegistrationBean bean = new AnnotatedServiceRegistrationBean()
.setServiceName("test")
.setService(new SimpleService())
.setDecorators(decorator);
final ServerBuilder sb1 = Server.builder();
final DocServiceBuilder dsb1 = DocService.builder();
configureAnnotatedServices(sb1, dsb1, ImmutableList.of(bean),
MeterIdPrefixFunctionFactory.ofDefault(), null);
final Server s1 = sb1.build();
verify(decorator, times(2)).apply(any());
assertThat(service(s1).as(MetricCollectingService.class)).isNotNull();
reset(decorator);
final ServerBuilder sb2 = Server.builder();
final DocServiceBuilder dsb2 = DocService.builder();
configureAnnotatedServices(sb2, dsb2, ImmutableList.of(bean),
null, null);
final Server s2 = sb2.build();
verify(decorator, times(2)).apply(any());
assertThat(getServiceForHttpMethod(sb2.build(), HttpMethod.OPTIONS))
.isInstanceOf(AnnotatedService.class);
}
@Test
void makesSureDecoratedServiceIsAdded() {
final Function<? super HttpService, ? extends HttpService> decorator = spy(new DecoratingFunction());
final AnnotatedServiceRegistrationBean bean = new AnnotatedServiceRegistrationBean()
.setServiceName("test")
.setService(new SimpleService())
.setDecorators(decorator);
final ServerBuilder sb = Server.builder();
final DocServiceBuilder dsb = DocService.builder();
configureAnnotatedServices(sb, dsb, ImmutableList.of(bean), null, null);
final Server s = sb.build();
verify(decorator, times(2)).apply(any());
assertThat(service(s).as(SimpleDecorator.class)).isNotNull();
}
private static HttpService service(Server server) {
return server.config().defaultVirtualHost().serviceConfigs().get(0).service();
}
private static HttpService getServiceForHttpMethod(Server server, HttpMethod httpMethod) {
return server.serviceConfigs().stream()
.filter(config -> config.route().methods().contains(httpMethod))
.findFirst().get().service();
}
/**
* A decorator function which is the same as {@link #identity()} but is not a final class.
*/
static class IdentityFunction implements Function<HttpService, HttpService> {
@Override
public HttpService apply(HttpService delegate) {
return delegate;
}
}
/**
* A simple decorating function.
*/
static class DecoratingFunction implements Function<HttpService, HttpService> {
@Override
public HttpService apply(HttpService delegate) {
return new SimpleDecorator(delegate);
}
}
static class SimpleDecorator extends SimpleDecoratingHttpService {
SimpleDecorator(HttpService delegate) {
super(delegate);
}
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
return HttpResponse.of(HttpStatus.NO_CONTENT);
}
}
/**
* A simple annotated HTTP service.
*/
static class SimpleService {
// We need to specify '@Options' annotation in order to avoid adding a decorator which denies
// a CORS preflight request. If any decorator is added, the service will be automatically decorated
// with AnnotatedService#ExceptionFilteredHttpResponseDecorator.
@Get
@Options
@Path("/")
public String root() {
return "Hello, world!";
}
}
}
| true |
d6f6281b47e9bc0060c678b93d03ba92052c4032
|
Java
|
jianghongping/openxal
|
/core/src/xal/tools/dsp/DataProcessingException.java
|
UTF-8
| 1,685 | 2.90625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
/**
* DataProcessingException.java
*
* Created : August, 2007
* Author : Christopher K. Allen
*/
package xal.tools.dsp;
/**
* Exception representing an unrecoverable error in data processing.
*
* @author Christopher K. Allen
*
*/
public class DataProcessingException extends RuntimeException {
/*
* Global Constants
*/
/** Serialization version identifier */
private static final long serialVersionUID = 1L;
/*
* Initialization
*/
/**
* Create a new exception with no detail message.
*/
public DataProcessingException() {
super();
}
/**
* Create a new exception with a cause. The cause object is saved for later
* retrieval by the <code>Throwable.getCause()</code> method. A null value is
* permitted, and indicates that the cause is nonexistent or unknown.
* @param cause cause of the exception
*
* @see java.lang.Throwable#getCause()
*/
public DataProcessingException(Throwable cause) {
super(cause);
}
/**
* Create a new exception with a detail message.
*
* @param message detail message
*/
public DataProcessingException(String message) {
super(message);
}
/**
* Create a new exception with a detail message and cause.
*
* @param message detail message
* @param cause the cause object
*
* @see DataProcessingException#DataProcessingException(Throwable)
*/
public DataProcessingException(String message, Throwable cause) {
super(message, cause);
}
}
| true |
fc70afa9af15ced50b7b19657bf5e4e740bdd53c
|
Java
|
zhouziwen/yucha
|
/app/src/main/java/com/example/hntea/mvpmodel/home/HomeData.java
|
UTF-8
| 26,994 | 1.828125 | 2 |
[] |
no_license
|
package com.example.hnTea.mvpmodel.home;
import com.android.volley.VolleyError;
import com.example.hnTea.MyApplication;
import com.example.hnTea.https.JsonUtils;
import com.example.hnTea.https.VolleyBack;
import com.example.hnTea.https.Volley_StringRequest;
import com.example.hnTea.mvpmodel.BaseModel;
import com.example.hnTea.mvpmodel.home.bean.CategoryGoodsList;
import com.example.hnTea.mvpmodel.home.bean.MainShop_Banner;
import com.example.hnTea.mvpmodel.home.bean.MainShop_Base;
import com.example.hnTea.mvpmodel.home.bean.MainShop_Category;
import com.example.hnTea.mvpmodel.home.bean.MainShop_HotShop;
import com.example.hnTea.mvpmodel.home.bean.MainShop_Nav;
import com.example.hnTea.mvpmodel.home.bean.MainShop_ShangJia;
import com.example.hnTea.mvpmodel.home.bean.ProduceSearchModel;
import com.example.hnTea.mvpmodel.home.bean.ShopCarListModel;
import com.example.hnTea.mvpmodel.home.bean.ShopDetail_Base;
import com.example.hnTea.utils.WorkFactory;
import com.google.gson.reflect.TypeToken;
import com.umeng.socialize.utils.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import java.util.TreeMap;
/**
* Created by 太能 on 2016/11/16.
*/
public class HomeData extends BaseModel {
private MainShop_Base mainShop_base;
//*****************************************首页 商城收据***********************************
public void GetMainHomeData(final IActionHome<MainShop_Base> iActionHome) {
WorkFactory.instance.service().submit(new Runnable() {
@Override
public void run() {
mainShop_base = new MainShop_Base(null, null, null, null, null);
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.start("");
}
});
//轮播图
TreeMap<String, String> map = new TreeMap<>();
map.put("c", "Shop");
map.put("m", "banner");
Volley_StringRequest.toRequest(map, new VolleyBack() {
@Override
public void onRequestSuccess(JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
String json = jsonObject.getString("data");
List<MainShop_Banner> banners = JsonUtils.parseArray(json,
new TypeToken<List<MainShop_Banner>>() {
});
mainShop_base.setBanners(banners);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(VolleyError volleyError) {
}
});
//首页分类 快速导航
TreeMap<String, String> map1 = new TreeMap<>();
map1.put("c", "Shop");
map1.put("m", "category");
Volley_StringRequest.toRequest(map1, new VolleyBack() {
@Override
public void onRequestSuccess(JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
String json = jsonObject.getString("data");
List<MainShop_Nav> navs = JsonUtils.parseArray(json,
new TypeToken<List<MainShop_Nav>>() {
});
mainShop_base.setNav(navs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(VolleyError volleyError) {
}
});
//热门商品模块
TreeMap<String, String> map2 = new TreeMap<>();
map2.put("c", "Shop");
map2.put("m", "hotGoods");
Volley_StringRequest.toRequest(map2, new VolleyBack() {
@Override
public void onRequestSuccess(JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
String json = jsonObject.getString("data");
List<MainShop_HotShop> hots = JsonUtils.parseArray(json,
new TypeToken<List<MainShop_HotShop>>() {
});
mainShop_base.setHotShops(hots);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(VolleyError volleyError) {
}
});
//入住商家
TreeMap<String, String> map3 = new TreeMap<>();
map3.put("c", "Shop");
map3.put("m", "getSupplier");
Volley_StringRequest.toRequest(map3, new VolleyBack() {
@Override
public void onRequestSuccess(JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
String json = jsonObject.getString("data");
List<MainShop_ShangJia> shangjia = JsonUtils.parseArray(json,
new TypeToken<List<MainShop_ShangJia>>() {
});
mainShop_base.setShnagJia(shangjia);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(VolleyError volleyError) {
}
});
//分类楼层
TreeMap<String, String> map4 = new TreeMap<>();
map4.put("m", "categoryList");
map4.put("c", "shop");
Volley_StringRequest.toRequest(map4, new VolleyBack() {
@Override
public void onRequestSuccess(JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
String json = jsonObject.getString("data");
List<MainShop_Category> category =
JsonUtils.parseArray(json, new TypeToken<List<MainShop_Category>>() {
});
mainShop_base.setCategory(category);
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.success(mainShop_base);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(VolleyError volleyError) {
}
});
}
});
}
//**************************************商品 详情 的数据***********************************
public void getShopDetailData(final String goodsId,
final String token,
final IActionHome<ShopDetail_Base> iActionHome) {
WorkFactory.instance.service().submit(() -> {
mHandler.post(() -> iActionHome.start(""));
TreeMap map = new TreeMap();
map.put("c", "Goods");
map.put("m", "getGoodsInfo");
map.put("goodsId", goodsId);
map.put("token", token);
Volley_StringRequest.toRequest(map, new VolleyBack() {
@Override
public void onRequestSuccess(final JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
//解析数据
String json = jsonObject.getString("data");
final ShopDetail_Base shopDetail_base =
JsonUtils.parseArray(json, ShopDetail_Base.class);
mHandler.post(() -> iActionHome.success(shopDetail_base));
} else {
mHandler.post(() -> {
try {
iActionHome.phpFail(jsonObject.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(final VolleyError volleyError) {
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.fail(volleyError);
}
});
}
});
});
}
//**************************************类型商品 列表 的数据***********************************
public void getCategoryGoodsList(final String sonCategoryId, final String styleId,
final String categoryId, final String brandId,
final String page, final IActionHome<CategoryGoodsList> iActionHome) {
WorkFactory.instance.service().submit(new Runnable() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.start("");
}
});
TreeMap<String, String> map = new TreeMap<>();
map.put("c", "Goods");
map.put("m", "goodsList");
map.put("scId", sonCategoryId);
map.put("sId", styleId);
map.put("cId", categoryId);
map.put("page", page);
map.put("bId", brandId);
Volley_StringRequest.toRequest(map, new VolleyBack() {
@Override
public void onRequestSuccess(final JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
//解析数据
String json = jsonObject.getString("data");
final CategoryGoodsList categoryGoodsList = JsonUtils.parseArray(json, CategoryGoodsList.class);
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.success(categoryGoodsList);
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
iActionHome.phpFail(jsonObject.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(final VolleyError volleyError) {
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.fail(volleyError);
}
});
}
});
}
});
}
//**************************************用户收藏商品*******************************************
public void UserCollection(final String goodId,
final String token,
final IActionHome<String> iActionHome) {
WorkFactory.instance.service().submit(() -> {
mHandler.post(() -> iActionHome.start(""));
TreeMap map = new TreeMap();
map.put("c", "Goods");
map.put("m", "GoodsCollection");
map.put("goodsId", goodId);
map.put("token", token);
Volley_StringRequest.toRequest(map, new VolleyBack() {
@Override
public void onRequestSuccess(final JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
iActionHome.success(jsonObject.getString("data"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
iActionHome.phpFail(jsonObject.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(final VolleyError volleyError) {
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.fail(volleyError);
}
});
}
});
});
}
//**************************************购物车商品拉取*******************************************
public void getShopCarData(final IActionHome<List<ShopCarListModel>> iActionHome) {
WorkFactory.instance.service().submit(new Runnable() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.start("");
}
});
TreeMap<String, String> map = new TreeMap<String, String>();
map.put("c", "Cart");
map.put("m", "cartList");
map.put("token", MyApplication.getUserToken());
Volley_StringRequest.toRequest(map, new VolleyBack() {
@Override
public void onRequestSuccess(final JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
String json = jsonObject.getString("data");
final List<ShopCarListModel> shopCarListModels = JsonUtils.parseArray(json,
new TypeToken<List<ShopCarListModel>>() {
});
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.success(shopCarListModels);
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
iActionHome.phpFail(jsonObject.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(final VolleyError volleyError) {
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.fail(volleyError);
}
});
}
});
}
});
}
//**************************************加入购物车*******************************************
public void getAddShopCar(final String product_id,
final String product_number,
final IActionHome<String> iActionHome) {
WorkFactory.instance.service().submit(new Runnable() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.start("");
}
});
TreeMap<String, String> map = new TreeMap<>();
map.put("c", "Cart");
map.put("m", "add");
map.put("product_id", product_id);
map.put("product_number", product_number);
map.put("token", MyApplication.getUserToken());
Volley_StringRequest.toRequest(map, new VolleyBack() {
@Override
public void onRequestSuccess(final JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.success("添加成功");
}
});
} else if (jsonObject.getInt("code") == 2) {
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.phpFail("商品库存不足");
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.phpFail("您必须选择一件商品,且商品数量不能为0");
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(final VolleyError volleyError) {
mHandler.post(new Runnable() {
@Override
public void run() {
iActionHome.fail(volleyError);
}
});
}
});
}
});
}
//************************************** 商品搜索 *******************************************
public void getProductSearch(final String keyWord,
final String styleId,
final String page,
final IActionHome<ProduceSearchModel> iActionHome) {
WorkFactory.instance.service().submit(() -> {
mHandler.post(() -> iActionHome.start(""));
TreeMap<String, String> map = new TreeMap<>();
map.put("c", "Goods");
map.put("m", "search");
map.put("k", keyWord);
map.put("sId", styleId);
map.put("page", page);
Volley_StringRequest.toRequest(map, new VolleyBack() {
@Override
public void onRequestSuccess(final JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
String json = jsonObject.getString("data");
final ProduceSearchModel produceSearchModel = JsonUtils.parseArray(json, ProduceSearchModel.class);
mHandler.post(() -> iActionHome.success(produceSearchModel));
} else {
mHandler.post(() -> {
try {
iActionHome.phpFail(jsonObject.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(final VolleyError volleyError) {
mHandler.post(() -> iActionHome.fail(volleyError));
}
});
});
}
//************************************** 商品删除 *******************************************
public void deleteShopCarGoods(String product_id, IActionHome<String> iActionHome) {
WorkFactory.instance.service().submit(() -> {
mHandler.post(() -> iActionHome.start(""));
TreeMap<String, String> map = new TreeMap<String, String>();
map.put("c", "Cart");
map.put("m", "delete");
map.put("product_id", product_id);
map.put("token", MyApplication.getUserToken());
Volley_StringRequest.toRequest(map, new VolleyBack() {
@Override
public void onRequestSuccess(JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
String json = jsonObject.getString("message");
mHandler.post(() -> iActionHome.success(json));
} else {
mHandler.post(() -> {
try {
iActionHome.phpFail(jsonObject.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(VolleyError volleyError) {
mHandler.post(() -> iActionHome.fail(volleyError));
}
});
});
}
//************************************** 修改数量 *******************************************
public void modifyGoodsNum(String product_id, String num, IActionHome<String> iActionHome) {
WorkFactory.instance.service().submit(() -> {
mHandler.post(() -> iActionHome.start(""));
TreeMap<String, String> map = new TreeMap<String, String>();
map.put("c", "Cart");
map.put("m", "update");
map.put("product_id", product_id);
map.put("num", num);
map.put("token", MyApplication.getUserToken());
Volley_StringRequest.toRequest(map, new VolleyBack() {
@Override
public void onRequestSuccess(JSONObject jsonObject) {
try {
if (jsonObject.getInt("code") == 1) {
String json = jsonObject.getString("message");
mHandler.post(() -> iActionHome.success(json));
} else {
mHandler.post(() -> {
try {
iActionHome.phpFail(jsonObject.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onVolleyError(VolleyError volleyError) {
mHandler.post(() -> iActionHome.fail(volleyError));
}
});
});
}
}
| true |
905aab4225830927774a685d0aa20f0a8b890643
|
Java
|
jennyhyojookwon/comp2511
|
/F10B-hoenny-master/src/unsw/dungeon/Player.java
|
UTF-8
| 17,935 | 2.796875 | 3 |
[] |
no_license
|
package unsw.dungeon;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
/**
* The player entity
* @author Robert Clifton-Everest
*
*/
public class Player extends Entity implements Subject {
private Dungeon dungeon;
private Boolean status;
private Bag bag;
//private Boolean life;
private ArrayList<Observer> observers;
private PlayerState playerState;
private TimerTask task; // used for timer
private Timer timer; //timer is for set the player to be not invincible after 30s
/**
* Create a player positioned in square (x,y)
* @param x
* @param y
*/
public Player(Dungeon dungeon, int x, int y, int id) {
super(x, y, id);
this.dungeon = dungeon;
this.status = false;
this.bag = new Bag(dungeon, this);
//this.life = true;
this.playerState = new VulnerableState();
this.observers = new ArrayList<Observer>();
this.timer = new Timer();
this.task = new TimerTask() {
@Override
public void run() {
}
};
}
public void moveUp() {
if (!playerState.equals(new GameOverState()) && getY() > 0) {
Entity next_en = dungeon.checkEntity(getX(), getY() - 1);
Entity nnext_en = dungeon.checkEntity(getX(), getY() - 2);
ArrayList<Key> keys = bag.getKeys();
if(dungeon.getStart() == 0) {dungeon.checkInitiallyTriggered();}
openDoorWithKey(next_en, keys);
if (!checkMove(next_en, keys) || dungeon.noObstacle(next_en, nnext_en, this)) {return;}
if (next_en != null) {
dungeon.meetEnetity(next_en, this);
if (dungeon.checkBoulder(next_en) || dungeon.checkSwitch(next_en)) {
checkObstacle(getX(), getY() - 2);
if(collisionOccurs(getX(), getY()-2, next_en)) {return;}
if(dungeon.checkSwitch(getX(), getY()-2)) {
FloorSwitch triggered = (FloorSwitch) dungeon.checkEntity(getX(), getY()-2);
if(checkDoubleBoulder(next_en, triggered)) {return;}
else if(dungeon.checkBoulder(next_en) && triggered.checkTrigger() == false) {
triggerwithBoulder(next_en, nnext_en);
return;
}
}
if(dungeon.getClass().getName().endsWith("FloorSwich") && ((FloorSwitch)next_en).checkTrigger() == true) {
if(!checkWall(getX(), getY() - 2) || !checkMultipleBoulder(getX(), getY() - 2)) {return;}
Boulder bt = (Boulder)dungeon.getTriggerBoulder(dungeon.getAllEntity(getX(), getY() - 1));
dungeon.pushBoulder(bt, this);
((FloorSwitch)next_en).untriggerSwitch();
return;
}
}
else if (dungeon.checkPortal(next_en)) {
MovePlayertoEnetity(next_en);
notify_dis();
return;
}
}
y().set(getY() - 1);
notify_dis();
}
}
public void moveDown() {
if (!playerState.equals(new GameOverState()) && getY() < dungeon.getHeight() - 1) {
Entity next_en = dungeon.checkEntity(getX(), getY() + 1);
Entity nnext_en = dungeon.checkEntity(getX(), getY() + 2);
ArrayList<Key> keys = bag.getKeys();
if(dungeon.getStart() == 0) {dungeon.checkInitiallyTriggered();}
openDoorWithKey(next_en, keys);
if (! checkMove(next_en, keys) || dungeon.noObstacle(next_en, nnext_en, this)) {return;}
if (next_en != null) {
dungeon.meetEnetity(next_en, this);
if (dungeon.checkBoulder(next_en) || dungeon.checkSwitch(next_en)) {
checkObstacle(getX(), getY() + 2);
if(collisionOccurs(getX(), getY() + 2, next_en)) {return;}
if(dungeon.checkSwitch(getX(), getY()+2)) {
FloorSwitch triggered = (FloorSwitch) dungeon.checkEntity(getX(), getY() + 2);
if(checkDoubleBoulder(next_en, triggered)) {return;}
else if(dungeon.checkBoulder(next_en) && triggered.checkTrigger() == false) {
triggerwithBoulder(next_en, nnext_en);
notify_dis();
return;
}
}
if(dungeon.getClass().getName().endsWith("FloorSwich") && ((FloorSwitch)next_en).checkTrigger() == true) {
if(!checkWall(getX(), getY() + 2) || !checkMultipleBoulder(getX(), getY() + 2)) {return;}
Boulder bt = (Boulder)dungeon.getTriggerBoulder(dungeon.getAllEntity(getX(), getY() + 1));
dungeon.pushBoulder(bt, this);
((FloorSwitch)next_en).untriggerSwitch();
return;
}
}
else if (dungeon.checkPortal(next_en)) {
MovePlayertoEnetity(next_en);
notify_dis();
return;
}
}
y().set(getY() + 1);
notify_dis();
}
}
public void moveLeft() {
if (!playerState.equals(new GameOverState()) && getX() > 0) {
Entity next_en = dungeon.checkEntity(getX()-1, getY());
Entity nnext_en = dungeon.checkEntity(getX()-2, getY());
ArrayList<Key> keys = bag.getKeys();
if(dungeon.getStart() == 0) {dungeon.checkInitiallyTriggered();}
openDoorWithKey(next_en, keys);
if (!checkMove(next_en, keys) || dungeon.noObstacle(next_en, nnext_en, this)) {return;}
if (next_en != null) {
dungeon.meetEnetity(next_en, this);
if (dungeon.checkBoulder(next_en) || dungeon.checkSwitch(next_en)) {
checkObstacle(getX()-2, getY());
if(collisionOccurs(getX()-2, getY(), next_en)) {return;}
if(dungeon.checkSwitch(getX()-2, getY())) {
FloorSwitch triggered = (FloorSwitch) dungeon.checkEntity(getX()-2, getY());
if(checkDoubleBoulder(next_en, triggered)) {return;}
else if(dungeon.checkBoulder(next_en) && triggered.checkTrigger() == false) {
triggerwithBoulder(next_en, nnext_en);
return;
}
}
if(dungeon.getClass().getName().endsWith("FloorSwich") && ((FloorSwitch)next_en).checkTrigger() == true) {
if(!checkWall(getX()-2, getY() ) || !checkMultipleBoulder(getX()-2, getY() )) {return;}
Boulder bt = (Boulder)dungeon.getTriggerBoulder(dungeon.getAllEntity(getX()-1, getY()));
dungeon.pushBoulder(bt, this);
((FloorSwitch)next_en).untriggerSwitch();
return;
}
}
else if (dungeon.checkPortal(next_en)) {
MovePlayertoEnetity(next_en);
notify_dis();
return;
}
}
x().set(getX() - 1);
notify_dis();
}
}
public void moveRight() {
if (!playerState.equals(new GameOverState()) && getX() < dungeon.getWidth() - 1) {
Entity next_en = dungeon.checkEntity(getX()+1, getY());
Entity nnext_en = dungeon.checkEntity(getX()+2, getY());
ArrayList<Key> keys = bag.getKeys();
if(dungeon.getStart() == 0) {dungeon.checkInitiallyTriggered();}
openDoorWithKey(next_en, keys);
if (! checkMove(next_en, keys) || dungeon.noObstacle(next_en, nnext_en, this)) {return;}
if (next_en != null) {
dungeon.meetEnetity(next_en, this);
if (dungeon.checkBoulder(next_en) || dungeon.checkSwitch(next_en)) {
checkObstacle(getX()+2, getY());
if(collisionOccurs(getX()+2, getY(), next_en)) {return;}
if(dungeon.checkSwitch(getX()+2, getY())) {
FloorSwitch triggered = (FloorSwitch) dungeon.checkEntity(getX()+2, getY());
if(checkDoubleBoulder(next_en, triggered)) {return;}
else if(dungeon.checkBoulder(next_en) && triggered.checkTrigger() == false) {
triggerwithBoulder(next_en, nnext_en);
return;
}
}
if(dungeon.getClass().getName().endsWith("FloorSwich") && ((FloorSwitch)next_en).checkTrigger() == true) {
if(!checkWall(getX()+2, getY()) || !checkMultipleBoulder(getX()+2, getY())) {return;}
Boulder bt = (Boulder)dungeon.getTriggerBoulder(dungeon.getAllEntity(getX()+1, getY()));
dungeon.pushBoulder(bt, this);
((FloorSwitch)next_en).untriggerSwitch();
return;
}
}
else if (dungeon.checkPortal(next_en)) {
MovePlayertoEnetity(next_en);
notify_dis();
return;
}
}
x().set(getX() + 1);
notify_dis();
}
}
/*
* restrict player's movement when there is an obstacle in the front
*/
public boolean checkMove(Entity nextEntity, ArrayList<Key> keys) {
String nameString = dungeon.EntityName(nextEntity);
if (nameString.equals("unsw.dungeon.Wall")) {return false;}
else if(nameString.equals("unsw.dungeon.Door") && ((Door)nextEntity).checkOpen() == true) {return true;}
else if(nameString.equals("unsw.dungeon.Door") && !KeyMatchDoor(nextEntity, keys)) {return false;}
return true;
}
/*
* method to check whether the player has a matching key to open the door
*/
public boolean KeyMatchDoor(Entity next_en, ArrayList<Key> arrayList) {
if(arrayList.isEmpty()) {return false;}
int doorID = ((Door)next_en).getID();
int keyID = ((Key)arrayList.get(0)).getID();
if(keyID == doorID) {
System.out.println("you have the matching key to open the door.");
return true;
}
return false;
}
public Boolean checkDoor(Entity nextEntity) {
String nameString = dungeon.EntityName(nextEntity);
if(nameString.endsWith("Door")) {
if(((Door) nextEntity).checkOpen()) {return false;}
return true;
}
return false;
}
/*
* check item for the player to pick up
*/
public Boolean checkItem(Entity nextEntit) {
String nameString = dungeon.EntityName(nextEntit);
if (nameString.endsWith("Potion")) {
nextEntit.changeStaus(this); //this is to change the status of player (like became incincible)
return true;
} else if (nameString.endsWith("Treasure")) {
bag.addTreasure();
checkGoal("treasure");
return true;
} else if (nameString.endsWith("Sword")) {
bag.addSword();
return true;
} else if (nameString.endsWith("Key") && bag.getKeys().size() < 1) {
bag.addKeys((Key)nextEntit);
return true;
} else if(nameString.endsWith("Key") && bag.getKeys().size() >= 1) {
bag.replaceKey(nextEntit);
return false;
} else if (nameString.endsWith("Exit")) {
nextEntit.setLife();
checkGoal("exit");
} else if (nameString.endsWith("Bomb")) {
bag.getBomb();
return true;
}
return false;
}
/*
* check status after player meeting enemy
*/
public Boolean meetEnemy(Entity enemy) {
if (this.status) {//invinciable
//dungeon.removeEntity(enemy); // this function is not finished yet
enemy.setLife();
checkGoal("enemies");
return true;
} else if (this.bag.checkSword(enemy)){ // ok, we have sword
killEnemy_Sword(enemy);
return true;
} else {
// killed by enemy
//dungeon.removeEntity(this); // this function is not finished yet
//dungeon.setPlayer(null);
killPlayer(enemy);
setPlayerState(new GameOverState());
return false;
}
}
public void killEnemy_Sword(Entity enemy) {
enemy.setLife();
dungeon.removeEntity(enemy);
Enemy en = (Enemy) enemy;
en.killEnemy();
bag.useSword(enemy);
checkGoal("enemies");
}
public void useBomb() {
System.out.println("try to use bomb");
bag.useBomb();
}
public void killPlayer(Entity enemy) {
enemy.setIschanged();
if (dungeon.getPlayer() == null) {
System.out.println("player is null");
}
this.setLife();
System.out.println("player dies============" + getID());
if (!dungeon.allPlayerLife()) {
System.out.println("you lose");
System.exit(1); // I don't think that is a good idea
}
dungeon.removeEntity(this);
moveObservers(enemy);
}
public void moveObservers(Entity enemy) {
dungeon.moveObservers(this, enemy);
}
public ArrayList<Observer> getObservers() {return observers;}
public void MovePlayertoEnetity(Entity portal) {
Portal portal2 = (Portal) portal;
Entity dest = dungeon.checkEntity(portal2);
if (dest == null) {System.out.println("dest portal is null");}
x().set(dest.getX());
y().set(dest.getY());
}
public boolean checkWall(int x, int y) {
String nameString = dungeon.EntityName(x, y);
if (nameString.equals("unsw.dungeon.Wall") ) {return false;}
return true;
}
public boolean checkMultipleBoulder(int x, int y) {
String nameString = dungeon.EntityName(x, y);
if (nameString.equals("unsw.dungeon.Boulder") ) {return false;}
return true;
}
public void addObderver(Observer ob) {this.observers.add(ob);}
public void removeObserver(Observer ob) {this.observers.remove(ob);}
@Override
public void notify_them() {
for (Observer ob: observers) {
ob.update(this);
}
}
public PlayerState getPlayerState() {return playerState;}
public void setPlayerState(PlayerState playerState) {this.playerState = playerState;}
public Boolean playerStatus() {return this.status;}
/*
* open door with correspodnign key
*/
public void openDoorWithKey(Entity next_en, ArrayList<Key> keys) {
if(checkDoor(next_en)) {
if(bag.getKeys().size() == 0) {return;}
if(bag.getKeys().size() >= 1 && dungeon.EntityName(next_en).equals("key")) {bag.replaceKey((Key)next_en);}
else if(!KeyMatchDoor(next_en, bag.getKeys())) {return;}
else if(KeyMatchDoor(next_en, bag.getKeys())) {
dungeon.removeEntity(keys.get(0));
bag.removeKey(keys.get(0));
//y().set(getY() - 1);
((Door)next_en).openDoor();
dungeon.getDungeonController().setDoorFlag();
dungeon.getDungeonController().setDoor(next_en);
return;
}
}
}
/*
* check collision before pushing boulder
*/
private boolean collisionOccurs(int x, int y, Entity next_en) {
if(!checkMultipleBoulder(x, y) && dungeon.checkBoulder(next_en)) {return true;}
if(!checkWall(x, y) && dungeon.checkBoulder(next_en)) {return true;}
return false;
}
private void triggerSwitch(FloorSwitch ent) {
if(dungeon.checkSwitch(ent) && ent.checkTrigger() == false) {
ent.triggerSwitch();
return;
}
}
private void checkObstacle(int x, int y) {
if(!checkWall(x, y) || !checkMultipleBoulder(x, y)) {return;}
}
@Override
public void notify_dis() {
for(Observer ob: observers) {
ob.update_dis(this);
}
}
public void checkGoal(String goalString) {
if (goalString.equals("enemies")) {
if (dungeon.checkAllEnemyDead()) {
dungeon.checkName("enemies");
}
} else if (goalString.equals("exit")) {
System.out.println("1111111");
dungeon.checkName("exit");
System.out.println("22222");
} else if (goalString.equals("treasure")) {
if (dungeon.getAllcollectedTreasure() == dungeon.getTreasure()) {
dungeon.checkName("treasure");
}
} else if (goalString.equals("boulder")) {
if (dungeon.checkTriggered(dungeon.getAllSwitch())) {
dungeon.checkName("boulder");
}
}
dungeon.checkReachGoal();
}
public int getTreasure() {return bag.getTreasure();}
public Boolean getStatus() {return status;}
public Bag getBag() {return bag;}
public int getSwordTime() {return bag.getSwordTime();}
private boolean checkDoubleBoulder(Entity next_en, FloorSwitch triggered) {
if(dungeon.checkBoulder(next_en) && triggered.checkTrigger() == true) {return true;}
return false;
}
public void changeinvincibleStatus() {
this.status = true;
notify_them(); //notify all the enemies that change their move pattern to "leave player"
}
public void changeStatusPotion() {
this.status = false;
notify_them(); //notify them the player is not invincible anymore
}
public Boolean checkStatus() {return status;}
public void resetTimer() {
System.out.println("resetting the potion timer");
timer.cancel();
timer.purge();
task.cancel();
timer = new Timer();
this.task = new TimerTask() {
@Override
public void run() {
changeStatusPotion(); // change is back
}
};
timer.schedule(this.task, 5000);
}
public void typeSpace() {
System.out.println("I typred space");
}
public void typeW() {
System.out.println("I typred W");
}
public void triggerwithBoulder(Entity next_en, Entity nnext_en) {
if(nnext_en == null) {return;}
//push down
if(next_en.getY() == getY()-1) {
y().set(getY() - 1); //move player
((Boulder)next_en).moveUp();
triggerSwitch((FloorSwitch)nnext_en);
//return;
}
// push down
if(next_en.getY() == getY()+1) {
y().set(getY() + 1); //move player
((Boulder)next_en).moveDown();
triggerSwitch((FloorSwitch)nnext_en);
//return;
}
// push left
if(next_en.getX() == getX()-1) {
x().set(getX() - 1); //move player
((Boulder)next_en).moveLeft();
triggerSwitch((FloorSwitch)nnext_en);
//return;
}
if(next_en.getX() == getX()+1) {
x().set(getX() + 1); //move player
((Boulder)next_en).moveRight();
triggerSwitch((FloorSwitch)nnext_en);
//return;
}
}
public Entity upEnt() {
return dungeon.checkEntity(getX(), getY() - 1);
}
public Entity downEnt() {
return dungeon.checkEntity(getX(), getY() + 1);
}
public Entity leftEnt() {
return dungeon.checkEntity(getX()-1, getY());
}
public Entity rightEnt() {
return dungeon.checkEntity(getX()+1, getY());
}
}
| true |
44e5c2b0185524af1276dea0950b65fc0bb7a202
|
Java
|
ResearchCollectionsAndPreservation/scsb-circ
|
/src/test/java/org/recap/ils/PrincetonJSIPConnectorUT.java
|
UTF-8
| 12,210 | 1.84375 | 2 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
package org.recap.ils;
import com.pkrete.jsip2.messages.responses.SIP2ItemInformationResponse;
import com.pkrete.jsip2.util.MessageUtil;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.recap.BaseTestCase;
import org.recap.ils.model.response.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import static org.junit.Assert.*;
/**
* Created by saravanakumarp on 28/9/16.
*/
public class PrincetonJSIPConnectorUT extends BaseTestCase {
@Mock
private PrincetonJSIPConnector princetonESIPConnector;
@Autowired
private PrincetonJSIPConnector pulESIPConnector;
private static final Logger logger = LoggerFactory.getLogger(PrincetonJSIPConnectorUT.class);
String[] itemIds = {"32101077423406", "32101061738587", "77777", "77777777777779", "32101065514414", "32101057972166", "PULTST54329"};
private String itemIdentifier = "32101077423406";
private String patronIdentifier = "22101008354581";
private String[] patronId = {"45678912", "45678913", "45678915"};
private String pickupLocation = "rcpcirc";
private String bibId = "9959052";
private String institutionId = "htccul";
private String itemInstitutionId = "";
private String expirationDate = MessageUtil.createFutureDate(1, 1);
@Test
public void login() throws Exception {
// Mockito.when(princetonESIPConnector.jSIPLogin(null, patronIdentifier)).thenReturn(true);
boolean sip2LoginRequest = pulESIPConnector.jSIPLogin(null, patronIdentifier);
assertTrue(sip2LoginRequest);
sip2LoginRequest = pulESIPConnector.jSIPLogin(null, "1212");
assertFalse(sip2LoginRequest);
}
@Test
public void lookupItem() throws Exception {
String[] itemIdentifiers = {"PULTST54321", "PULTST54322", "PULTST54323", "PULTST54324", "PULTST54325", "PULTST54326", "PULTST54334", "PULTST54335", "PULTST54337", "PULTST54338", "PULTST54339", "PULTST54340"};
for (int i = 0; i < itemIdentifiers.length; i++) {
String identifier = itemIdentifiers[i];
Mockito.when((ItemInformationResponse) princetonESIPConnector.lookupItem(identifier)).thenReturn(getItemInformationResponse());
ItemInformationResponse itemInformationResponse = (ItemInformationResponse) princetonESIPConnector.lookupItem(identifier);
logger.info("\n\n");
logger.info("Item barcode : " + itemInformationResponse.getItemBarcode());
logger.info("Circulation Status : " + itemInformationResponse.getCirculationStatus());
logger.info("SecurityMarker : " + itemInformationResponse.getSecurityMarker());
logger.info("Fee Type : " + itemInformationResponse.getFeeType());
logger.info("Transaction Date : " + itemInformationResponse.getTransactionDate());
logger.info("Hold Queue Length (CF) : " + itemInformationResponse.getHoldQueueLength());
}
// assertEquals(this.itemIdentifier,itemInformationResponse.getItemBarcode());
}
@Test
public void lookupUser() throws Exception {
String patronIdentifier = "45678912";
String institutionId = "htccul";
// Mockito.when((PatronInformationResponse) princetonESIPConnector.lookupPatron(patronIdentifier)).thenReturn(new PatronInformationResponse());
PatronInformationResponse patronInformationResponse = (PatronInformationResponse) pulESIPConnector.lookupPatron(patronIdentifier);
assertNotNull(patronInformationResponse);
}
@Test
public void checkout() throws Exception {
Mockito.when((ItemCheckoutResponse) princetonESIPConnector.checkOutItem(itemIdentifier, patronIdentifier)).thenReturn(getItemCheckoutResponse());
ItemCheckoutResponse itemCheckoutResponse = (ItemCheckoutResponse) princetonESIPConnector.checkOutItem(itemIdentifier, patronIdentifier);
assertNotNull(itemCheckoutResponse);
assertTrue(itemCheckoutResponse.isSuccess());
lookupItem();
}
@Test
public void checkIn() throws Exception {
Mockito.when((ItemCheckinResponse) princetonESIPConnector.checkInItem(itemIdentifier, patronIdentifier)).thenReturn(getItemCheckinResponse());
ItemCheckinResponse itemCheckinResponse = (ItemCheckinResponse) princetonESIPConnector.checkInItem(itemIdentifier, patronIdentifier);
assertNotNull(itemCheckinResponse);
assertTrue(itemCheckinResponse.isSuccess());
lookupItem();
}
@Test
public void check_out_In() throws Exception {
String itemIdentifier = "32101077423406";
String patronIdentifier = "198572368";
Mockito.when((ItemCheckoutResponse) princetonESIPConnector.checkOutItem(this.itemIdentifier, this.patronIdentifier)).thenReturn(getItemCheckoutResponse());
ItemCheckoutResponse itemCheckoutResponse = (ItemCheckoutResponse) princetonESIPConnector.checkOutItem(this.itemIdentifier, this.patronIdentifier);
assertNotNull(itemCheckoutResponse);
assertTrue(itemCheckoutResponse.isSuccess());
lookupItem();
Mockito.when((ItemCheckinResponse) princetonESIPConnector.checkInItem(this.itemIdentifier, this.patronIdentifier)).thenReturn(getItemCheckinResponse());
ItemCheckinResponse itemCheckinResponse = (ItemCheckinResponse) princetonESIPConnector.checkInItem(this.itemIdentifier, this.patronIdentifier);
assertNotNull(itemCheckinResponse);
assertTrue(itemCheckinResponse.isSuccess());
lookupItem();
}
@Test
public void cancelHold() throws Exception {
Mockito.when((ItemHoldResponse) princetonESIPConnector.cancelHold(itemIdentifier, patronIdentifier, institutionId, expirationDate, bibId, pickupLocation, null)).thenReturn(getItemHoldResponse());
ItemHoldResponse holdResponse = (ItemHoldResponse) princetonESIPConnector.cancelHold(itemIdentifier, patronIdentifier, institutionId, expirationDate, bibId, pickupLocation, null);
try {
assertNotNull(holdResponse);
assertTrue(holdResponse.isSuccess());
} catch (AssertionError e) {
logger.error("Cancel Hold Error - > ", e);
}
lookupItem();
}
@Test
public void placeHold() throws Exception {
Mockito.when((ItemHoldResponse) princetonESIPConnector.placeHold(itemIdentifier, patronIdentifier, institutionId, itemInstitutionId, expirationDate, bibId, pickupLocation, null, null, null, null)).thenReturn(getItemHoldResponse());
ItemHoldResponse holdResponse = (ItemHoldResponse) princetonESIPConnector.placeHold(itemIdentifier, patronIdentifier, institutionId, itemInstitutionId, expirationDate, bibId, pickupLocation, null, null, null, null);
try {
assertNotNull(holdResponse);
assertTrue(holdResponse.isSuccess());
} catch (AssertionError e) {
logger.error("Hold Error - > ", e);
}
lookupItem();
}
@Test
public void bothHold() throws Exception {
String itemIdentifier = "32101095533293";
String patronIdentifier = "198572368";
String institutionId = "htccul";
String itemInstitutionId = "";
String expirationDate = MessageUtil.getSipDateTime(); // Date Format YYYYMMDDZZZZHHMMSS
String bibId = "100001";
String pickupLocation = "htcsc";
ItemHoldResponse holdResponse;
Mockito.when((ItemHoldResponse) princetonESIPConnector.cancelHold(itemIdentifier, patronIdentifier, institutionId, expirationDate, bibId, pickupLocation, null)).thenReturn(getItemHoldResponse());
Mockito.when((ItemHoldResponse) princetonESIPConnector.placeHold(itemIdentifier, patronIdentifier, institutionId, itemInstitutionId, expirationDate, bibId, pickupLocation, null, null, null, null)).thenReturn(getItemHoldResponse());
holdResponse = (ItemHoldResponse) princetonESIPConnector.cancelHold(itemIdentifier, patronIdentifier, institutionId, expirationDate, bibId, pickupLocation, null);
holdResponse = (ItemHoldResponse) princetonESIPConnector.placeHold(itemIdentifier, patronIdentifier, institutionId, itemInstitutionId, expirationDate, bibId, pickupLocation, null, null, null, null);
assertNotNull(holdResponse);
assertTrue(holdResponse.isSuccess());
}
@Test
public void createBib() throws Exception {
String itemIdentifier = " CU69277435";
String patronIdentifier = "45678915";
String titleIdentifier = "";
String institutionId = "htccul";
Mockito.when(princetonESIPConnector.createBib(itemIdentifier, patronIdentifier, institutionId, titleIdentifier)).thenReturn(getItemCreateBibResponse());
ItemCreateBibResponse itemCreateBibResponse = princetonESIPConnector.createBib(itemIdentifier, patronIdentifier, institutionId, titleIdentifier);
assertNotNull(itemCreateBibResponse);
assertTrue(itemCreateBibResponse.isSuccess());
}
@Test
public void testRecall() throws Exception {
String itemIdentifier = "32101065514414";
String patronIdentifier = "45678912";
String institutionId = "htccul";
String expirationDate = MessageUtil.createFutureDate(20, 2);
String pickupLocation = "htcsc";
String bibId = "9959082";
Mockito.when(princetonESIPConnector.recallItem(itemIdentifier, patronIdentifier, institutionId, expirationDate, bibId, pickupLocation)).thenReturn(getItemRecallResponse());
ItemRecallResponse itemRecallResponse = princetonESIPConnector.recallItem(itemIdentifier, patronIdentifier, institutionId, expirationDate, bibId, pickupLocation);
assertNotNull(itemRecallResponse);
assertTrue(itemRecallResponse.isSuccess());
}
public ItemRecallResponse getItemRecallResponse() {
ItemRecallResponse itemRecallResponse = new ItemRecallResponse();
itemRecallResponse.setSuccess(true);
return itemRecallResponse;
}
public ItemHoldResponse getItemHoldResponse() {
ItemHoldResponse itemHoldResponse = new ItemHoldResponse();
itemHoldResponse.setSuccess(true);
return itemHoldResponse;
}
public ItemCreateBibResponse getItemCreateBibResponse() {
ItemCreateBibResponse itemCreateBibResponse = new ItemCreateBibResponse();
itemCreateBibResponse.setBibId("123");
itemCreateBibResponse.setItemId("1234");
itemCreateBibResponse.setScreenMessage("");
itemCreateBibResponse.setSuccess(true);
return itemCreateBibResponse;
}
public ItemCheckoutResponse getItemCheckoutResponse() {
ItemCheckoutResponse itemCheckoutResponse = new ItemCheckoutResponse();
itemCheckoutResponse.setSuccess(true);
return itemCheckoutResponse;
}
public ItemCheckinResponse getItemCheckinResponse() {
ItemCheckinResponse itemCheckinResponse = new ItemCheckinResponse();
itemCheckinResponse.setSuccess(true);
return itemCheckinResponse;
}
public ItemInformationResponse getItemInformationResponse() {
ItemInformationResponse itemInformationResponse = new ItemInformationResponse();
itemInformationResponse.setCirculationStatus("test");
itemInformationResponse.setSecurityMarker("test");
itemInformationResponse.setFeeType("test");
itemInformationResponse.setTransactionDate(new Date().toString());
itemInformationResponse.setHoldQueueLength("10");
itemInformationResponse.setTitleIdentifier("test");
itemInformationResponse.setBibID("1223");
itemInformationResponse.setDueDate(new Date().toString());
itemInformationResponse.setExpirationDate(new Date().toString());
itemInformationResponse.setRecallDate(new Date().toString());
itemInformationResponse.setCurrentLocation("test");
itemInformationResponse.setHoldPickupDate(new Date().toString());
itemInformationResponse.setItemBarcode("32101077423406");
return itemInformationResponse;
}
}
| true |
f1c9e1b99ba9224ac031e01ee7f353eb8ff01792
|
Java
|
stanovov/job4j_design
|
/src/main/java/ru/job4j/design/menu/ActionSelect.java
|
UTF-8
| 458 | 3.03125 | 3 |
[] |
no_license
|
package ru.job4j.design.menu;
import java.util.Scanner;
public class ActionSelect implements UserAction {
@Override
public String getName() {
return "Select";
}
@Override
public boolean action(Toolbox toolbox, Scanner scanner) {
Item item = toolbox.getMapItems().get(toolbox.getCurrentNumber());
System.out.printf("You selected: \"%s\"%n", item.getName());
return item.action(toolbox, scanner);
}
}
| true |
bcd9b8d2929b39a13c9eba3490b4bc6d3bbf7f42
|
Java
|
PriyavratSharma/OnlineMovieTicket
|
/OnlineMovieTicket/src/main/java/com/cg/gla/fs/repository/TheaterRepository.java
|
UTF-8
| 406 | 1.984375 | 2 |
[] |
no_license
|
package com.cg.gla.fs.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.cg.gla.fs.model.Theater;
@Repository
public interface TheaterRepository extends CrudRepository<Theater,String> {
Theater findByTheaterId(int theaterId);
Theater findByTheaterNameAndTheaterCity(String theaterName,String theaterCity);
}
| true |
2a1861649c0138917ff6e73e686f97a8e315b489
|
Java
|
akashanjana08/RxJava-Practice
|
/operator/CreateOperator.java
|
UTF-8
| 1,432 | 2.984375 | 3 |
[] |
no_license
|
package operator;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
public class CreateOperator {
public static void main(String[] args) {
Observable<Integer> observableData = Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(ObservableEmitter<Integer> observable) throws Exception {
// TODO Auto-generated method stub
new Thread(){
public void run() {
int j=0;
try{
for(int i=0 ; i<40 ;i++){
j=i;
//Thread.sleep(40);
}
}finally{
observable.onNext(j);
observable.onComplete();
}
};
}.start();
}
});
observableData.subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
// TODO Auto-generated method stub
System.out.println("subscribe");
}
@Override
public void onNext(Object t) {
// TODO Auto-generated method stub
System.out.println(t);
}
@Override
public void onError(Throwable e) {
// TODO Auto-generated method stub
System.out.println("onError");
}
@Override
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("onComplete");
}
});
System.out.println("Please wait....");
}
}
| true |
bfbc69c3f5ad6d11f9ec9c7074b0ed2b37260323
|
Java
|
a84302486/java004_NO1
|
/src/_02_TasteHibernate/TasteMainTest.java
|
UTF-8
| 240 | 2.125 | 2 |
[] |
no_license
|
package _02_TasteHibernate;
public class TasteMainTest {
public static void main(String[] args) {
TasteHibernateDAO dao = new TasteHibernateDAO();
TasteBean tbInsert = new TasteBean( "002" , "辣味");
dao.insert(tbInsert);
}
}
| true |
fc8c4d8a30293b1050ed103eae67d4333a0c4bc3
|
Java
|
futuristixa/Fireworks-1
|
/FloatP.java
|
UTF-8
| 738 | 3.09375 | 3 |
[] |
no_license
|
// ----------------------------------------------------------
// Program Name: FloatP.java
// Course: CS1302 T-R NIGHT
// Student Name: David Rodgers
// Assignment Number: Project 6
// Due Date: November 29, 2007
// Location: Southern Polytechnic State University
// ----------------------------------------------------------
// DEFINES A COORDINATE SYSTEM
// ----------------------------------------------------------
package fireworks;
public class FloatP
{
public float x, y;
public FloatP()
{
x = 0;
y = 0;
}
public FloatP(float x, float y)
{
this.x = x;
this.y = y;
}
public void addVelocity(FloatP p)
{
x += p.x;
y += p.y;
}
public int getX() { return (int)x; }
public int getY() { return (int)y; }
}
| true |
22bed7324836465601135a03c9d1523cd71166a2
|
Java
|
CodeBeanBean/doudou-meeting
|
/doudou-weixin/src/main/java/com/doudou/project/meeting/oauth/WeixinOauth.java
|
UTF-8
| 7,311 | 2.09375 | 2 |
[] |
no_license
|
package com.doudou.project.meeting.oauth;
import com.doudou.po.User;
import com.doudou.po.WeiUser;
import com.doudou.project.weixin.main.MenuManager;
import com.doudou.project.weixin.util.WeixinUtil;
import com.doudou.service.UserService;
import com.doudou.service.WeiUserService;
import net.sf.json.JSONObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* @Description:
* @Company:
* @Author: 窦刘柱
* @Date:2019/11/27
* @Time:20:09
*/
@RequestMapping("oauth")
@Controller
@MapperScan(basePackages = {"com.doudou.mapper"})
public class WeixinOauth {
@Autowired
private WeiUserService weiUserService;
@Autowired
private UserService userService;
/**
* 微信个人中心菜单按钮
*
* @param response
* @throws IOException
*/
@RequestMapping("weixin/user")
public void oauth(HttpServletResponse response) throws IOException {
//授权后重定向的回调连接地址,使用uirEncode对链接进行处理
String redirect_url = MenuManager.REAL_URL + "oauth/weixin/user/invoke";
try {
redirect_url = URLEncoder.encode(redirect_url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//1.用户同意授权。获取code
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" + MenuManager.appId +
"&redirect_uri=" + redirect_url +
"&response_type=code" +
"&scope=snsapi_userinfo" + //静默授权
"&state=doudou" +
"#wechat_redirect";//只能在微信中打开
//如果提示无法访问则 检查参数错误 scope 对应授权权限
response.sendRedirect(url);
}
@RequestMapping("weixin/user/invoke")
public String invoke(HttpServletRequest request) {
//第二步 得到code
String code = request.getParameter("code");
System.out.println("得到code" + code);
request.getParameter("state");
//获取code后,请求以下链接获取access_token:
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" + MenuManager.appId +
"&secret=" + MenuManager.appSecret +
"&code=" + code +
"&grant_type=authorization_code";
//发送请求
JSONObject jsonObject = WeixinUtil.httpRequest(url, "GET", null);
System.out.println("json" + jsonObject.toString());
//得到accesstoken
String access_token = jsonObject.getString("access_token");
//得到openid
String openid = jsonObject.getString("openid");
/**
* 用户时候进行绑定
* 1根据openid 查询weiuser类 得到逐渐ID
* 2根据wid去查询weiuser表
*
*/
WeiUser weiUser = weiUserService.selectByOpenid(openid);
if (weiUser == null) {
//微信的个人信息不存在我的库中
//1 提示 重新关注
//2 收集用户信息 存入数据库中
System.out.println("该用户微信个人信息不存在" + openid);
} else {
//判断当前的微信用户是否进行登录(绑定)功能
User user = userService.selectByWid(weiUser.getId());
if (user == null) { //未绑定 跳到登陆页面
request.setAttribute("wid", weiUser.getId());
return "weixin/login";//templates/***.html
} else {
request.setAttribute("user", user);
return "weixin/user/userInfo";
}
}
return "oauth";
}
/**
* 微信 会议 ---》会议发布
*/
@RequestMapping("weixin/meetingPub") //oauth/weixin/meetingPub
public void oauthMeetingPub(HttpServletResponse response) throws IOException {
//授权后重定向的回调连接地址,使用uirEncode对链接进行处理
String redirect_url = MenuManager.REAL_URL + "oauth/weixin/meetingPub/invoke";
try {
redirect_url = URLEncoder.encode(redirect_url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//1.用户同意授权。获取code
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" + MenuManager.appId +
"&redirect_uri=" + redirect_url +
"&response_type=code" +
"&scope=snsapi_userinfo" +
"&state=doudou" +
"#wechat_redirect";//只能在微信中打开
//如果提示无法访问则 检查参数错误 scope 对应授权权限
response.sendRedirect(url);
}
@RequestMapping("weixin/meetingPub/invoke") // oauth/weixin/meetingPub/invoke
public String meetingPubinvoke(HttpServletRequest request) {
//第二步 得到code
String code = request.getParameter("code");
System.out.println("得到code" + code);
request.getParameter("state");
//获取code后,请求以下链接获取access_token:
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" + MenuManager.appId +
"&secret=" + MenuManager.appSecret +
"&code=" + code +
"&grant_type=authorization_code";
//发送请求
JSONObject jsonObject = WeixinUtil.httpRequest(url, "GET", null);
//得到openid
String openid = jsonObject.getString("openid");
/**
* 1、通过openid 得到主键id weiuser
* 2、通过wid查询user对象user.getRid
*/
WeiUser weiUser = weiUserService.selectByOpenid(openid); //1、通过openid 得到主键id weiuser
if (weiUser == null) {
//1.数据库weiuser表中没有你的微信个人信息--》重新收集个人数据提示/提示:网络异常 重新关注公众号
return "";
} else {
// * 2、通过wid查询user对象user.getRid
User user = userService.selectByWid(weiUser.getId());
if (user == null) { //2、未进行绑定的过程 跳到登陆页面
request.setAttribute("wid", weiUser.getId());
return "weixin/login";//templates/***.html
} else {//已绑定判断角色是发单组还是抢单组
if (1 == user.getRid()) {//发单组 跳到发单组页面
request.setAttribute("uid",user.getId());
return "weixin/meetingPub/meetingPub";
} else if (2 == user.getRid()) {//抢单组--》无权限页面
return "weixin/unauth";
} else {//查看组
return "";//其他情况
}
}
}
}
}
| true |
e86e2a6d2f38bb2a6c341059cd5becc38ea71d97
|
Java
|
JustDoItHilary/HilarysTraining
|
/weexdemo/src/main/java/com/example/weexdemo/weex/MyIWebView.java
|
UTF-8
| 885 | 2.046875 | 2 |
[] |
no_license
|
package com.example.weexdemo.weex;
import android.view.View;
/**
* Created by Hilary
* on 2016/12/30.
*/
public interface MyIWebView{
public View getView();
public void destroy();
public void loadUrl(String url);
public void reload();
public void goBack();
public void goForward();
public void setShowLoading(boolean shown);
public void setOnErrorListener(MyIWebView.OnErrorListener listener);
public void setOnPageListener(MyIWebView.OnPageListener listener);
public interface OnErrorListener {
public void onError(String type, Object message);
}
public interface OnPageListener {
public void onReceivedTitle(String title);
public void onPageStart(String url);
public void onPageFinish(String url, boolean canGoBack, boolean canGoForward);
public void onPageChange(int progress);
}
}
| true |
b87120862190f9b7836a71120b40e42e45ea6de2
|
Java
|
liangmeihuai/webx-demo
|
/biz/src/test/java/com/alibaba/zhu/impl/UserServiceTest.java
|
UTF-8
| 1,800 | 2.109375 | 2 |
[] |
no_license
|
package com.alibaba.zhu.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.zhu.AbstractComponentTest;
import com.alibaba.zhu.domain.User;
import com.alibaba.zhu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static com.alibaba.zhu.utils.ServiceUtils.md5;
/**
* UserServiceTest
*
* @author <a href="mailto:[email protected]">风袭</a>
* @version V1.0.0
* @since 2015-08-27
*/
public class UserServiceTest extends AbstractComponentTest {
@Autowired
private UserService userService;
@Test
public void testGetUserByID() {
User user = userService.getUserByID(2L);
System.out.println(JSON.toJSONString(user));
}
@Test
public void testGetUserByUserName() {
User user = userService.getUserByUserName("zhu");
System.out.println(JSON.toJSONString(user));
}
@Test
public void testInset() throws ParseException {
SimpleDateFormat bartDateFormat =
new SimpleDateFormat("yyyy-MM-dd");
String dateStringToParse = "2001-9-29";
Date date = bartDateFormat.parse(dateStringToParse);
User user = new User();
user.setId(2L);
user.setBirthday(date);
user.setEmail("[email protected]");
user.setNickname("燕子");
user.setUserName("xiaozhu");
user.setPassword(md5("123"));
userService.getUserMapperDao().insert(user);
Assert.assertNotNull(userService.getUserByID(2L));
System.out.println(JSON.toJSONString(userService.getUserByID(1L)));
System.out.println(JSON.toJSONString(userService.getUserByID(2L)));
}
}
| true |
7a58c22cdf7c610a3804dfa8205295ed177b84d9
|
Java
|
code-Smueller-li/Stackexchange-Tag-Extractor
|
/src/li/smueller/code/stackexchange/model/TagWiki.java
|
UTF-8
| 320 | 1.960938 | 2 |
[] |
no_license
|
package li.smueller.code.stackexchange.model;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class TagWiki {
@SerializedName("tag_wikis")
private List<Wiki> wikis = new ArrayList<Wiki>();
public boolean hasWiki() {
return wikis.size() != 0;
}
}
| true |
75cffcb1d8ee5df1307582ef2e6601191775c67e
|
Java
|
s-williams/BusTripMapper
|
/src/main/BusTripMapper.java
|
UTF-8
| 2,651 | 3.15625 | 3 |
[] |
no_license
|
package main;
import main.model.Tap;
import main.model.Trip;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class BusTripMapper {
private final List<Tap> taps;
private final List<Trip> trips;
public BusTripMapper() {
this.taps = new ArrayList<>();
this.trips = new ArrayList<>();
}
/**
* Map the credit card payment taps to a list of bus trips.
* @param taps
* @return the list of bus trips
*/
public List<Trip> mapTrips(List<Tap> taps) {
taps.stream().filter(t -> t.getTapType().equals("ON")).forEach(firstStop -> {
Tap secondStop = getSecondTap(firstStop, taps);
trips.add(createTrip(firstStop, secondStop));
});
return trips;
}
/**
* Get the second stop given the first stop and the list of taps
* @param firstStop
* @param taps
* @return
*/
public Tap getSecondTap(Tap firstStop, List<Tap> taps) {
List<Tap> samePan = taps.stream()
.filter(t -> t.getPan().equals(firstStop.getPan()))
.filter(t -> t.getCompanyId().equals(firstStop.getCompanyId()))
.filter(t -> t.getBusId().equals(firstStop.getBusId()))
.filter(t -> t.getDateTime().after(firstStop.getDateTime()))
.filter(t -> t.getTapType().equals("OFF"))
.collect(Collectors.toList());
if (samePan.size() > 0) {
return samePan.get(0);
} else {
return null;
}
}
/**
* Create a trip from the first stop and second stop
* @param firstStop
* @param secondStop
* @return
*/
public Trip createTrip(Tap firstStop, Tap secondStop) {
Trip trip = new Trip();
trip.setStarted(firstStop.getDateTime());
if (secondStop != null) {
trip.setFinished(secondStop.getDateTime());
trip.setToStopId(secondStop.getStopId());
if (firstStop.getStopId().equals(secondStop.getStopId())) {
trip.setStatus("CANCELLED");
} else {
trip.setStatus("COMPLETE");
}
} else {
trip.setFinished(null);
trip.setToStopId(null);
trip.setStatus("INCOMPLETE");
}
trip.setFromStopId(firstStop.getStopId());
trip.setCompanyId(firstStop.getCompanyId());
trip.setBusId(firstStop.getBusId());
trip.setPan(firstStop.getPan());
trip.setChargeAmount(Utility.calculateCharge(trip.getFromStopId(), trip.getToStopId()));
return trip;
}
}
| true |
2671da29d43a9574be2410ab130093833884b67f
|
Java
|
bhasin11/Algorithms-in-Java
|
/BST/mergeBST.java
|
UTF-8
| 713 | 3.671875 | 4 |
[] |
no_license
|
/*
Given 2 BSTs, merge them. I have altered the original trees here.
*/
public Node mergeTwoBST(Node root1, Node root2){
if(root2!=null){
mergeTwoBST(root1,root2.leftChild);
root2.leftChild=null;
mergeTwoBST(root1,root2.rightChild);
root2.rightChild=null;
root1 = insertAgain(root1,root2);
}
return root1;
}
public Node insertAgain(Node root, Node newNode){
Node current=root;
while(true){
if(current.age>newNode.age){
if(current.leftChild==null){
current.leftChild=newNode;
break;
}
else current=current.leftChild;
}
else{
if(current.rightChild==null){
current.rightChild=newNode;
break;
}
else current=current.rightChild;
}
}
return root;
}
| true |
3bf7e3e418925622a36d427f5128142a0ff00a44
|
Java
|
lijtforgithub/study-mybatis
|
/src/main/java/com/ljt/study/service/APIService.java
|
UTF-8
| 339 | 1.90625 | 2 |
[] |
no_license
|
package com.ljt.study.service;
import java.util.List;
import com.ljt.study.entity.Tag;
import com.ljt.study.entity.User;
/**
* @author LiJingTang
* @version 2015年9月28日 下午8:34:27
*/
public interface APIService {
List<Tag> queryTag(int offset, int limit);
User saveUser(User user);
User findUserById(Integer id);
}
| true |
feffdcf76bdc733fe9177931276312b4107696b4
|
Java
|
sengeiou/project-3
|
/kuaihuo-parent/phshopping-facade-member/src/main/java/com/ph/shopping/facade/member/dto/AdAtachmentDTO.java
|
UTF-8
| 1,145 | 1.976563 | 2 |
[] |
no_license
|
package com.ph.shopping.facade.member.dto;
import com.ph.shopping.common.core.base.BaseValidate;
import java.io.Serializable;
/**
* Created by wudi on 2017/9/1.
*/
public class AdAtachmentDTO extends BaseValidate implements Serializable {
private static final long serialVersionUID = -4747734633757244024L;
/**
* 当前页码
*/
private Integer pageNum;
/**
* 每页条数
*/
private Integer pageSize;
/**
* 轮播图类型
*/
private Integer type;
/**
* 图片name
*/
private String name;
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| true |
4b0d3a3defdc5bf5a11ba38f1d3f68c9b3f13180
|
Java
|
shams01/Space
|
/src/com/company/Enemy1.java
|
UTF-8
| 1,387 | 3.0625 | 3 |
[] |
no_license
|
package com.company;
public class Enemy1 {
public static void moveEnemy1() {
for (int i = 0; i < Main.enemyCount1; ++i) {
Main.xEnemy1[i] = Main.xEnemy1[i] - Main.speedEnemy1[i] - Main.speedPlayer;
//переустановка переменных врага заехавшего далеко за зону видимости
if (Main.xEnemy1[i] <= -3000 || Main.xEnemy1[i] >= 3000) {
Main.xEnemy1[i] = (int) ((Math.random() * 1000) + 1000);
Main.speedEnemy1[i] = (int) (Math.random() * 9 + 3);
}
//проверка съезда с дороги врагов
if (Main.yEnemy1[i] < 45) Main.yEnemy1[i] = 45;
if (Main.yEnemy1[i] > 425) Main.yEnemy1[i] = 425;
//поворот врагов
if (Main.enemyLeft1[i]) Main.yEnemy1[i] -= 4;
if (Main.enemyRight1[i]) Main.yEnemy1[i] += 4;
//повернуть врагов с вероятностью 1 к 10
if ((int) (Math.random() * 10) == 0) tern();
}
}
private static void tern() {
for (int i = 0; i < Main.enemyCount1; ++i) {
if ((int) (Math.random() * 2) == 0)
Main.enemyRight1[i] = !Main.enemyRight1[i];
else
Main.enemyLeft1[i] = !Main.enemyLeft1[i];
}
}
}
| true |
d36f5ab7929a5ec8d5bd12608dd38debc5773081
|
Java
|
luisfelipeas5/GiveMeDetails
|
/view/src/main/java/br/com/luisfelipeas5/givemedetails/view/details/TrailersMvpView.java
|
UTF-8
| 442 | 1.976563 | 2 |
[] |
no_license
|
package br.com.luisfelipeas5.givemedetails.view.details;
import java.util.List;
import br.com.luisfelipeas5.givemedetails.model.model.trailer.Trailer;
import br.com.luisfelipeas5.givemedetails.view.MvpView;
public interface TrailersMvpView extends MvpView {
void setMovieId(String movieId, boolean showPreview);
void onTrailersReady(List<Trailer> trailers);
void onGetTrailersFailed();
void showSeeAllTrailersButton();
}
| true |
01ddf8e6fdb89f83ee5e6c84c3377aa45c7d3223
|
Java
|
friendsGoodBoy/linkShop
|
/admin/src/main/java/com/link/admin/controller/vo/TreeMenu.java
|
UTF-8
| 2,047 | 2.578125 | 3 |
[] |
no_license
|
package com.link.admin.controller.vo;
import com.jfinal.kit.StrKit;
import com.link.model.Menu;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by linkzz on 2017-06-10.
*/
public class TreeMenu extends Menu {
private List<Menu> nodes;
private List<TreeMenu> treeMenus;
private int size = 0;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<TreeMenu> getTreeMenus() {
return treeMenus;
}
public void setTreeMenus(List<TreeMenu> treeMenus) {
this.treeMenus = treeMenus;
}
public TreeMenu(){}
public TreeMenu(List<Menu> nodes){
this.nodes = nodes;
}
public List<TreeMenu> buildTree(){
List<TreeMenu> treeMenus0 = new ArrayList<>();
for (Menu node : nodes) {
if (StrKit.isBlank(node.getParent())) {
TreeMenu treeMenu = new TreeMenu();
BeanUtils.copyProperties(node,treeMenu);
build(node,treeMenu);
treeMenus0.add(treeMenu);
}
}
return treeMenus0;
}
private void build(Menu node,TreeMenu treeMenu){
List<Menu> children = getChildren(node);
if (!children.isEmpty()) {
List<TreeMenu> list = new ArrayList<>();
for (Menu child : children) {
TreeMenu treeMenu1 = new TreeMenu();
BeanUtils.copyProperties(child,treeMenu1);
build(child,treeMenu1);
list.add(treeMenu1);
}
treeMenu.setTreeMenus(list);
treeMenu.setSize(children.size());
}
}
private List<Menu> getChildren(Menu node){
List<Menu> children = new ArrayList<Menu>();
String id = node.getId();
for (Menu child : nodes) {
if (id.equals(child.getParent())) {
children.add(child);
}
}
return children;
}
}
| true |
92b8ffb60e946609d728678f4f253608287519fd
|
Java
|
tianchao62375540/ym-spring
|
/sf/src/main/java/com/atomic/sync/SynchronizedTest2.java
|
UTF-8
| 991 | 2.96875 | 3 |
[] |
no_license
|
package com.atomic.sync;
import java.util.Vector;
/**
* 源码学院-Fox
* 只为培养BAT程序员而生
* http://bat.ke.qq.com
* 往期视频加群:516212256 暗号:6
*/
public class SynchronizedTest2 {
Vector<String> vector = new Vector<String>();
/*
锁的粗化
*/
public void test(){
for(int i = 0 ; i < 10 ; i++){
vector.add(i + "");
}
vector.add("fox");
vector.add("fox111");
vector.add("fox222");
/*synchronized (this){
for
}*/
}
/**
* 锁的消除
*
* -XX:+EliminateLocks 开启同步消除
*/
public void test2(){
// jvm不会加锁 判断不会存在竞争,同步消除
synchronized (new Object()){
//TODO 业务逻辑
Vector<String> vector = new Vector<String>();
vector.add("fox");
vector.add("fox111");
vector.add("fox222");
}
}
}
| true |
2ea519b30077d4c49378095223dcb428622c8a78
|
Java
|
Nickster258/PRom
|
/src/main/java/org/stonecipher/event/InteractEvent.java
|
UTF-8
| 2,127 | 2.65625 | 3 |
[] |
no_license
|
package org.stonecipher.event;
import org.bukkit.block.Block;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.stonecipher.PRom;
import org.stonecipher.editor.RomBuilder;
import org.stonecipher.entity.Input;
import org.stonecipher.entity.Output;
public class InteractEvent implements Listener {
public void onBreak(PlayerInteractEvent playerInteractEvent) {
RomBuilder builder = PRom.builders.stream()
.filter(romBuilder -> romBuilder.getPlayer().equals(playerInteractEvent.getPlayer()))
.findFirst().get();
// Check if the builder exists, the action was a left click, and the previous action was confirmed
if ((builder == null) || (playerInteractEvent.getAction().equals(Action.LEFT_CLICK_BLOCK)) || (!builder.getConfirmedState())) {
return;
}
Block clickedBlock = playerInteractEvent.getClickedBlock();
Block selectedBlock = clickedBlock.getRelative(playerInteractEvent.getBlockFace());
if (builder.getConfirmedState()) {
if (builder.isBuildingInputs()) {
builder.getRom().addInput(new Input(selectedBlock.getLocation(), builder.getInputCount()));
builder.incrementInputCount();
} else {
builder.getRom().addOutput(new Output(selectedBlock.getLocation(), builder.getOutputCount()));
builder.incrementOutputCount();
}
} else {
if (builder.isBuildingInputs()) {
builder.getRom().addInput(new Input(selectedBlock.getLocation(), builder.getInputCount()-1));
builder.incrementInputCount();
} else {
builder.getRom().addOutput(new Output(selectedBlock.getLocation(), builder.getOutputCount()-1));
builder.incrementOutputCount();
}
}
if (builder.getInputCount() == builder.getRom().getAddressable()) {
builder.setBuildingInputs(false);
}
builder.setConfirmedState(false);
}
}
| true |
16e237a07ec5d955b33639dde787cf6f93abac49
|
Java
|
vladimirtarasenko/byitacademyfinal
|
/src/main/java/PatientsSearhedByDate.java
|
UTF-8
| 501 | 2.65625 | 3 |
[] |
no_license
|
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.util.Scanner;
public class PatientsSearhedByDate implements PatientsSorting {
@Override
public void sortPatients() throws IOException, XMLStreamException {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the date");
String date = scanner.nextLine();
GetPatients patients = new GetPatients();
patients.execute().birthdaySearch(date);
}
}
| true |