text stringlengths 10 2.72M |
|---|
package com.example.jwtdemo2.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.example.jwtdemo2.models.ERole;
import com.example.jwtdemo2.models.Role;
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(ERole name);
boolean existsByName(ERole e);
}
|
package ru.lanit.at;
import io.appium.java_client.remote.MobileCapabilityType;
import org.openqa.grid.internal.utils.CapabilityMatcher;
import org.openqa.selenium.remote.CapabilityType;
import ru.lanit.at.validation.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.openqa.selenium.remote.CapabilityType.BROWSER_NAME;
public class CustomCapabilitiesMatcher implements CapabilityMatcher {
private final List<Validator> validators = new ArrayList<>();
{
validators.addAll(Arrays.asList(
new AliasedPropertyValidator(BROWSER_NAME, "browser"),
new VersionValidator(CapabilityType.BROWSER_VERSION),
new PlatformValidator(),
new VersionValidator(CapabilityType.VERSION),
new VersionValidator(MobileCapabilityType.PLATFORM_VERSION),
new SimplePropertyValidator(CapabilityType.APPLICATION_NAME),
new AppiumPropertyValidator(MobileCapabilityType.UDID),
new AppiumPropertyValidator(MobileCapabilityType.DEVICE_NAME)
));
}
@Override
public boolean matches(Map<String, Object> providedCapabilities, Map<String, Object> requestedCapabilities) {
return providedCapabilities != null && requestedCapabilities != null
&& validators.stream().allMatch(v -> v.apply(providedCapabilities, requestedCapabilities));
}
}
|
package chat.Client.gui;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ChatWindow extends JFrame {
private final JButton sendButton;
private final JTextField messageField;
private final JTextPane logPane;
private final Document logDocument;
private Listener listener;
public interface Listener {
void sendChatMessage(String message);
}
public ChatWindow() {
setTitle("Chat");
setSize(700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sendButton = new JButton("send");
messageField = new JTextField();
logPane = new JTextPane();
logPane.setPreferredSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(logPane);
logPane.setEditable(false);
JScrollPane scroll = new JScrollPane(logPane);
add(scroll);
JPanel messagePanel = new JPanel();
messagePanel.setLayout(new BoxLayout(messagePanel, BoxLayout.X_AXIS));
messagePanel.add(messageField);
messagePanel.add(sendButton);
add(messagePanel);
logDocument = logPane.getDocument();
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sendMessage();
}
});
messageField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sendMessage();
}
});
setVisible(true);
}
public void setListener(Listener listener) {
this.listener = listener;
}
public void displayIncomingMessage(String message) {
displayMessage(message);
}
private void sendMessage() {
String message = messageField.getText();
messageField.setText("");
listener.sendChatMessage(message);
}
private void displayMessage(String message) {
try {
logDocument.insertString(logDocument.getLength(), message + "\n", null);}
catch (BadLocationException x) {
System.out.println(x.getMessage());
}
}
}
|
package com.flowedu.domain;
import lombok.Data;
/**
* Created by jihoan on 2017. 10. 18..
*/
@Data
public class RequestApi {
private String body;
private int httpStatusCode;
public RequestApi(String body, int httpStatusCode) {
this.body = body;
this.httpStatusCode = httpStatusCode;
}
}
|
package egovframework.usr.stu.std.controller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ziaan.lcms.EduStartBean;
import egovframework.adm.exm.service.ExamAdmService;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.usr.stu.std.service.StudyExamService;
import egovframework.usr.stu.std.service.StudyManageService;
@Controller
public class StudyExamController {
/** log */
protected static final Log log = LogFactory.getLog(StudyExamController.class);
/** EgovMessageSource */
@Resource(name = "egovMessageSource")
EgovMessageSource egovMessageSource;
/** studyExamService */
@Resource(name = "studyExamService")
StudyExamService studyExamService;
/** studyManageService */
@Resource(name = "studyManageService")
private StudyManageService studyManageService;
/** examAdmService */
@Resource(name = "examAdmService")
private ExamAdmService examAdmService;
@RequestMapping(value="/usr/stu/std/userStudyExamList.do")
public String listPage(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
setSummaryInfo(commandMap, model);
//์ํ
List exam_list = studyManageService.selectExamList(commandMap);
model.addAttribute("exam_list", exam_list);
model.addAllAttributes(commandMap);
return "usr/stu/std/userStudyExamList";
}
@RequestMapping(value="/usr/stu/std/userStudyCheckDuplicateIP.do")
public String checkDuplicateIP(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception {
Date date = new Date();
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdformat = new SimpleDateFormat("yyyyMMddHHmmss");
cal.setTime(date);
cal.add(Calendar.HOUR, -1);
String user_now = sdformat.format(cal.getTime());
commandMap.put("user_ip", request.getRemoteAddr());
commandMap.put("user_now", user_now);
Integer rtn = studyManageService.checkDuplicateIP(commandMap);
model.addAttribute("rtn", rtn);
return "usr/stu/std/userStudyCheckDuplicateIP";
}
@RequestMapping(value="/usr/stu/std/userStudyExamAnswerPage.do")
public String detailPage(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
String v_subj = (String)commandMap.get("p_subj");
String v_year = (String)commandMap.get("p_year");
String v_subjseq = (String)commandMap.get("p_subjseq");
String p_exam_subj = commandMap.get("p_exam_subj") != null ? (String)commandMap.get("p_exam_subj") : "";
System.out.println("v_subj ----> "+v_subj);
System.out.println("v_year ----> "+v_year);
System.out.println("v_subjseq ----> "+v_subjseq);
System.out.println("p_exam_subj ----> "+p_exam_subj);
//๋ณด๋๋ฌธ์
String ingExam = "N";
//์ถ๊ฐ์ํ
String retryExamChangeYn ="N";
//๋ฌธ์ ๋ฌธํ ๋ณ๊ฒฝ
String examBankchangeYn = "N";
if(p_exam_subj.length() > 0){
examBankchangeYn = "Y";
}
/*if(("PRF150001".equals(v_subj) && "2015".equals(v_year) && "0003".equals(v_subjseq)) || ("PRF150017".equals(v_subj) && "2015".equals(v_year) && "0001".equals(v_subjseq))){
examBankchangeYn = "Y";
}*/
System.out.println("examBankchangeYn ----> "+examBankchangeYn);
commandMap.put("examBankchangeYn", examBankchangeYn);
String ses_search_subj = commandMap.get("p_subj").toString();
String ses_search_year = commandMap.get("p_year").toString();
String ses_search_subjseq = commandMap.get("p_subjseq").toString();
String p_lesson = "001";
commandMap.put("ses_search_subj", ses_search_subj);
commandMap.put("ses_search_year", ses_search_year);
commandMap.put("ses_search_subjseq", ses_search_subjseq);
commandMap.put("p_lesson", p_lesson);
String examtabletemp = "temp"; //2์ฐจ์์ ํ
์ด๋ธ๋ช
์ถ๊ฐ ๋ฌธ์(tz_examresulttemp)
setSummaryInfo(commandMap, model);
/**
* 1ํ์์ ์ฌ๋ถ์ฒดํฌ
*/
int exam_1 = studyExamService.getExamResultChk(commandMap);
commandMap.put("examCnt", exam_1);
/**
* 1์ฐจ์์๋ฅผ ํ์๋ค๋ฉด
* 2ํ์์ ์ฌ๋ถ์ฒดํฌ๋ฅผ ์ฒดํฌํ๋ค.
*/
/*if(exam_1 > 0) {
commandMap.put("examtabletemp", examtabletemp);
int exam_2 = studyExamService.getExamResultChk(commandMap);
if(exam_2 > 0) //2์ฐจ์์๋ ์๋ฃ๋ ์ํ
{
commandMap.remove("examtabletemp");
}
else
{
// 2์ฐจ์์๊ฐ ๊ฐ๋ฅํ ์ํ
}
}*/
List list = null;
String resultMsg = "";
if(exam_1 > 0) {
//1์ฐจ ์ํ ์๋ฃ?
String resultSubmit_1 = studyExamService.selectExamResultSubmit(commandMap);
if(resultSubmit_1.equals("Y")){
commandMap.put("examtabletemp", examtabletemp);
//2์ฐจ์ํ์ ๋ณธ์ ์ด ์๋๊ฐ?
int exam_2 = studyExamService.getExamResultChk(commandMap);
//2์ฐจ์ํ์ ์๋ฃ ํ๋๊ฐ?
String resultSubmit_2 = studyExamService.selectExamResultSubmit(commandMap);
resultSubmit_2 = resultSubmit_2 !=null ? resultSubmit_2.toString() : "N";
//2์ฐจ์ํ์ ๋ณธ์ ์ด ์์ผ๋ฉด
if(exam_2>0){
//2์ฐจ์ํ ์๋ฃ?
if(resultSubmit_2.equals("Y")){
// ์ถ๊ฐ์ํ ๊ฐ๋ฅ ์ฌ๋ถ ์ฒดํฌ (๊ด๋ฆฌ์์์ ์ฌ์ฉ์ ์์ํ์ (์ฌ์์์
))
commandMap.remove("examtabletemp");
retryExamChangeYn = studyExamService.getRetryExamChangeYn(commandMap); //userretry > 0 and submit_yn = 'Y'
retryExamChangeYn = retryExamChangeYn !=null ? retryExamChangeYn.toString() : "N";
if("Y".equals(retryExamChangeYn)){
ingExam = "R"; //RETRY์ถ๊ฐ๋ก ๋ณผ ๋
//๋ฌธ์
list = studyExamService.selectPaperQuestionExampleList(commandMap);
model.addAttribute("PaperQuestionExampleList", list);
String tmp = "";
String p_answer = "";
for(int i = 0; i < list.size(); i++ ){
Map m2 = (Map)list.get(i);
if(!tmp.equals(m2.get("examnum").toString()) ){
tmp = m2.get("examnum").toString();
p_answer += "0,";
System.out.println("p_answer 1111 ----> "+p_answer);
}
}
p_answer = p_answer.substring(0, p_answer.length() - 1);
System.out.println("p_answer 2222 ----> "+p_answer);
System.out.println("ingExam 2222 ----> "+p_answer);
commandMap.put("p_answer", p_answer);
studyExamService.updateRetryExamChange(commandMap);
}
}else{
ingExam = "Y";
}
}
}else{
ingExam = "Y";
}
//๋ณด๋ ๋ฌธ์
if(ingExam.equals("Y")){
Map<String, Object> examResultInfo = studyExamService.getExamResultInfo(commandMap);
Map<String, Object> paramMap = new HashMap<String, Object>();
List<Object> examList = new ArrayList<Object>();
int examIdx = 0;
String[] myAnswerArr = String.valueOf(examResultInfo.get("answer")).split(",");
for(String examnum: String.valueOf(examResultInfo.get("exam")).split(",")) {
Map<String, Object> examMap = new HashMap<String, Object>();
examMap.put("examnum", examnum);
examMap.put("rn", examIdx + 1);
examMap.put("myAnswer", myAnswerArr[examIdx]);
examList.add(examMap);
examIdx ++;
}
paramMap.put("examList", examList);
paramMap.put("examsubj", p_exam_subj);
list = studyExamService.getExamInProgress(paramMap);
model.addAttribute("PaperQuestionExampleList", list);
}
//๋ณด๋๋ฌธ์ end
}
System.out.println("ingExam ----> "+ingExam);
//์ฒ์์ํ
if(ingExam.equals("N")){
list = studyExamService.selectPaperQuestionExampleList(commandMap);
model.addAttribute("PaperQuestionExampleList", list);
}
if(list == null || list.size() == 0) {
resultMsg = "์ด๋ฏธ ํ๊ฐ๊ฐ ์๋ฃ๋์์ต๋๋ค.";
}// ํ๊ฐ ๊ธฐ๊ฐ๋ด์ ์๋์ง ํ์ธ ํ ๊ฒ
else if (list.size() > 0) {
commandMap.put("p_subjsel", commandMap.get("p_subj") );
commandMap.put("p_upperclass","ALL");
Map data = studyExamService.getPaperData(commandMap); // ๋ฌธ์ ์ง ์ค๋ช
์ ๋ณด
if ("N".equals(data.get("chck"))) {
resultMsg = "์ด๋ฏธ ํ๊ฐ๊ธฐ๊ฐ์ด ์ง๋ฌ์ต๋๋ค.";
} else {
model.addAttribute("ExamPaperData", data);
commandMap.remove("p_subjsel");
String v_exam = "";
String tmp = "";
for(int i = 0; i < list.size(); i++ ){
Map m2 = (Map)list.get(i);
if( !tmp.equals(m2.get("examnum").toString()) ){
v_exam += m2.get("examnum")+",";
tmp = m2.get("examnum").toString();
}
}
commandMap.put("p_exam", v_exam);
// ์ด์ ์ ์์ํ ํ๊ฐ๊ฒฐ๊ณผ๊ฐ์ด ์กด์ฌํ๋ฉด ํด๋น ๊ฒฐ๊ณผ์ ์์ ์๊ฐ์ ๊ฐ์ ธ์จ๋ค.
Map dataMap = studyExamService.selectStartTime(commandMap);
commandMap.put("extra_time", dataMap.get("extratime"));
commandMap.put("started", dataMap.get("started"));
commandMap.put("answer", dataMap.get("answer"));
commandMap.put("dataMap", dataMap);
int isOk = studyExamService.InsertResult(commandMap);
}
}
model.addAllAttributes(commandMap);
return "usr/stu/std/userStudyExamAnswerPage";
}
@RequestMapping(value="/usr/stu/std/userStudyExamAnswerFinish.do")
public String insertData(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
int isOk = 0;
String resultMsg = "";
if(null != request.getSession().getAttribute("userid")) {
String v_subj = (String)commandMap.get("p_subj");
String v_year = (String)commandMap.get("p_year");
String v_subjseq = (String)commandMap.get("p_subjseq");
String p_exam_subj = commandMap.get("p_exam_subj") != null ? (String)commandMap.get("p_exam_subj") : "";
System.out.println("v_subj ----> "+v_subj);
System.out.println("v_year ----> "+v_year);
System.out.println("v_subjseq ----> "+v_subjseq);
//๋ฌธ์ ๋ฌธํ ๋ณ๊ฒฝ
String examBankchangeYn = "N";
if(p_exam_subj.length() > 0){
examBankchangeYn = "Y";
}
/*if(("PRF150001".equals(v_subj) && "2015".equals(v_year) && "0003".equals(v_subjseq)) || ("PRF150017".equals(v_subj) && "2015".equals(v_year) && "0001".equals(v_subjseq))){
examBankchangeYn = "Y";
}*/
System.out.println("examBankchangeYn ----> "+examBankchangeYn);
commandMap.put("examBankchangeYn", examBankchangeYn);
commandMap.put("submitYn", "Y");
isOk = studyExamService.InsertResult(commandMap);
isOk = studyExamService.insertExamAnswerFinish(commandMap);
}
if( isOk > 0 ){
resultMsg = "์ ์ถ๋์์ต๋๋ค.";
}else{
resultMsg = "์ ์ถ์ ์คํจํ์์ต๋๋ค.";
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "forward:/usr/stu/std/userStudyExamList.do";
}
/**
* ์ฌ์ฉ์๊ฐ ์ ์ถํ ํ๊ฐ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/usr/stu/std/userStudyExamAnswerView.do")
public String userStudyExamAnswerView(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception {
//๋งต๋ค์ ์ฒ๋ฆฌํ๊ธฐ
commandMap.put("ses_search_subj", commandMap.get("p_subj"));
commandMap.put("ses_search_gyear", commandMap.get("p_gyear"));
commandMap.put("ses_search_subjseq", commandMap.get("p_subjseq"));
commandMap.put("search_papernum", commandMap.get("p_papernum"));
//์ ์ฒด ํ๊ท
model.addAttribute("view", examAdmService.selectExamResultAvg(commandMap));
//์ ์ฒด ๋ฌธ์ ์ ๋ณด
List paperList = examAdmService.selectUserPaperResultList(commandMap);
model.addAttribute("paperList", paperList);
//์ ์ฒด ๋ต์์ ๋ณด - ํ์ต์
Map userExamView = examAdmService.selectUserExamResultList(commandMap);
model.addAttribute("userExamView", userExamView);
//์ ์ฒด๋ฌธ์ ๋ต์์ ๋ณด - ํ์ด์ ๋ณด์ฌ์ฃผ๊ธฐ
List examList = examAdmService.selectUserExamResultAnswerList(userExamView);
model.addAttribute("examList", examList);
//๋งต ์ญ์
commandMap.remove("ses_search_subj");
commandMap.remove("ses_search_gyear");
commandMap.remove("ses_search_subjseq");
commandMap.remove("search_papernum");
model.addAllAttributes(commandMap);
return "usr/stu/std/userStudyExamAnswerView";
}
@RequestMapping(value="/usr/stu/std/popupExamAgree.do")
public String popupExamAgree(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception {
model.addAllAttributes(commandMap);
return "usr/stu/std/popupExamAgree";
}
public void setSummaryInfo(Map<String, Object> commandMap, ModelMap model) throws Exception{
if( commandMap.get("studyPopup") == null || commandMap.get("studyPopup").toString().equals("") ){
// ๋์ ์ง๋์จ, ๊ถ์ฅ ์ง๋์จ
double progress = Double.parseDouble(studyManageService.getProgress(commandMap));
double promotion = Double.parseDouble(studyManageService.getPromotion(commandMap));
model.addAttribute("progress", String.valueOf(progress));
model.addAttribute("promotion", String.valueOf(promotion));
// ํ์ต์ ๋ณด
EduStartBean bean = EduStartBean.getInstance();
List dataTime = studyManageService.SelectEduTimeCountOBC(commandMap); // ํ์ต์๊ฐ,์ต๊ทผํ์ต์ผ,๊ฐ์์ ๊ทผํ์
model.addAttribute("EduTime", dataTime);
Map data2 = studyManageService.SelectEduScore(commandMap);
model.addAttribute("EduScore", data2);
// ๊ฐ์ฌ์ ๋ณด
Map tutorInfo = studyManageService.getTutorInfo(commandMap);
model.addAttribute("tutorInfo", tutorInfo);
commandMap.put("p_grcode","N000001");
commandMap.put("p_class","1");
List list = studyManageService.selectListOrderPerson(commandMap);
model.addAttribute("ReportInfo", list);
// ์ด์ฐจ์, ํ์ตํ ์ฐจ์, ์ง๋์จ, ๊ณผ์ ๊ตฌ๋ถ
Map map = studyManageService.getStudyChasi(commandMap);
model.addAttribute("datecnt", map.get("datecnt")); // ์ด์ฐจ์
model.addAttribute("edudatecnt", map.get("edudatecnt")); // ํ์ตํ ์ฐจ์
model.addAttribute("wstep", map.get("wstep")); // ์ง๋์จ
model.addAttribute("attendCnt", map.get("attendCnt")); // ์ถ์๊ฐ์
}
}
}
|
package com.hdb.web;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.taglibs.standard.extra.spath.RelativePath;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import com.hdb.web.dto.User;
/**
*
* @author HDB
*
*/
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.hdb.web" })
public class WebConfig extends WebMvcConfigurationSupport {
@Bean
public InternalResourceViewResolver resolver() {
System.out.println("calling InternalResourceViewResolver");
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Bean
public MessageSource messageSource() {
System.out.println("calling MessageSource");
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("messages");
return source;
}
@Bean
public LocalSessionFactoryBean factory() {
System.out.println("calling LSFB");
LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
/*
* <bean id="sessionFactory"
* class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property
* name="configLocations" value="hibernate.cfg.xml"></property> </bean>
*/
// Resource resource = new PathResource("E:\\Java Jars\\Framework\\hibernate.cfg.xml");
Resource resource=new ClassPathResource("hibernate.cfg.xml");
bean.setConfigLocations(resource);
/* Properties properties = new Properties();
properties.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/universal");
properties.setProperty("hibernate.connection.username", "root");
properties.setProperty("hibernate.connection.password", "");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
properties.setProperty("show_sql", "true");
properties.setProperty("hbm2ddl.auto", "update");
bean.setAnnotatedClasses(User.class);
bean.setAnnotatedClasses(languages.class);
bean.setHibernateProperties(properties);
*/
return bean;
}
/* @Bean
public AbstractEntityManagerFactoryBean entityManagerFactory() {
DriverManagerDataSource dataSource=new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/universal");
dataSource.setUsername("hdb");
dataSource.setPassword("");
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource);
entityManagerFactory.setPackagesToScan("com.hdb.web");
entityManagerFactory.setPersistenceProvider(new HibernatePersistenceProvider());
entityManagerFactory.getJpaPropertyMap().put("hibernate.hbm2ddl.auto", "validate");
entityManagerFactory.get
return entityManagerFactory;
}
*/
} |
package com.microservice.apigateway.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Configuration
public class CustomPreFilter implements GlobalFilter {
Logger logger = LoggerFactory.getLogger(CustomPreFilter.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest serverHttpRequest = exchange.getRequest() ;
return chain.filter(exchange).then(
// whatever we write inside then, its the post filter.
Mono.fromRunnable(() -> {
ServerHttpResponse serverHttpResponse = exchange.getResponse() ;
logger.info("Post filter: "+serverHttpResponse.getStatusCode()) ;
})) ;
}
}
|
import org.apache.log4j.Logger;
import java.sql.*;
/**
* Created by shukad on 09/12/15.
*/
public class BulkIngestorConnector {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/bulk_ingestion";
static final String USER = "root";
static final String PASS = "KayajC9s";
private Connection connection;
private static Logger logger = Logger.getLogger(BulkIngestorConnector.class);
public BulkIngestorConnector(){
initializeConnection();
}
public void initializeConnection() {
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void shutdown() {
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
logger.error("Error: " + e.getMessage());
}
}
}
public String getInvoicesToBeIngested(int batchSize){
String ids = "";
try {
String query = "select GROUP_CONCAT(CONCAT('''', A.id, '''')) from (select id from invoice_ingestion where status = 0 limit " + batchSize + ") A;";
Statement statement = connection.createStatement();
statement.execute(query);
ResultSet rs = statement.getResultSet();
rs.next();
ids = rs.getString(1);
//ids = ids + "'";
lockIdsAsPicked(ids);
}catch (SQLException e){
logger.error("Error: " + e.getMessage());
}
return ids;
}
public void lockIdsAsPicked(String ids){
try {
String query = "update invoice_ingestion set status = 2 where id in (" + ids + ")";
Statement statement = connection.createStatement();
statement.executeUpdate(query);
}catch (SQLException e){
logger.error("Error: " + e.getMessage());
}
}
public void markIdsAsIngested(String ids, String ackInfo){
try {
String query = "update invoice_ingestion set status = 1, ack_info = '" + ackInfo
+ "' where id in (" + ids + ")";
Statement statement = connection.createStatement();
statement.executeUpdate(query);
}catch (SQLException e){
logger.error("Error: " + e.getMessage());
}
}
}
|
XZZZZ
.//Java application to show how a similar result like multipal inharitance can be acchive in java
//Defining Super class Base
class Base{
void bdisp(){
System.out.println("Super class bdisp()method called");
}
}//close of super class Base
//Defining interface named style
interface style1{
void sdisp();
}//close of interface named style1
//defining class that extends super class and interface (style1)
class multipal_inharitance extends Base implements style1{
public void sdisp(){
System.out.println("Sdisp()method implimented called");
}
}//close of class
class multipal{
public static void main(String args[]){
multipal_inharitance m=new multipal_inharitance();
m.bdisp();
m.sdisp();
}
}//close of main class
|
package org.point85.domain.dto;
import java.util.ArrayList;
import java.util.List;
import org.point85.domain.schedule.Break;
import org.point85.domain.schedule.Shift;
public class ShiftDto extends TimePeriodDto {
private List<BreakDto> breaks = new ArrayList<>();
public ShiftDto(Shift shift) {
super(shift);
for (Break period : shift.getBreaks()) {
breaks.add(new BreakDto(period));
}
}
public List<BreakDto> getBreaks() {
return this.breaks;
}
}
|
package v2;
public class Deme {
LevelStrategy[] strategies;
int level;
public Deme(LevelStrategy[] strategies, int level) {
this.strategies = strategies;
this.level = level;
checkErrors();
}
private void checkErrors() {
if (strategies.length == 0 || strategies == null || level > MasterVariables.MAXSYSTEM) {
System.out.println("Deme class error!!");
System.exit(0);
}
}
}
|
package com.bergerkiller.bukkit.tc;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import com.google.common.collect.ImmutableList;
/**
* A simple class that uses the 'preloader' section in the plugin.yml
* to load the actual plugin. If dependencies declared in this section
* are not available or other errors occur, the plugin isn't loaded.
*
* If the plugin couldn't be loaded, a message is sent to operators when
* they join the server, as well as when executing the plugin's command.
*
* In case commands are registered inside onEnable() rather than as part
* of plugin.yml, commands can be declared inside the preloader section.
* These will be registered if the plugin could not be loaded.
*
* @author Irmo van den Berge (bergerkiller) - Feel free to use in this
* in your own plugin, I do not care.
* @version 1.3
*/
public class Preloader extends JavaPlugin {
private final String mainClassName;
private final List<Depend> dependList;
private final List<String> preloaderCommands;
private final List<Depend> missingDepends = new ArrayList<>();
private String loadError = null;
public Preloader() {
// Parse the required information from plugin.yml
// If anything goes wrong, abort right away!
try (InputStream stream = getResource("plugin.yml"); Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
YamlConfiguration config = new YamlConfiguration();
config.load(reader);
ConfigurationSection preloaderConfig = config.getConfigurationSection("preloader");
if (preloaderConfig == null) {
throw new IllegalStateException("plugin.yml has no preloader configuration");
}
mainClassName = preloaderConfig.getString("main");
if (mainClassName == null) {
throw new IllegalStateException("plugin.yml preloader configuration declares no main class");
}
// Check that all dependencies exist
ConfigurationSection dependConfig = preloaderConfig.getConfigurationSection("depend");
if (dependConfig == null) {
dependList = Collections.emptyList();
} else {
Set<String> names = dependConfig.getKeys(false);
dependList = new ArrayList<Depend>(names.size());
for (String name : names) {
dependList.add(new Depend(name, dependConfig.getString(name)));
}
}
// Check that commands need to be registered if loading fails
List<String> preloaderCommandsTmp = preloaderConfig.getStringList("commands");
if (preloaderCommandsTmp == null || preloaderCommandsTmp.isEmpty()) {
preloaderCommands = Collections.emptyList();
} else {
preloaderCommands = new ArrayList<String>(preloaderCommandsTmp);
}
} catch (IOException e) {
throw new IllegalStateException("Corrupt jar: Failed to read plugin.yml", e);
} catch (InvalidConfigurationException e) {
throw new IllegalStateException("Corrupt jar: Failed to load plugin.yml", e);
}
}
@Override
@SuppressWarnings({ "deprecation", "unchecked" })
public void onLoad() {
// Verify all the hard depend plugins are available
missingDepends.clear();
for (Depend depend : dependList) {
if (this.getServer().getPluginManager().getPlugin(depend.name) == null) {
missingDepends.add(depend);
}
}
if (!missingDepends.isEmpty()) {
return;
}
// Now that we know all plugins we need are there we can safely make them hard-dependencies
// They cannot be hard-dependencies before, otherwise this preloader cannot handle onEnabled()
// It is also a problem if the main plugin class references classes from a hard dependency,
// because then class not found exceptions will be thrown when instantiating the plugin.
{
PluginDescriptionFile description = this.getDescription();
List<String> newDepend = new ArrayList<String>(description.getDepend());
for (Depend depend : dependList) {
if (!newDepend.contains(depend.name)) {
newDepend.add(depend.name);
}
}
try {
Field field = PluginDescriptionFile.class.getDeclaredField("depend");
field.setAccessible(true);
field.set(description, ImmutableList.copyOf(newDepend));
} catch (Throwable t) {
this.getLogger().log(Level.SEVERE, "Failed to update depend list", t);
}
}
// Get up-front
final String pluginName = this.getName();
// Load the main class as declared in the preloader configuration
final Class<?> mainClass;
try {
mainClass = this.getClassLoader().loadClass(mainClassName);
} catch (ClassNotFoundException e) {
this.getLogger().log(Level.SEVERE, "Failed to load the plugin main class", e);
this.loadError = "Failed to load the plugin main class - check server log!";
return;
}
// Inside the JavaPlugin constructor it initializes itself using the PluginClassLoader
// As part of this, it checks that the plugin and pluginInit fields are unset.
// So before we initialize a new instance, unset these fields.
this.setLoaderPluginField(null, pluginName);
// Initialize the plugin class the same way this preloader class was initialized
// This is normally done inside the constructor of PluginClassLoader
final JavaPlugin mainPlugin;
try {
mainPlugin = (JavaPlugin) mainClass.newInstance();
} catch (Throwable t) {
this.getLogger().log(Level.SEVERE, "Failed to call plugin constructor", t);
this.loadError = "Failed to call plugin constructor - check server log!";
this.setLoaderPluginField(this, pluginName); // Undo this, otherwise state is corrupted
return;
}
// Normally done inside PluginClassLoader constructor, so do it now
setLoaderPluginField(mainPlugin, pluginName);
// Initialization successful! Now replace the plugin instance in all other places
// It's absolutely important we replace it EVERYWHERE or things will probably break!
PluginManager manager = this.getServer().getPluginManager();
try {
// private final List<Plugin> plugins
{
Field pluginsField = manager.getClass().getDeclaredField("plugins");
pluginsField.setAccessible(true);
List<Object> plugins = (List<Object>) pluginsField.get(manager);
int index = plugins.indexOf(this);
if (index == -1) {
throw new IllegalStateException("Preloader does not exist in plugins list");
}
plugins.set(index, mainPlugin);
}
// private final Map<String, Plugin> lookupNames
{
Field lookupNamesField = manager.getClass().getDeclaredField("lookupNames");
lookupNamesField.setAccessible(true);
Map<Object, Object> lookupNames = (Map<Object, Object>) lookupNamesField.get(manager);
boolean found = false;
for (Map.Entry<Object, Object> e : lookupNames.entrySet()) {
if (e.getValue() == this) {
e.setValue(mainPlugin);
found = true;
}
}
if (!found) {
throw new IllegalStateException("Preloader does not exist in lookupNames mapping");
}
}
} catch (Throwable t) {
throw new IllegalStateException("Failed to load plugin into the server", t);
}
// Re-initialize the PluginClassLoader with the new main plugin
// Call onLoad - if this fails, it's as if onLoad failed of the plugin itself
mainPlugin.onLoad();
}
@Override
public void onEnable() {
// Log about these missing dependencies
if (!missingDepends.isEmpty()) {
missingDepends.forEach(depend -> {
final PluginDescriptionFile desc = getDescription();
getLogger().log(Level.SEVERE, "Plugin " + desc.getName() + " " + desc.getVersion() +
" requires plugin " + depend.name + " to be installed! But it is not!");
getLogger().log(Level.SEVERE, "Download " + depend.name + " from " + depend.url);
});
}
// If nothing is wrong, something weird is going on
// It should never get here...
if (this.loadError == null && this.missingDepends.isEmpty()) {
this.loadError = "Preloading failed - unsupported server?";
}
if (this.loadError != null) {
getLogger().log(Level.SEVERE, "Not enabled because plugin could not be loaded! - Check server log");
}
// Register commands late if specified
this.preloaderCommands.forEach(commandName -> {
try {
PluginCommand command;
{
Constructor<PluginCommand> constr = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
constr.setAccessible(true);
command = constr.newInstance(commandName, this);
command.setDescription("Plugin " + getName() + " could not be loaded!");
}
command.setExecutor((sender, label, e_cmd, args) -> {
showErrors(sender);
return true;
});
Field commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("commandMap");
commandMapField.setAccessible(true);
CommandMap commandMap = (CommandMap) commandMapField.get(Bukkit.getPluginManager());
commandMap.register(this.getName(), command);
} catch (Throwable t) {
getLogger().log(Level.SEVERE, "Failed to register preloader fallback command " + commandName, t);
}
});
// Install a Listener into the server with the sole task of annoying people
// Tell them the plugin is not enabled for the reasons as stated
this.getServer().getPluginManager().registerEvents(new Listener() {
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
if (event.getPlayer().isOp()) {
showErrors(event.getPlayer());
}
}
}, this);
}
private void showErrors(CommandSender sender) {
if (this.loadError != null) {
sender.sendMessage(ChatColor.RED + "There was a fatal error initializing " + this.getName());
sender.sendMessage(ChatColor.RED + this.loadError);
} else {
sender.sendMessage(ChatColor.RED + "Plugin " + this.getName() + " could not be enabled!");
sender.sendMessage(ChatColor.RED + "Please install these additional dependencies:");
for (Depend depend : this.missingDepends) {
sender.sendMessage(ChatColor.RED + " ======== " + depend.name + " ========");
sender.sendMessage(ChatColor.RED + " > " + ChatColor.WHITE + ChatColor.UNDERLINE + depend.url);
}
}
}
@SuppressWarnings("unchecked")
private void setLoaderPluginField(JavaPlugin plugin, String pluginName) {
ClassLoader loader = this.getClassLoader();
try {
Field pluginField = loader.getClass().getDeclaredField("plugin");
pluginField.setAccessible(true);
pluginField.set(loader, plugin);
} catch (Throwable t) {
this.getLogger().log(Level.SEVERE, "[Preloader] Failed to update 'plugin' field", t);
}
try {
Field pluginInitField = loader.getClass().getDeclaredField("pluginInit");
pluginInitField.setAccessible(true);
pluginInitField.set(loader, plugin);
} catch (Throwable t) {
this.getLogger().log(Level.SEVERE, "[Preloader] Failed to update 'pluginInit' field", t);
}
// Make sure that during initialization (null) the PluginClassLoader for this plugin
// is not registered in the 'global' JavaPluginLoader loaders field. Having this here
// can cause a nullpointer exception because the plugin is initializing. Normally
// it is also not registered here while calling the constructor.
try {
Field globalLoaderField = loader.getClass().getDeclaredField("loader");
globalLoaderField.setAccessible(true);
JavaPluginLoader globalLoader = (JavaPluginLoader) globalLoaderField.get(loader);
Field globalLoaderPluginLoadersField = JavaPluginLoader.class.getDeclaredField("loaders");
globalLoaderPluginLoadersField.setAccessible(true);
Object rawLoaders = globalLoaderPluginLoadersField.get(globalLoader);
if (rawLoaders instanceof List) {
// Since Bukkit 1.10 onwards
List<Object> pluginLoaders = (List<Object>) rawLoaders;
if (plugin == null) {
pluginLoaders.remove(loader);
} else if (!pluginLoaders.contains(loader)) {
pluginLoaders.add(loader);
}
} else if (rawLoaders instanceof Map) {
// Bukkit/Minecraft 1.8 to 1.9.4 used a Map by plugin name
Map<String, Object> pluginLoaders = (Map<String, Object>) rawLoaders;
if (plugin == null) {
if (pluginLoaders.get(pluginName) == loader) {
pluginLoaders.remove(pluginName);
}
} else {
if (pluginLoaders.get(pluginName) == null) {
pluginLoaders.put(pluginName, loader);
}
}
} else {
throw new IllegalStateException("Unknown loaders field type: " + rawLoaders.getClass());
}
} catch (Throwable t) {
this.getLogger().log(Level.SEVERE, "[Preloader] Failed to update class loader registry", t);
}
}
private static final class Depend {
public final String name;
public final String url;
public Depend(String name, String url) {
this.name = name.replace(' ', '_');
this.url = url;
}
}
}
|
/*
* (c) Copyright 2001-2007 PRODAXIS, S.A.S. All rights reserved.
* PRODAXIS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.prodaxis.junitgenerator.wizards;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* The "New" wizard page allows setting the container for the new file as well
* as the file name. The page will only accept file name without the extension
* OR with the extension that matches the expected one (mpe).
*/
public class JUnitGeneratorWizardPage extends WizardPage {
private Text packageText; // Package read-lony
private Text classText; // Source Class read-only
private Text junitText; // JUnit Class mandatory
private ICompilationUnit compilationUnit;
/**
* Constructor for JUnitGeneratorWizardPage.
*
* @param compilationUnit
*/
public JUnitGeneratorWizardPage(ICompilationUnit compilationUnit) {
super("wizardPage");
setTitle("Generate Mapping File");
setDescription("This wizard creates the Bean Component's JUnit Test.\n");
this.compilationUnit = compilationUnit;
}
/**
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NULL);
GridLayout gridLayout = new GridLayout();
composite.setLayout(gridLayout);
gridLayout.numColumns = 2;
gridLayout.verticalSpacing = 9;
Label label = new Label(composite, SWT.NULL);
label.setText("Package:");
packageText = new Text(composite, SWT.BORDER | SWT.SINGLE);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
packageText.setLayoutData(gridData);
packageText.setEnabled(false);
label = new Label(composite, SWT.NULL);
label.setText("Class Name:");
classText = new Text(composite, SWT.BORDER | SWT.SINGLE);
gridData = new GridData(GridData.FILL_HORIZONTAL);
classText.setLayoutData(gridData);
classText.setEnabled(false);
label = new Label(composite, SWT.NULL);
label.setText("JUnit Test Class Name:");
junitText = new Text(composite, SWT.BORDER | SWT.SINGLE);
gridData = new GridData(GridData.FILL_HORIZONTAL);
junitText.setLayoutData(gridData);
junitText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
dialogChanged();
}
});
initialize();
setControl(composite);
}
/**
* Ensures that both text fields are set.
*/
private void dialogChanged() {
if (null == junitText || null == junitText.getText() || "".equals(junitText.getText())) {
updateStatus("JUnit Test Class Name must be spรฉcified");
return;
}
updateStatus(null);
}
private void updateStatus(String message) {
setErrorMessage(message);
setPageComplete(message == null);
}
/**
* Tests if the current workbench selection is a suitable container to use.
*/
private void initialize() {
if (compilationUnit != null) {
packageText.setText(compilationUnit.getParent().getElementName());
try {
classText.setText(compilationUnit.getTypes()[0].getElementName());
junitText.setText(classText.getText().substring(0, classText.getText().length() - 4) + "Test");
}
catch (JavaModelException exception) {
}
}
dialogChanged();
}
public String getPackageText() {
return packageText.getText();
}
public String getClassText() {
return classText.getText();
}
public String getJunitText() {
return junitText.getText();
}
}
|
package travel.api.chat.service.impl;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import travel.api.chat.service.ChatService;
import travel.api.config.response.WorkException;
import travel.api.config.response.WorkStatus;
import travel.api.dto.request.chat.ChatRequestDTO;
import travel.api.dto.request.user.UserRequestDTO;
import travel.api.dto.response.chat.FriendResponseDTO;
import travel.api.dto.response.chat.PrivateMsgResponseDTO;
import travel.api.table.mapper.PrivateMsgMapper;
import travel.api.table.mapper.UserUserRelationMapper;
import java.util.List;
/**
* @Author: dd
*/
@Service
public class ChatServiceImpl implements ChatService {
@Autowired
private UserUserRelationMapper userUserRelationMapper;
@Autowired
private PrivateMsgMapper privateMsgMapper;
@Override
public JSONObject friendList(UserRequestDTO userRequestDTO) {
if (null == userRequestDTO.getUserId()) {
throw new WorkException(WorkStatus.CHECK_PARAM);
}
List<FriendResponseDTO> friendList = userUserRelationMapper.friendList(userRequestDTO.getUserId());
JSONObject jsonObject = new JSONObject();
jsonObject.put("friends", friendList);
return jsonObject;
}
@Override
public JSONObject privateMsg(ChatRequestDTO requestDTO) {
if (null == requestDTO.getFromUser() || null == requestDTO.getToUser()) {
throw new WorkException(WorkStatus.CHECK_PARAM);
}
List<PrivateMsgResponseDTO> list = privateMsgMapper.privateMsg(requestDTO);
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", list);
return jsonObject;
}
}
|
public class Car implements Vehicle {
private Vehicle.VehicleType type;
public Car(Vehicle.VehicleType type){
this.type = type; //passed the type (reg/HC) of the bike when initialized
}
@Override
public Vehicle.VehicleSize getSize() {
return Vehicle.VehicleSize.MEDIUM;
}
@Override
public Vehicle.VehicleType getType() {
return type;
}
}
|
package sundayhomework;
public class ManupulatingMarks {
int firstNumber ;
int secondNumber;
int add(int addNum1,int addNum2)
{
int resultAdditionVal = addNum1 + addNum2;
return resultAdditionVal;
}
int sub(int subNum1, int subNum2)
{
int resultSubrationVal = subNum1 - subNum2;
return resultSubrationVal;
}
int mul(int mulNum1, int mulNum2)
{
int resultMultiplicationVal = mulNum1*mulNum2;
return resultMultiplicationVal;
}
int div(int divNum1, int divNum2)
{
int resultDivisionVal = divNum1/divNum2;
return resultDivisionVal;
}
} |
package io.chark.food.domain.restaurant;
import io.chark.food.domain.BaseRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RestaurantDetailsRepository extends BaseRepository<RestaurantDetails> {
} |
package com.zc.pivas.docteradvice.service.impl;
import com.zc.base.orm.mybatis.paging.JqueryStylePaging;
import com.zc.base.orm.mybatis.paging.JqueryStylePagingResults;
import com.zc.base.sys.common.util.NumberUtil;
import com.zc.pivas.docteradvice.bean.ForceRulesWithArea;
import com.zc.pivas.docteradvice.bean.PriorityRulesWithArea;
import com.zc.pivas.docteradvice.bean.VolumeRulesWithBatch;
import com.zc.pivas.docteradvice.entity.OtherRule;
import com.zc.pivas.docteradvice.entity.PriorityRules;
import com.zc.pivas.docteradvice.entity.VolumeRules;
import com.zc.pivas.docteradvice.repository.PrescriptionRuleDao;
import com.zc.pivas.docteradvice.service.PrescriptionRuleService;
import com.zc.pivas.medicamentscategory.entity.MedicCategory;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ๆนๆฌกไผๅ
*
* @author Ray
* @version 1.0
*/
@Service("ydRuleService")
public class PrescriptionRuleServiceImpl implements PrescriptionRuleService {
@Resource
private PrescriptionRuleDao ydRuleDao;
/**
* ่ฏ็ฉไผๅ
็บงๆฅ่ฏข
*
* @param map
* @return
*/
@Override
public List<PriorityRulesWithArea> qryPrioRulesList(Map<String, Object> map) {
return ydRuleDao.qryPrioRulesList(map);
}
/**
* ๆทปๅ ่ฏ็ฉไผๅ
็บง
*
* @param prioRules
* @return
*/
@Override
public Integer addPrioRules(PriorityRules prioRules) {
return ydRuleDao.addPrioRules(prioRules);
}
/**
* ๆดๆฐ่ฏ็ฉไผๅ
็บง
*
* @param map
* @return
*/
@Override
public Integer updPrioRules(Map<String, Object> map) {
return ydRuleDao.updPrioRules(map);
}
@Override
public Integer updTwoPrioRules(Map<String, Object> map1, Map<String, Object> map2) {
int row1 = ydRuleDao.updPrioRules(map1);
int row2 = ydRuleDao.updPrioRules(map2);
return row1 + row2;
}
/**
* ๅ ้ค่ฏ็ฉไผๅ
็บง
*
* @param map
* @return
*/
@Override
public Integer delPrioRules(Map<String, Object> map) {
return ydRuleDao.delPrioRules(map);
}
@Override
public Integer delPrioRules(Object prId) {
Long prIdL = NumberUtil.getObjLong(prId);
if (prIdL != null) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("prId", prIdL);
return delPrioRules(map);
}
return 0;
}
/**
* ๆฅ่ฏข่ฏ็ฉไผๅ
็บงไธไธไธชๅบๅท
*
* @param map
* @return
*/
@Override
public Integer qryPrioRulesVal(Map<String, Object> map) {
return ydRuleDao.qryPrioRulesVal(map);
}
/**
* ๆฅ่ฏข่ฏ็ฉไผๅ
็บงไธไธไธชๅบๅท
*
* @param prType
* @param deptcode
* @return
*/
@Override
public Integer qryPrioRulesVal(Integer prType, String deptcode) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("prType", prType);
map.put("deptcode", deptcode);
Integer maxVal = ydRuleDao.qryPrioRulesVal(map);
if (maxVal != null) {
return maxVal;
}
return 1;
}
/**
* ๆน้ๆทปๅ ่ฏ็ฉไผๅ
็บง
*
* @param map
* @return
*/
@Override
public Integer addPrioRulesMany(Map<String, Object> map) {
return ydRuleDao.addPrioRulesMany(map);
}
/**
* ๆน้ๆทปๅ ่ฏ็ฉไผๅ
็บง
*
* @param addMap
* @return
*/
@Override
public Integer addAndDelPrioRulesMany(Map<String, Object> addMap) {
/* int row = ydRuleDao.delPrioRules(delMap);*/
return ydRuleDao.addPrioRulesMany(addMap);
}
/**
* ๆฅ่ฏขๅฎน็งฏ่งๅ
*
* @param map
* @param jquryStylePaging
* @return
*/
@Override
public List<VolumeRulesWithBatch> qryVolumeRulesList(Map<String, Object> map, JqueryStylePaging jquryStylePaging) {
return ydRuleDao.qryVolumeRulesList(map, jquryStylePaging);
}
/**
* ๆฅ่ฏขๅฎน็งฏ่งๅๆปๆฐ
*
* @param map
* @return
*/
@Override
public Integer qryVolumeRulesCount(Map<String, Object> map) {
return ydRuleDao.qryVolumeRulesCount(map);
}
/**
* ๆทปๅ ๅฎน็งฏ่งๅ
*
* @param prioRules
* @return
*/
@Override
public Integer addVolumeRules(VolumeRules prioRules) {
return ydRuleDao.addVolumeRules(prioRules);
}
/**
* ๆดๆฐๅฎน็งฏ่งๅ
*
* @param map
* @return
*/
@Override
public Integer updVolumeRules(Map<String, Object> map) {
return ydRuleDao.updVolumeRules(map);
}
/**
* ๅ ้คๅฎน็งฏ่งๅ
*
* @param map
* @return
*/
@Override
public Integer delVolumeRules(Map<String, Object> map) {
return ydRuleDao.delVolumeRules(map);
}
/**
* ๆน้ๆทปๅ ๅฎน็งฏ่งๅ
*
* @param map
* @return
*/
@Override
public Integer addVolumeRulesMany(Map<String, Object> map) {
return ydRuleDao.addVolumeRulesMany(map);
}
/**
* ๆน้ๆทปๅ ๅฎน็งฏ่งๅ
*
* @param addMap
* @return
*/
@Override
public Integer addAndDeVolumeRulesMany(Map<String, Object> addMap) {
/*int row = ydRuleDao.delVolumeRules(delMap);*/
return ydRuleDao.addVolumeRulesMany(addMap);
}
/**
* ๅ้กตๆฅ่ฏขๅฎน็งฏ่งๅ
*
* @param map
* @param jquryStylePaging
* @return
* @throws Exception
*/
@Override
public JqueryStylePagingResults<VolumeRulesWithBatch> qryVolRulePageByMap(Map<String, Object> map, JqueryStylePaging jquryStylePaging) throws Exception {
List<VolumeRulesWithBatch> listBean = ydRuleDao.qryVolumeRulesList(map, jquryStylePaging);
int rowCount = ydRuleDao.qryVolumeRulesCount(map);
String[] columns = {"vrId", "vrType", "deptcode", "batchId", "overrun", "maxval", "minval", "vrUserId", "vrTime", "deptname", "batchName"};
JqueryStylePagingResults<VolumeRulesWithBatch> pagingResults = new JqueryStylePagingResults<VolumeRulesWithBatch>(columns);
pagingResults.setDataRows(listBean);
pagingResults.setTotal(rowCount);
pagingResults.setPage(jquryStylePaging.getPage());
return pagingResults;
}
/**
* ๆฅ่ฏขๅผบๅถๆนๆฌก
*
* @param map
* @param jquryStylePaging
* @return
*/
@Override
public List<ForceRulesWithArea> qryForceRulesList(Map<String, Object> map, JqueryStylePaging jquryStylePaging) {
return ydRuleDao.qryForceRulesList(map, jquryStylePaging);
}
/**
* ๆฅ่ฏขๅผบๅถๆนๆฌกๆปๆฐ
*
* @param map
* @return
*/
@Override
public Integer qryForceRulesCount(Map<String, Object> map) {
return ydRuleDao.qryForceRulesCount(map);
}
/**
* ๆดๆฐๅผบๅถๆนๆฌก
*
* @param map
* @return
*/
@Override
public Integer updForceRules(Map<String, Object> map) {
return ydRuleDao.updForceRules(map);
}
/**
* ๅ้กตๆฅ่ฏขๅผบๅถ่งๅ
*
* @param map
* @param jquryStylePaging
* @return
* @throws Exception
*/
@Override
public JqueryStylePagingResults<ForceRulesWithArea> qryForceRulePageByMap(Map<String, Object> map, JqueryStylePaging jquryStylePaging) throws Exception {
List<ForceRulesWithArea> listBean = ydRuleDao.qryForceRulesList(map, jquryStylePaging);
int rowCount = ydRuleDao.qryForceRulesCount(map);
String[] columns = {"prId", "prType", "deptcode", "medicId", "medicType", "batchId", "prOrder", "prUserId", "prTime", "deptname", "medicName", "batchName"};
JqueryStylePagingResults<ForceRulesWithArea> pagingResults = new JqueryStylePagingResults<ForceRulesWithArea>(columns);
pagingResults.setDataRows(listBean);
pagingResults.setTotal(rowCount);
pagingResults.setPage(jquryStylePaging.getPage());
return pagingResults;
}
/**
* ๆฅ่ฏขๅ
ถไป่งๅ
*
* @param map
* @return
*/
@Override
public List<OtherRule> qryOtherRulesList(@Param("qry") Map<String, Object> map) {
return ydRuleDao.qryOtherRulesList(map);
}
/**
* ๆดๆฐๅ
ถไป่งๅ
*
* @param map
* @return
*/
@Override
public Integer updOtherRules(@Param("map") Map<String, Object> map) {
return ydRuleDao.updOtherRules(map);
}
/**
* ่ทๅ่ฏๅ็ง็ฑป
*
* @param map
* @return
*/
@Override
public List<MedicCategory> qryMedicamentCategory(@Param("qry") Map<String, Object> map) {
return ydRuleDao.qryMedicamentCategory(map);
}
/**
* ๆฃๆฅๅฎน็งฏ่งๅๆฏๅฆๅญๅจ
*
* @param volumeRules
* @return
*/
@Override
public List<VolumeRules> checkVolumRuleExist(@Param("volumeRules") VolumeRules volumeRules) {
// TODO Auto-generated method stub
return ydRuleDao.checkVolumRuleExist(volumeRules);
}
}
|
package jianzhioffer;
import a_important.tool.TreeNode;
/**
* @ClassName : Solution54
* @Description : ไบๅๆๅบๆ ็็ฌฌKไธช่็น
* @Date : 2019/9/19 20:35
*/
public class Solution54 {
int count=0;
TreeNode res=null;
TreeNode KthNode(TreeNode pRoot, int k)
{
if (pRoot==null || k<=0)
return null;
return getKthNode(pRoot,k);
}
//ไธญๅบ้ๅ
private TreeNode getKthNode(TreeNode pRoot, int k) {
if (pRoot.left!=null)
getKthNode(pRoot.left,k);
count++;
if (count==k){
res=pRoot;
}
if (res==null && pRoot.right!=null)
getKthNode(pRoot.right,k);
return res;
}
}
|
package com.skilldistillery.fallout.data;
import java.util.List;
import org.springframework.stereotype.Component;
import com.skilldistillery.fallout.entities.FalloutCharacter;
@Component
public interface FOCharacterDAO {
FalloutCharacter findById(int id);
FalloutCharacter createCharacter(FalloutCharacter foCharacter);
FalloutCharacter updateCharacter(FalloutCharacter foCharacter);
boolean deleteCharacter(FalloutCharacter foCharacter);
List<FalloutCharacter> findCharBySearchString(String keyword);
}
|
package com.scriptingsystems.tutorialjava.poo.collections;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Diccionario {
Map <Character, List<String>> buffer;
public Diccionario (String file) throws FileNotFoundException {
buffer=new HashMap<>();
FileInputStream in=new FileInputStream(file);
Scanner sc=new Scanner(in);
load(sc);
}
private void load(Scanner sc){
while(sc.hasNext()){
String line=sc.nextLine();
//Guadar la linea leida en el buffer
char c=line.charAt(0);
List<String> l=buffer.get(c);
if(l==null){
l=new ArrayList<>();
buffer.put(c, l);
}
l.add(line);
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
if (buffer == null) {
return "No hay informaciรณn";
}
Set<Character> keys = buffer.keySet();
for (Character key : keys) {
List<String> values = buffer.get(key);
System.out.println(key + "[" );
for (String s : values) {
System.out.println(s+ ", ");
}
System.out.println("]");
}
return "";
}
}
|
package com.bofsoft.laio.customerservice.Fragment;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.alibaba.fastjson.JSON;
import com.bofsoft.laio.common.CommandCodeTS;
import com.bofsoft.laio.common.MyLog;
import com.bofsoft.laio.customerservice.Activity.BaseFragment;
import com.bofsoft.laio.customerservice.DataClass.BaseResponseStatusData;
import com.bofsoft.laio.customerservice.R;
import com.bofsoft.laio.customerservice.Widget.JasonScrollView;
import com.bofsoft.laio.customerservice.Widget.JasonWebView;
import com.bofsoft.laio.tcp.DataLoadTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* ไบงๅๅ่ฎฎ๏ผๆๅกๆ ๅ ้่ดน่งๅ ๅญฆๅไฟ้
*
* @author yedong
*/
public class FragmentServiceProtocol extends BaseFragment {
MyLog myLog = new MyLog(getClass());
private JasonWebView mWebView;
private View mOptionView;
private int ReqType; // Integer ่ฏทๆฑๆนๅผ๏ผ0 ไบงๅๅๅธๆถ่ฏทๆฑ ,1 ้่ฟไบงๅๆ่ฎขๅId
private int ProtocolType; // Integer ๅ่ฎฎ็ฑปๅ๏ผ0ๆๅกๆ ๅ๏ผ1้่ดน่งๅ
// ไบงๅๆ่ฎขๅId๏ผ
private int Type; // Integer ่ฏทๆฑ็ฑปๅ๏ผ0ไบงๅ๏ผ1่ฎขๅ
private int Id; // Integer ไบงๅๆ่ฎขๅID
private int ClassType = -1; // ไบงๅIdๆถ(ๅน่ฎญ้ๆญคๅๆฐ)๏ผ0ไธบ่ฟๅๅ
จ้จ๏ผ1ๅๅญฆๅน่ฎญ๏ผ2่กฅ่ฎญ๏ผ3้ช็ป๏ผ
private BaseResponseStatusData mProtocalData;
// public Handler mHandler;
// private boolean isCallBack = false;
public FragmentServiceProtocol() {
super();
}
/**
* @param reqType ่ฏทๆฑๆนๅผ๏ผ0 ไบงๅๅๅธๆถ่ฏทๆฑ ,1 ้่ฟไบงๅๆ่ฎขๅId
* @param protocolType Integer ๅ่ฎฎ็ฑปๅ๏ผ0ๆๅกๆ ๅ๏ผ1้่ดน่งๅ
* @param type ่ฏทๆฑ็ฑปๅ๏ผ0ไบงๅ๏ผ1่ฎขๅ
* @param id Integer ไบงๅๆ่ฎขๅID
*/
@SuppressLint("ValidFragment")
public FragmentServiceProtocol(int reqType, int protocolType, int type, int id) {
super();
ReqType = reqType;
ProtocolType = protocolType;
Type = type;
Id = id;
}
/**
* @param reqType ่ฏทๆฑๆนๅผ๏ผ0 ไบงๅๅๅธๆถ่ฏทๆฑ ,1 ้่ฟไบงๅๆ่ฎขๅId
* @param protocolType Integer ๅ่ฎฎ็ฑปๅ๏ผ0ๆๅกๆ ๅ๏ผ1้่ดน่งๅ
* @param type ่ฏทๆฑ็ฑปๅ๏ผ0ไบงๅ๏ผ1่ฎขๅ
* @param id Integer ไบงๅๆ่ฎขๅID
* @param classType ไบงๅIdๆถ(ๅน่ฎญ้ๆญคๅๆฐ)๏ผ0ไธบ่ฟๅๅ
จ้จ๏ผ1ๅๅญฆๅน่ฎญ๏ผ2่กฅ่ฎญ๏ผ3้ช็ป๏ผ
*/
@SuppressLint("ValidFragment")
public FragmentServiceProtocol(int reqType, int protocolType, int type, int id, int classType) {
super();
ReqType = reqType;
ProtocolType = protocolType;
Type = type;
Id = id;
ClassType = classType;
}
@Override
public void messageBack(int code, String result) {
super.messageBack(code, result);
switch (code) {
case CommandCodeTS.CMD_PROTOCOL_TRAIN:
parseProtocolData(result);
break;
case CommandCodeTS.CMD_PROTOCOL_REG:
parseProtocolData(result);
break;
default:
break;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view =
LayoutInflater.from(getActivity()).inflate(R.layout.fragment_service_protocol, container,
false);
initView(view);
return view;
}
/**
* ่ทๅๆ็่ฎขๅๅ่ฎฎ
*
* @param reqType ่ฏทๆฑๆนๅผ๏ผ0 ไบงๅๅๅธๆถ่ฏทๆฑ ,1 ้่ฟไบงๅๆ่ฎขๅId
* @param protocolType Integer ๅ่ฎฎ็ฑปๅ๏ผ0ๆๅกๆ ๅ๏ผ1้่ดน่งๅ
* @param type ่ฏทๆฑ็ฑปๅ๏ผ0ไบงๅ๏ผ1่ฎขๅ
* @param id Integer ไบงๅๆ่ฎขๅID
*/
public void loadData(int reqType, int protocolType, int type, int id) {
this.ReqType = reqType;
this.ProtocolType = protocolType;
this.Type = type;
this.Id = id;
if (mProtocalData == null) {
getProtocalData();
} else {
loadView();
}
}
/**
* ่ทๅๅน่ฎญ่ฎขๅๅ่ฎฎ
*
* @param reqType ่ฏทๆฑๆนๅผ๏ผ0 ไบงๅๅๅธๆถ่ฏทๆฑ ,1 ้่ฟไบงๅๆ่ฎขๅId
* @param protocolType Integer ๅ่ฎฎ็ฑปๅ๏ผ0ๆๅกๆ ๅ๏ผ1้่ดน่งๅ
* @param type ่ฏทๆฑ็ฑปๅ๏ผ0ไบงๅ๏ผ1่ฎขๅ
* @param id Integer ไบงๅๆ่ฎขๅID
* @param classType ไบงๅIdๆถ(ๅน่ฎญ้ๆญคๅๆฐ)๏ผ0ไธบ่ฟๅๅ
จ้จ๏ผ1ๅๅญฆๅน่ฎญ๏ผ2่กฅ่ฎญ๏ผ3้ช็ป๏ผ
*/
public void loadData(int reqType, int protocolType, int type, int id, int classType) {
this.ReqType = reqType;
this.ProtocolType = protocolType;
this.Type = type;
this.Id = id;
this.ClassType = classType;
if (mProtocalData == null) {
getProtocalData();
} else {
loadView();
}
}
public void initView(View view) {
mWebView = (JasonWebView) view.findViewById(R.id.webview);
mWebView.requestFocus();
mWebView.getSettings().setDefaultFontSize(14);
mWebView.setJasonWebViewBack(new JasonWebView.IJasonWebViewBack() {
@Override
public int onLoadOverAndChangeSize(View v, int h) {
int parentH = JasonScrollView.getScrollParentH(mOptionView);
int opHeight = 0;
if (mOptionView != null) {
opHeight = mOptionView.getHeight();
}
int height = parentH - opHeight;
myLog.i("-------------parentH|" + parentH + "-----opHeight|" + opHeight);
// if (height < h && mHandler != null) {
// mHandler.sendEmptyMessage(0);
// } else {
// if (isCallBack) {
// if (mWebView.isloadOver) {
// if (mHandler != null)
// mHandler.sendEmptyMessage(0);
// }
// }
// }
// isCallBack = true;
return h < height ? height : h;
}
});
loadView();
}
/**
* ๅทๆฐ็้ข
*/
private void loadView() {
if (mProtocalData != null) {
if (mProtocalData.Code == 1 && !TextUtils.isEmpty(mProtocalData.Content)) {
mWebView.loadDataWithBaseURL("", mProtocalData.Content, "text/html", "UTF-8", "");
}
// else {
// mWebView.loadUrl("file:///android_asset/index.html");
// }
}
// else {
// mWebView.loadUrl("file:///android_asset/index.html");
// }
}
/**
* ่ทๅๅ่ฎฎdata
*/
private void getProtocalData() {
JSONObject jsonObject = new JSONObject();
short commandid = 0;
try {
jsonObject.put("ReqType", ReqType);
jsonObject.put("ProtocolType", ProtocolType);
JSONArray FindList = new JSONArray();
JSONObject FindListObj = new JSONObject();
FindListObj.put("Type", Type);
FindListObj.put("Id", Id);
if (ClassType != -1) {
FindListObj.put("ClassType", ClassType);
commandid = CommandCodeTS.CMD_PROTOCOL_TRAIN;
} else {
commandid = CommandCodeTS.CMD_PROTOCOL_REG;
}
FindList.put(FindListObj);
jsonObject.put("FindList", FindList);
} catch (JSONException e) {
e.printStackTrace();
}
DataLoadTask.getInstance().loadData(commandid, jsonObject.toString(), this);
}
private void parseProtocolData(String result) {
mProtocalData = JSON.parseObject(result, BaseResponseStatusData.class);
loadView();
}
/**
* ๆฅๅๅๆปๅฎไฝoptionๆงไปถ
*
* @param view
*/
public void setScrollBackView(View view) {
this.mOptionView = view;
}
@Override
public void onDestroyView() {
if (mWebView != null) {
ViewGroup parent = (ViewGroup) mWebView.getParent();
if (parent != null) {
parent.removeView(mWebView);
}
super.onDestroyView();
mWebView.removeAllViews();
mWebView.destroy();
} else {
super.onDestroyView();
}
}
}
|
package fr.lteconsulting.pomexplorer.commands;
import fr.lteconsulting.pomexplorer.Application;
import fr.lteconsulting.pomexplorer.ILogger;
@Command
public class HelpCommand extends AbstractCommand
{
public HelpCommand(Application application)
{
super(application);
}
@Help("gives this message")
public void main(ILogger log)
{
log.html(commands().help());
}
}
|
package Pro37.GetNumberOfK;
import java.util.HashMap;
public class Solution
{
// hashMap
public int GetNumberOfK(int[] array, int k)
{
HashMap<Integer, Integer> hashMap = new HashMap<>();
hashMap = sumNum(array);
int position = findPosition(array, k);
return hashMap.get(array[position]);
}
private int findPosition(int[] array, int k)
{
for (int i = 0; i < array.length; i++)
{
if (k == array[i])
{
return i;
}
else
{
return 0;
}
}
return 0;
}
private HashMap<Integer, Integer> sumNum(int[] array)
{
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < array.length; i++)
{
if (hashMap.containsKey(array[i]))
{
int num = hashMap.get(array[i]);
hashMap.put(array[i], ++num);
}
else
{
hashMap.put(array[i], 1);
}
}
return hashMap;
}
// ไบๅๆฅๆพ
public int GetNumberOfk1(int[] array, int k)
{
int length = array.length;
if (length == 0)
{
return 0;
}
int firstK = getFirstK(array, k, 0, length - 1);
int lastK = getLastK(array, k, 0, length - 1);
if (firstK != -1 && lastK != -1)
{
return lastK - firstK + 1;
}
return 0;
}
private int getFirstK(int[] array, int k, int start, int end)
{
if (start > end)
{
return -1;
}
int mid = (start + end) >> 1;
if (array[mid] > k)
{
return getFirstK(array, k, start, mid - 1);
}
else if (array[mid] < k)
{
return getFirstK(array, k, mid + 1, end);
}
else if (mid - 1 >= 0 && array[mid - 1] == k)
{
return getFirstK(array, k, start, mid - 1);
}
else
{
return mid;
}
}
private int getLastK(int[] array, int k, int start, int end)
{
int length = array.length;
int mid = (start + end) >> 1;
while ((start <= end))
{
if (array[mid] > k)
{
end = mid - 1;
}
else if (array[mid] < k)
{
start = mid + 1;
}
else if (mid + 1 < length && array[mid + 1] == k)
{
start = mid + 1;
}
else
{
return mid;
}
mid = (start + end) >> 1;
}
return -1;
}
}
|
package br.com.votacao.principal;
import br.com.votacao.beans.Magica;
public class ImplementarVoto {
public static void main(String[] args) {
Magica.i("Digite a zona");
Magica.i("Digite a secao");
Magica.s("Digite a cidade");
}
}
|
package negocio.repositorio;
import hibernate.util.HibernateUtil;
import java.util.List;
import negocio.basica.Privilegio;
public class RepositorioPrivilegio {
public void incluir(Privilegio pPrivilegio){
HibernateUtil.getSession().save(pPrivilegio);
}
public void alterar(Privilegio pPrivilegio){
HibernateUtil.getSession().update(pPrivilegio);
}
public void remover(Privilegio pPrivilegio){
HibernateUtil.getSession().delete(pPrivilegio);
}
public Privilegio consultarPorChavePrimaria(Privilegio pPrivilegio){
pPrivilegio = (Privilegio) HibernateUtil.getSession().get(Privilegio.class,
pPrivilegio.getId());
return pPrivilegio;
}
public List<Privilegio> listar(){
List<Privilegio> retorno;
retorno = HibernateUtil.getSession().createCriteria(Privilegio.class).list();
return retorno;
}
}
|
import java.util.Scanner;
public class OneEmp {
int empno; String empname; int age;
OneEmp(int empno, String empname, int age){
this.empno = empno;
this.empname=empname;
this.age=age;
}
}
/**
public class emp{
public static void main(String [] args){
//int a=20;
//Integer i=Integer.valueOf(a);
Integer a=new Integer(3);
int i =a.intValue();//converting Integer to int
Integer j=a;//unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
int i2 = 90; // Primitive data type 'int'
// Integer Wrapper class instantiation
Integer i2_Obj = new Integer(i); // Unwrapping primitive data 'int' from wrapper object
int i3 = i2_Obj.intValue(); System.out.println(i2 + i3);
}
}
//float has three default constructors in form of wrapper classes. These are int/float/double/boolean/short/long
//eg) a primitive data type int has two constructors as an Integer and Valueof()
//float as three constructors float/string/double
//default constructor is available in java.lang.comnpARE
*/ |
package com.worldchip.bbpawphonechat.dialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.easemob.chat.EMChatManager;
import com.worldchip.bbpawphonechat.R;
import com.worldchip.bbpawphonechat.application.MyApplication;
import com.worldchip.bbpawphonechat.comments.MyComment;
import com.worldchip.bbpawphonechat.comments.MySharePreData;
public class EditNameDialog extends Dialog implements
android.view.View.OnClickListener {
private Context context;
private Handler handler;
private String currentName;
private String changeName;
private boolean updatenick = false;
private EditText et_name;
private Button btn_sure, btn_cancel;
private RelativeLayout rl_bg;
public EditNameDialog(Handler handler, Context context) {
super(context, R.style.Aleart_Dialog_Style);
this.context = context;
this.handler = handler;
currentName = MySharePreData.GetData(context, MyComment.CHAT_SP_NAME,
MyComment.MY_NICK_NAME);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_setting_edit_user_name);
rl_bg = (RelativeLayout) findViewById(R.id.rl_dialog_edit_user_name_bg);
btn_cancel = (Button) findViewById(R.id.btn_edit_name_cancel);
btn_sure = (Button) findViewById(R.id.btn_edit_name_sure);
et_name = (EditText) findViewById(R.id.et_dialog_user_name);
imageAdapter();
if (currentName.equals("")) {
et_name.setText(MyApplication.getInstance().getUserName());
} else {
et_name.setText(currentName);
}
et_name.setSelection(et_name.getText().length());
btn_cancel.setOnClickListener(this);
btn_sure.setOnClickListener(this);
}
private void imageAdapter() {
// TODO Auto-generated method stub
MyApplication.getInstance().ImageAdapter(
rl_bg,
new int[] { R.drawable.dialog_edit_user_name_bg,
R.drawable.dialog_edit_user_name_bg_es,
R.drawable.dialog_edit_user_name_bg_en });
MyApplication.getInstance().ImageAdapter(
btn_cancel,
new int[] { R.drawable.selector_btn_cancle,
R.drawable.selector_btn_cancle_es,
R.drawable.selector_btn_cancle_en });
MyApplication.getInstance().ImageAdapter(
btn_sure,
new int[] { R.drawable.selector_btn_sure,
R.drawable.selector_btn_sure_es,
R.drawable.selector_btn_sure_en });
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_edit_name_sure:
changeName = et_name.getText().toString().trim();
if (!changeName.equals("")) {
Message message = new Message();
message.what = MyComment.CHANGE_NICK_NAME;
message.obj = changeName;
handler.sendMessage(message);
dismiss();
}else{
Toast.makeText(context, R.string.change_name_null, Toast.LENGTH_LONG).show();
}
break;
case R.id.btn_edit_name_cancel:
dismiss();
break;
default:
break;
}
}
}
|
package by.orion.onlinertasks.presentation.main.fragments.tasks.mappers;
import android.content.Context;
import android.support.annotation.NonNull;
import javax.inject.Inject;
import by.orion.onlinertasks.R;
import by.orion.onlinertasks.common.GenericObjectMapper;
import by.orion.onlinertasks.data.models.task.Image;
import by.orion.onlinertasks.data.models.task.Price;
import by.orion.onlinertasks.data.models.task.Task;
import by.orion.onlinertasks.presentation.common.models.TaskStatus;
import by.orion.onlinertasks.presentation.main.fragments.tasks.models.TaskItem;
public class TaskToTaskItemMapper implements GenericObjectMapper<Task, TaskItem> {
@NonNull
private final Context context;
@Inject
public TaskToTaskItemMapper(@NonNull Context context) {
this.context = context;
}
@NonNull
@Override
public TaskItem map(@NonNull Task task) {
Image image = task.image();
Price price = task.price();
return TaskItem.builder()
.id(task.id())
.title(task.title())
.description(task.description())
.imageUrl(image != null ? image._280x280() : null)
.price(price != null ? String.format("%s %s", price.amount(), price.currency()) : null)
.status(TaskStatus.get(task.status()))
.proposalsQty(task.proposals_qty())
.location(new TaskLocationToTaskLocationItemMapper().map(task.location()))
.deadline(String.format("%s %s", context.getString(R.string.common_before), task.deadline()))
.createdAt(task.createdAt())
.author(new TaskAuthorToTaskAuthorItemMapper().map(task.author()))
.section(new TaskSectionToTaskSectionItemMapper().map(task.section()))
.build();
}
}
|
package code;
/**
* ๆ ๅฏไปฅ็ๆๆฏไธไธช่ฟ้ไธ ๆ ็ฏย ็ย ๆ ๅย ๅพใ
* <p>
* ็ปๅฎๅพไธๆฃตย n ไธช่็น (่็นๅผย 1๏ฝn) ็ๆ ไธญๆทปๅ ไธๆก่พนๅ็ๅพใๆทปๅ ็่พน็ไธคไธช้กถ็นๅ
ๅซๅจ 1 ๅฐ nย ไธญ้ด๏ผไธ่ฟๆก้ๅ ็่พนไธๅฑไบๆ ไธญๅทฒๅญๅจ็่พนใๅพ็ไฟกๆฏ่ฎฐๅฝไบ้ฟๅบฆไธบ n ็ไบ็ปดๆฐ็ป edgesย ๏ผedges[i] = [ai, bi]ย ่กจ็คบๅพไธญๅจ ai ๅ bi ไน้ดๅญๅจไธๆก่พนใ
* <p>
* ่ฏทๆพๅบไธๆกๅฏไปฅๅ ๅป็่พน๏ผๅ ้คๅๅฏไฝฟๅพๅฉไฝ้จๅๆฏไธไธชๆ็ n ไธช่็น็ๆ ใๅฆๆๆๅคไธช็ญๆก๏ผๅ่ฟๅๆฐ็ปย edgesย ไธญๆๅๅบ็ฐ็่พนใ
* <p>
* Solution:
* ๅนถๆฅ้
*
* @author liyuke
* @date 2021-08-04 21:46
*/
public class RedundantConnection {
private int[] fa;
public int[] findRedundantConnection(int[][] edges) {
int n = edges.length;
fa = new int[n + 1];
for (int i = 0; i <= n; i++) {
fa[i] = i;
}
for (int[] edge : edges) {
if (find(edge[0]) == find(edge[1])) {
return edge;
}
unionSet(edge[0], edge[1]);
}
return new int[0];
}
private int find(int target) {
if (target == fa[target]) {
return target;
}
return fa[target] = find(fa[target]);
}
private void unionSet(int x, int y) {
x = find(x);
y = find(y);
if (x != y) {
fa[y] = x;
}
}
}
|
/* Treerow.java
Purpose:
Description:
History:
Wed Jul 6 18:56:22 2005, Created by tomyeh
Copyright (C) 2005 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.zul;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.UiException;
import org.zkoss.zul.impl.XulElement;
/**
* A treerow.
* <p>Default {@link #getZclass}: z-treerow (since 5.0.0)
* @author tomyeh
*/
public class Treerow extends XulElement implements org.zkoss.zul.api.Treerow {
public Treerow() {
}
/** Instantiates a treerow with a treecel holding the given label.
* @since 5.0.8
*/
public Treerow(String label) {
setLabel(label);
}
/** Returns the {@link Tree} instance containing this element.
*/
public Tree getTree() {
for (Component p = this; (p = p.getParent()) != null;)
if (p instanceof Tree)
return (Tree)p;
return null;
}
/** Returns the {@link Tree} instance containing this element.
* @since 3.5.2
*/
public org.zkoss.zul.api.Tree getTreeApi() {
return getTree();
}
/** Returns the level this cell is. The root is level 0.
*/
public int getLevel() {
final Component parent = getParent();
return parent != null ? ((Treeitem)parent).getLevel(): 0;
}
/** Returns the {@link Treechildren} associated with this
* {@link Treerow}.
* In other words, it is {@link Treeitem#getTreechildren} of
* {@link #getParent}.
* @since 2.4.1
* @see Treechildren#getLinkedTreerow
*/
public Treechildren getLinkedTreechildren() {
final Component parent = getParent();
return parent != null ? ((Treeitem)parent).getTreechildren(): null;
}
/** Returns the {@link Treechildren} associated with this
* {@link Treerow}.
* In other words, it is {@link Treeitem#getTreechildren} of
* {@link #getParent}.
* @since 3.5.2
* @see Treechildren#getLinkedTreerow
*/
public org.zkoss.zul.api.Treechildren getLinkedTreechildrenApi() {
return getLinkedTreechildren();
}
/** Returns the label of the {@link Treecell} it contains, or null
* if no such cell.
* @since 5.0.8
*/
public String getLabel() {
final Treecell cell = (Treecell)getFirstChild();
return cell != null ? cell.getLabel(): null;
}
/** Sets the label of the {@link Treecell} it contains.
*
* <p>If treecell are not created, we automatically create it.
*
* <p>Notice that this method will create a treecell automatically
* if they don't exist.
* @since 5.0.8
*/
public void setLabel(String label) {
autoFirstCell().setLabel(label);
}
/** Returns the image of the {@link Treecell} it contains, or null
* if no such cell.
* @since 5.0.8
*/
public String getImage() {
final Treecell cell = (Treecell)getFirstChild();
return cell != null ? cell.getImage(): null;
}
/** Sets the image of the {@link Treecell} it contains.
*
* <p>If treecell are not created, we automatically create it.
*
* <p>Notice that this method will create a treerow and treecell automatically
* if they don't exist.
* @since 5.0.8
*/
public void setImage(String image) {
autoFirstCell().setImage(image);
}
private Treecell autoFirstCell() {
Treecell cell = (Treecell)getFirstChild();
if (cell == null) {
cell = new Treecell();
cell.applyProperties();
cell.setParent(this);
}
return cell;
}
//-- Component --//
public String getZclass() {
return _zclass == null ? "z-treerow" : _zclass;
}
public void smartUpdate(String attr, Object value) {
super.smartUpdate(attr, value);
}
public void beforeParentChanged(Component parent) {
if (parent != null && !(parent instanceof Treeitem))
throw new UiException("Wrong parent: "+parent);
super.beforeParentChanged(parent);
}
public void beforeChildAdded(Component child, Component refChild) {
if (!(child instanceof Treecell))
throw new UiException("Unsupported child for tree row: "+child);
super.beforeChildAdded(child, refChild);
}}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* @author Lakindu Oshadha (lakinduoshadha98@gmail.com)
*/
public class Identity {
/**
* Prints elements with those have same index as their values (Index/s i such that a[ i ] = i)
*
* @param arr InputArray(In ascending order)
* @param p FirstIndex
*/
static void printIdentityEl(int[] arr, int p) {
// Checking conditions & Calling printIdentityEl recursively
if (p < arr.length && p >= 0) {
if(arr[p] == p) {
System.out.print(p + " "); // Prints tha values
}
if(p >= arr[p]) {
printIdentityEl(arr,p+1); // Calls printIdentityEl recursively
}
}
}
/**
* Gives a brief introduction to user
* Takes the array and the size of the array from the user.
*
* @return inputArray
* @throws IOException
*/
public static int[] getInputArray() throws IOException{
// Giving a brief Introduction to the user
System.out.print("This program will find elements with those have same index as their values" +
" in given Array Using recursive Algorithm .\n" + "n - " +
"No. of integers in input Array.\n" + "\nEnter input arr size(n): ");
// Getting input size from user
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
// Getting the Input arr from the user
int[] arr = new int[n];
int inputSize = 0;
String input;
do {
System.out.print("Enter " + n + " integers, separated using space (n1 n2 n3 ...): ");
input = reader.readLine();
inputSize = input.split(" ").length;
} while (inputSize != n);
String[] numbers = input.split(" ");
for (int j = 0; j < n; j++) {
arr[j] = Integer.parseInt(numbers[j]);
}
return arr;
}
/**
* Prints the given arr
*
* @param arr arr which is to be printed
*/
public static void printInputArray(int[] arr){
System.out.println("\n" + "Input Array : " + Arrays.toString(arr) );
}
/**
* main
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
int[] inputArr = getInputArray(); // Getting the array from the user
printInputArray(inputArr); // Prints input array.
System.out.print("Index/s i such that a[ i ] = i : ");
printIdentityEl(inputArr,0);// Prints Index/s i such that a[ i ] = i
System.out.println("\n");
}
}
|
package wirusy;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class WirusSpecyficzny extends Wirus {
private final Nukleotyd[] nukleotydyPoMutacji;
private final int[] pozycjePodatneNaMutacje;
public WirusSpecyficzny(Nukleotyd[] kwasNukleinowy, int mutacjeNaMiesiac,
int[] pozycjePodatneNaMutacje,
Nukleotyd[] nukleotydyPoMutacji) {
super(kwasNukleinowy, mutacjeNaMiesiac);
this.pozycjePodatneNaMutacje = pozycjePodatneNaMutacje;
this.nukleotydyPoMutacji = Arrays.copyOf(nukleotydyPoMutacji, nukleotydyPoMutacji.length);
}
@Override
protected void symulujMutacje() {
Random r = new Random();
int pozycja = pozycjePodatneNaMutacje[r.nextInt(pozycjePodatneNaMutacje.length)];
Nukleotyd zmutowanyNukleotyd = nukleotydyPoMutacji[r.nextInt(nukleotydyPoMutacji.length)];
while (zmutowanyNukleotyd == kwasNukleinowy[pozycja]) {
// w kaลผdym obrocie co najmniej 50% szans na przerwanie pฤtli
// (zatem w praktyce zakoลczy siฤ w rozsฤ
dnym czasie)
zmutowanyNukleotyd = nukleotydyPoMutacji[r.nextInt(nukleotydyPoMutacji.length)];
}
kwasNukleinowy[pozycja] = zmutowanyNukleotyd;
}
}
|
package ffm.slc.model.enums;
/**
* Reflects the type of employment or contract.
*/
public enum EmploymentStatusType {
PROBATIONARY("Probationary"),
CONTRACTUAL("Contractual"),
SUBSTITUTE_TEMPORARY("Substitute/temporary"),
TENURED_OR_PERMANENT("Tenured or permanent"),
VOLUNTEER_NO_CONTRACT("Volunteer/no contract"),
EMPLOYED_OR_AFFILIATED_WITH_OUTSIDE_ORGANIZATION("Employed or affiliated with outside organization"),
CONTINGENT_UPON_FUNDING("Contingent upon funding"),
NON_CONTRACTUAL("Non-contractual"),
SELF_EMPLOYED_PART_TIME("Self-employed part-time"),
EMPLOYED_OR_AFFILIATED_WITH_OUTSIDE_AGENCY_PART_TIME("Employed or affiliated with outside agency part-time"),
OTHER("Other");
private String prettyName;
EmploymentStatusType(String prettyName) {
this.prettyName = prettyName;
}
@Override
public String toString() {
return prettyName;
}
}
|
package com.scripbox.controller;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.scripbox.exception.ApplicationException;
import com.scripbox.filter.JwtTokenUtil;
import com.scripbox.model.Challenge;
import com.scripbox.model.Employee;
import com.scripbox.model.GenericResponse;
import com.scripbox.service.EmployeeChallengeService;
@RestController
@RequestMapping("/employee")
public class ChallengesController {
@Autowired
private EmployeeChallengeService service;
@Autowired
JwtTokenUtil jwttokenUtil;
@PostMapping(value = "/challenges", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getaccountStatement(@RequestBody List<Challenge> challenges , HttpServletRequest request)
throws ApplicationException, NoSuchAlgorithmException {
String userName = jwttokenUtil.getUsernameFromToken(request.getHeader("Authorization").substring(7)).toString();
return new ResponseEntity<GenericResponse>(
service.saveChallenges(challenges, userName),HttpStatus.CREATED);
}
@PostMapping(value = "/vote/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> upVoteChallenge(HttpServletRequest request, @PathParam(value = "id") String id)
throws ApplicationException, NoSuchAlgorithmException {
String userName = jwttokenUtil.getUsernameFromToken(request.getHeader("Authorization").substring(7)).toString();
return new ResponseEntity<GenericResponse>(
service.upVoteChallenge(id, userName),HttpStatus.ACCEPTED);
}
@PostMapping(value = "/collaborate/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> collaborateChallenge(HttpServletRequest request, @PathParam(value = "id") String id)
throws ApplicationException, NoSuchAlgorithmException {
String userName = jwttokenUtil.getUsernameFromToken(request.getHeader("Authorization").substring(7)).toString();
return new ResponseEntity<GenericResponse>(
service.collaborateChallenge(id, userName),HttpStatus.ACCEPTED);
}
@GetMapping(value = "/collaboration/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getChallengeColaborations(HttpServletRequest request, @PathParam(value = "id") String id)
throws ApplicationException, NoSuchAlgorithmException {
String userName = jwttokenUtil.getUsernameFromToken(request.getHeader("Authorization").substring(7)).toString();
return new ResponseEntity<List<Employee>>(
service.getChallengeColaborations(id, userName),HttpStatus.OK);
}
@GetMapping(value = "/challenges", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getChallenge(
@RequestParam(required = false, value = "creationDate") boolean creationDateSort,
@RequestParam(required = false, value = "voteCounts") boolean voteCountSort,
HttpServletRequest request)
throws ApplicationException, NoSuchAlgorithmException {
return new ResponseEntity<List<Challenge>>(service.getChallenges(creationDateSort,voteCountSort),HttpStatus.OK);
}
}
|
package com.example.shoji.bakingapp.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.example.shoji.bakingapp.R;
import com.example.shoji.bakingapp.pojo.Recipe;
import com.example.shoji.bakingapp.pojo.RecipeIngredient;
import com.example.shoji.bakingapp.provider.RecipeContract;
import com.example.shoji.bakingapp.provider.RecipeProvider;
import com.example.shoji.bakingapp.ui.RecipeActivity;
import com.example.shoji.bakingapp.utils.RecipeProviderUtils;
import java.util.ArrayList;
public class StackWidgetService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new StackRemoteViewsFactory(this.getApplicationContext(), intent);
}
}
class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
private Context mContext;
private Cursor mCursor;
public StackRemoteViewsFactory(Context context, Intent intent) {
mContext = context;
}
@Override
public void onCreate() {
}
@Override
public void onDestroy() {
if (mCursor != null)
mCursor.close();
}
@Override
public int getCount() {
if (mCursor == null) {
return 0;
}
return mCursor.getCount();
}
@Override
public RemoteViews getViewAt(int position) {
if (mCursor == null || mCursor.getCount() == 0) return null;
mCursor.moveToPosition(position);
String name = mCursor.getString(mCursor.getColumnIndex(RecipeContract.COLUMN_NAME));
String recipe_id = mCursor.getString(mCursor.getColumnIndex(RecipeContract.COLUMN_RECIPE_ID));
String servings = mCursor.getString(mCursor.getColumnIndex(RecipeContract.COLUMN_SERVINGS));
String image = mCursor.getString(mCursor.getColumnIndex(RecipeContract.COLUMN_IMAGE));
Recipe recipe = new Recipe();
recipe.setId(recipe_id);
recipe.setName(name);
recipe.setServings(servings);
recipe.setImage(image);
String _id = mCursor.getString(mCursor.getColumnIndex(RecipeContract._ID));
recipe.setIngredientList(RecipeProviderUtils.getIngredientsFromDb(mContext, _id));
recipe.setStepList(RecipeProviderUtils.getStepsFromDb(mContext, _id));
int layoutResId = R.layout.widget_ingredient_list;
RemoteViews views = new RemoteViews(mContext.getPackageName(), layoutResId);
// Put recipe as extra
Bundle extras = new Bundle();
extras.putParcelable(RecipeActivity.EXTRA_RECIPE_DATA, recipe);
// FillInIntent
Intent fillInIntent = new Intent();
fillInIntent.putExtras(extras);
//fillInIntent.setAction(RecipeActivity.ACTION_OPEN_INGREDIENT_LIST);
views.setOnClickFillInIntent(R.id.appwidget_text, fillInIntent);
StringBuffer sb = new StringBuffer();
sb.append(recipe.getName());
ArrayList<RecipeIngredient> ingredients = recipe.getIngredientList();
if(ingredients != null) {
for (RecipeIngredient ingredient : ingredients) {
String formatted = mContext.getString(R.string.recipe_formatted_ingredients,
ingredient.getQuantity(),
ingredient.getMeasure(),
ingredient.getDescription());
sb.append("\n").append(formatted);
}
}
views.setTextViewText(R.id.appwidget_text, sb.toString());
return views;
}
@Override
public RemoteViews getLoadingView() {
return null;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public void onDataSetChanged() {
if (mCursor != null) mCursor.close();
mCursor = mContext.getContentResolver().query(
RecipeProvider.Recipes.CONTENT_URI,
null,
null,
null,
null
);
}
}
|
package weight;
public class Elevator {
public static void main(String args[]) {
int Person; // int used most of the time if its to short go for LONG
int Limit;
int NoPeople;
int Remaining;
char Little; //this is just to use the char type and play with to upper case
char Big;
Person = 150;
Limit = 1400;
NoPeople =
Limit / Person;
Remaining =
Limit % Person; //% sign shows the number of items left after division.
Little = 'm';
Big = Character.toUpperCase(Little); //changing character from lower to upper case
// you can do the opposite using .to LowerCase
boolean AllTen = NoPeople >= 10;
System.out.print("You can fit ");
System.out.print(NoPeople);
System.out.println(" in the box.");//the 3 lines to this line can be condensed using +
System.out.println();
System.out.print("Can all 10 of us fit in the box? ");
System.out.println(AllTen + "!");
System.out.println();
System.out.println("You have " + Remaining + "Kg weight left.");
System.out.println();
System.out.println(Big);
}
}
|
package com.springtraining.form;
import java.util.List;
public class ParentForm {
private String month;
private List<String> monthList;
private List<TopForm> topFormList;
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public List<String> getMonthList() {
return monthList;
}
public void setMonthList(List<String> monthList) {
this.monthList = monthList;
}
public List<TopForm> getTopFormList() {
return topFormList;
}
public void setTopFormList(List<TopForm> topFormList) {
this.topFormList = topFormList;
}
} |
package com.github.fierioziy.particlenativeapi.api.particle.type;
import com.github.fierioziy.particlenativeapi.api.utils.Shared;
import org.bukkit.Material;
/**
* <p>Class used to represent item particle type that needs an item type.</p>
*
* <p>It provides a non-reflective <code>of</code> method overloads
* to construct <code>ParticleTypeMotion</code> with selected item type.</p>
*
* <p>All <code>of</code> methods does not validate parameters in any way.</p>
*
* <p><b>IMPORTANT NOTE</b>: All methods annotated with {@link Shared} annotation
* caches and returns exactly one and the same instance with changed state between method calls.
* For an independent copy of returned instances, check <code>detachCopy</code> methods on them.</p>
*
* @see ParticleTypeMotion
*/
public interface ParticleTypeItemMotion {
/**
* <p>Selects an item this particle should represents.</p>
*
* <p>Parameters are not validated in any way.</p>
*
* <p><b>This method is overridden by dynamically generated
* subclasses.</b></p>
*
* @param item a {@link Material} object representing
* desired item type.
* @return a valid {@link ParticleTypeMotion} object with selected
* item type.
*/
@Shared ParticleTypeMotion of(Material item);
/**
* <p>Checks if this particle is supported by this Spigot version.</p>
*
* <p><b>This method is overridden by dynamically generated
* subclasses.</b></p>
*
* @return true if this particle is supported by
* this Spigot version, false otherwise.
*/
boolean isPresent();
}
|
package com.xi.regexDemo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/*
* ๅญ็ฌฆไธฒ"$ \"ไธญ็$ไธ\ๅญ็ฌฆไบๆขไฝ็ฝฎ
*/
public class SpecialCharReplace {
private static String REGEX = "([A-Z])ๅฎค";
public static void main(String[] args) {
// String str = "ๆฑๆตทๆฐๆ(B)11ๅนข134ๅท301ๅฎคAๅฎค";
// System.out.println(str.replaceAll("ๆฑๆตทๆฐๆ(B)11ๅนข134ๅท301ๅฎค", ""));
//// String str = "*adCVs*34_a _09_b5*[/435^*&ๅๆฑ ()^$$&*).{}+.|.)%%*(*.ไธญๅฝ}34{45[]12.fd'*&999ไธ้ขๆฏไธญๆ็ๅญ็ฌฆ๏ฟฅโฆโฆ{}ใใใ๏ผ๏ผโโโโ๏ผ";
//// System.out.println(str);
// System.out.println(StringFilter(str));
// System.out.println (compare ("ๅพทๆฆ่ทฏ375ๅผ26-27ๅท408ๅฎคAๅฎค", "1ST"));
String str="็พๅนณ่ทฏ696ๅผ11ๅท1804ๅฎคAๅฎค1SY";
String s = str.replaceAll("[^a-zA-Z].+$", "");
System.out.println("S:"+s);
System.out.println("findLetter(str):"+findLetter(str));
}
public static String StringFilter(String str) throws PatternSyntaxException {
// ๅชๅ
่ฎธๅญๆฏๅๆฐๅญ
// String regEx = "[^a-zA-Z0-9]";
// ๆธ
้คๆๆๆ็นๆฎๅญ็ฌฆ
String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~๏ผ@#๏ฟฅ%โฆโฆ&*๏ผ๏ผโโ+|{}ใใโ๏ผ๏ผโโโใ๏ผใ๏ผ]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
/**ๆฏ่พไธคไธชๅญ็ฌฆไธฒไธญๆฏๅฆๆ็ธๅๅ
็ด
* @param f
* @param s
* @return
*/
private static String compare(String f, String s) {
int count = 0;
String str="";//็ธๅๅ
็ด
String str2="";//ไธๅๅ
็ด
for (int i = 0; i < f.length(); i++) {
for (int j = 0; j < s.length(); j++) {
if (f.charAt(i) == s.charAt(j)) {
count++;
str+=f.charAt(i);
}
}
}
char[] a1 = f.toCharArray();
char[] b1 = s.toCharArray();
int c = a1.length<b1.length? a1.length:b1.length;
for(int i=0;i<c-1;i++){
if(a1[i]!=b1[i]){
str2+=f.charAt(i);
// break;
}
}
return str2;
}
public static String findLetter(String str) {
if(str == null || str.length() == 0) {
return str;
}
char[] chs = str.toCharArray();
int k = 0;
String str2="";//็ธๅๅ
็ด
for(int i = 0; i < chs.length; i++) {
if(isAsciiLetter(chs[i])) {
// break;
str2+=chs[i];
}
k++;
}
// return new String(chs, 0, k);
return str2;
}
private static boolean isAsciiLetter(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
private static boolean isAsciiLetter(String str) {
return Pattern.compile(REGEX).matcher(str).find();
}
} |
package com.example.chordnote.ui.period;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.chordnote.ui.base.BaseFragment;
import com.example.chordnote.ui.period.comment.CommentFragment;
import com.example.chordnote.ui.period.periodcontent.PeriodContentFragment;
import com.example.chordnote.ui.period.question.QuestionFragment;
import java.util.ArrayList;
import java.util.List;
public class PeriodPagerAdapter extends FragmentPagerAdapter {
private final int PAGE_NUM = 3;
private List<BaseFragment> fragments;
private List<String> tabTitle;
public PeriodPagerAdapter(@NonNull FragmentManager fm, List<BaseFragment> fragments, List<String> tabTitle) {
super(fm);
this.fragments = fragments;
this.tabTitle = tabTitle;
}
@Override
public Fragment getItem(int position){
return fragments.get(position);
}
@Override
public int getCount(){
return PAGE_NUM;
}
@Override
public CharSequence getPageTitle(int position){
return tabTitle.get(position);
}
}
|
package br.com.gaia.service;
import java.util.List;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import br.com.gaia.model.Gaia;
public class GaiaService {
private static WebTarget resource = ClientBuilder.newBuilder().build().target("https://gaia-discover-api.herokuapp.com/api/locations/discover/local");
public List<Gaia> getGaia(String address, String local) {
return resource.queryParam("address", address).queryParam("local", local).request(MediaType.APPLICATION_JSON).get(new GenericType<List<Gaia>>() {});
}
} |
package utn.sau.hp.com.modelo;
// Generated 04/12/2014 23:31:51 by Hibernate Tools 3.6.0
import java.util.HashSet;
import java.util.Set;
/**
* Localidades generated by hbm2java
*/
public class Localidades implements java.io.Serializable {
private Integer id;
private Departamentos departamentos;
private String nombre;
private Set empresases = new HashSet(0);
private Set firmanteses = new HashSet(0);
private Set alumnoses = new HashSet(0);
public Localidades() {
}
public Localidades(Departamentos departamentos) {
this.departamentos = departamentos;
}
public Localidades(Departamentos departamentos, String nombre, Set empresases, Set firmanteses, Set alumnoses) {
this.departamentos = departamentos;
this.nombre = nombre;
this.empresases = empresases;
this.firmanteses = firmanteses;
this.alumnoses = alumnoses;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Departamentos getDepartamentos() {
return this.departamentos;
}
public void setDepartamentos(Departamentos departamentos) {
this.departamentos = departamentos;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Set getEmpresases() {
return this.empresases;
}
public void setEmpresases(Set empresases) {
this.empresases = empresases;
}
public Set getFirmanteses() {
return this.firmanteses;
}
public void setFirmanteses(Set firmanteses) {
this.firmanteses = firmanteses;
}
public Set getAlumnoses() {
return this.alumnoses;
}
public void setAlumnoses(Set alumnoses) {
this.alumnoses = alumnoses;
}
}
|
package view.model;
import model.interfaces.Player;
/*
* Player state is a class which is instantiated when a new player is added. Same ID as player it is referencing.
* Player state objects exist to check if players have been spun once, record win/loss etc.
*/
public class PlayerWithState {
private Player player;
//spun is set as true when a player has spun once a round and reset after spinner spins
private boolean spun = false;
//won and lost integers
private int won = 0;
private int lost = 0;
//points integers to check if a player has won or lost
private int currentPoints;
private int betPoints;
private int previousPoints;
public PlayerWithState(Player player) {
this.player = player;
}
//********************************************//
public String getPlayerWithStateId() {
return player.getPlayerId();
}
public int getPlayerWithStatePoints() {
return player.getPoints();
}
public int getPlayerWithBetPoints() {
return player.getBet();
}
//********************************************//
public boolean getSpun() {
return this.spun;
}
public void setSpun(boolean spun) {
this.spun = spun;
}
//********************* Getters and Setters ***********************//
public int getWon() {
return this.won;
}
public void incrementWon() {
this.won++;
}
public int getLost() {
return this.lost;
}
public void incrementLost() {
this.lost++;
}
//********************** Getters and setters **********************//
public int getPreviousPoints() {
return this.previousPoints;
}
public void setPreviousPoints(int previous) {
this.previousPoints = previous;
}
public int getBetPoints() {
return this.betPoints;
}
public void setBetPoints(int bet) {
this.betPoints = bet;
}
public int getCurrentPoints() {
return this.currentPoints;
}
public void setCurrentPoints(int currentPoints) {
this.currentPoints = currentPoints;
}
//********************************************//
}
|
package com.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Given a list of words (without duplicates),
* ็ปไธไธฒๆฒกๆ็ธๅๅญ็ฌฆ็ๅญ็ฌฆ็ป
* please write a program that returns all concatenated words in the given list of words.
* ๅฎ็ฐไธไธช็ฎๆณ๏ผ่ฟๅๅ่กจไธญๅฎๅ
จ็ฑๅ
ถๅฎๅญ็ฌฆ็ปๆ็ๅญ็ฌฆ
*
* A concatenated word is defined as a string
* ็ฑๅ
ถๅฎๅญ็ฌฆ็ปๆ็ๅญ็ฌฆๅซไนๆฏ
* that is comprised entirely of at least two shorter words in the given array.
* ่ฏฅๅญ็ฌฆ๏ผๆฏๅ่กจไธญๅ
ถๅฎไธคไธชไปฅไธ(ๅ
ๅซไธคไธช)็ๅญ็ฌฆ๏ผ็ปๆ
*
* Example:
* Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
* Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
*
* Note:
* The number of elements of the given array will not exceed 10,000
* The length sum of elements in the given array will not exceed 600,000.
* All the input string will only include lower case letters.
* The returned elements order does not matter.
*
* 1๏ผๅ
ๆๅญ็ฌฆ้ฟ็ญๆๅบ๏ผ็ญ->้ฟ
* 2๏ผTree็ปๆๆดๆ๏ผไธไธชไธช็ๆทปๅ (็ฌ็ซ็๏ผๅๅ ๅ
ฅ๏ผๅฆๅๅ ๅ
ฅ)
*
* Treeๆ ็ๅคๆจกๅผไธฒ๏ผๅๅไธไธปไธฒ๏ผๅน้
้ฎ้ข
*
* @author YLine
*
* 2019ๅนด8ๆ12ๆฅ ไธๅ2:14:23
*/
public class SolutionA
{
public List<String> findAllConcatenatedWordsInADict(String[] words)
{
if (words.length < 3)
{
return new ArrayList<>();
}
Arrays.sort(words, new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
return o1.length() - o2.length();
}
});
System.out.println(Arrays.toString(words));
List<String> result = new ArrayList<>();
NTree root = new NTree();
addWord(root, words[0]);
for (int i = 1; i < words.length; i++)
{
if (isMatch(root, words[i]))
{
result.add(words[i]);
}
else
{
addWord(root, words[i]);
}
}
System.out.println(Arrays.toString(result.toArray()));
return result;
}
/**
* .ๅฝๅๅญ็ฌฆ๏ผๆฏๅฆ็ฑๅ
ถๅฎๅญ็ฌฆๆๆ
* @param root ๅทฒๆทปๅ ็ๅ
ๅฎน
* @param words ๅฝๅ็ๅ่ฏ
* @return ๆฏๅฆๆปก่ถณ
*/
private boolean isMatch(NTree root, String words)
{
return isMatch(root, words, root, 0, 0);
}
/**
*
* @param root ๆ น่็น
* @param words ๅฝๅ็ๅ่ฏ
*
* @param node ๅฝๅ่็น
* @param index ๅฝๅๅ่ฏ็ไฝ็ฝฎ
* @param size ๅทฒ็ปๅ
ๅซ็ๅ่ฏๆฐ้
* @return
*/
private boolean isMatch(NTree root, String words, NTree node, int index, int size)
{
NTree value = node.getValue(words.charAt(index));
if (null == value)
{
return false;
}
// ้ๅๅฐๆๅไธไธช่็น
if (index == words.length() - 1)
{
// ๅฝๆๅไธไธชๅญๆฏๆถ๏ผ่ฆๆฑๅฝๅ่็นไนๆฏๅ
ถไปๅ่ฏ็็ปๆ๏ผๅนถไธๅทฒ็ปๆๅ
ถไปๅ่ฏไบ
return (value.isWord && size >= 1);
}
if (value.isWord)
{
// ๅฝๅ่็นๆฏๅ่ฏ
boolean current = isMatch(root, words, value, index + 1, size); // ็ปง็ปญๅพไธ้ๅ
return current || isMatch(root, words, root, index + 1, size + 1); // ไปๆฐ็ๅฐๆนๅผๅง้ๅ
}
else
{
// ๅฝๅ่็นไธๆฏๅ่ฏ
return isMatch(root, words, value, index + 1, size);
}
}
/**
* .ๅฝ๏ผๆฃๆฅไธๆฏ็ฑ๏ผไธคไธชๅไปฅไธ็ปๆๆถ๏ผๆทปๅ ๅฐNTreeไธญ
* @param root ๆ น่็น
* @param words ๆทปๅ ็ๅ่ฏ
*/
private void addWord(NTree root, String words)
{
if (words.length() == 0)
{
return;
}
NTree node = root;
for (int i = 0; i < words.length(); i++)
{
node = node.add(words.charAt(i));
}
node.isWord = true;
}
private static class NTree
{
private boolean isWord; // ่ฏฅ่็นๆฏๅฆๆฏไธไธชๅ่ฏ็็ปๅฐพ
private Map<Character, NTree> valueMap; // ่ฏฅ่็น็ๅญๅ
ๅฎน
private NTree()
{
this.isWord = false;
}
public NTree add(char value)
{
if (null == valueMap)
{
valueMap = new HashMap<>();
}
if (valueMap.containsKey(value))
{
return valueMap.get(value);
}
else
{
NTree child = new NTree();
valueMap.put(value, child);
return child;
}
}
public NTree getValue(char value)
{
if (null == valueMap)
{
return null;
}
return valueMap.get(value);
}
}
}
|
package com.example;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
public class DatabaseFromFile extends Activity {
private static final int DLG_FONTFAILED = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView vR = (TextView) findViewById(R.id.FontViewR); // 1
TextView vBI = (TextView) findViewById(R.id.FontViewBI);
try {
InputStream dbIn = R.asset.databasefile;
new File("/data/data/com/com.example/databases").mkdirs();
try (FileOutputStream os = openFileOutput("databases/prefabdatabase", Context.MODE_PRIVATE)) {
// read from asset, write to os
}
} catch (RuntimeException e) {
showDialog(DLG_FONTFAILED);
}
}
@Override
protected Dialog onCreateDialog(int id, Bundle args) {
switch (id) {
case DLG_FONTFAILED:
return new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle(R.string.font_fail_title)
.setMessage(R.string.font_fail_text)
.setNeutralButton("OK",
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.exit(1);
}
}).create();
default:
return super.onCreateDialog(id, args);
}
}
}
|
package rs2.model.game.world;
import java.util.HashMap;
import java.util.Map;
import rs2.model.game.entity.Entity;
import rs2.model.game.entity.Position;
import rs2.model.game.entity.ground.GroundItem;
import rs2.model.game.entity.ground.GroundObject;
/**
* Holds and manages the active Regions of the game world.
* @author Jake Bellotti
* @since 1.0
*/
public class RegionManager {
private static final Map<String, Region> activeRegions = new HashMap<>();
private static final int REGION_SIZE = 16;
/**
* Locates the region from a {@link Position}.
* WARNING this will return a {@value null} value if the {@link Region} is not found.
* @param position
* @return
*/
public static final Region findRegion(final Position position) {
return activeRegions.get(getKey(position));
}
/**
* Finds whether or not an active region exists at a coordinate.
* @param position
* @return
*/
public static final boolean regionExists(final Position position) {
return activeRegions.containsKey(getKey(position));
}
/**
* Promises a non-null Region instance. If there isn't currently a region for the specified
* <code>Position</code>, one will be created and returned.
* @param position
* @return
*/
public static final Region createIfNotPresent(final Position position) {
final Region region = findRegion(position);
if(region == null) {
return createRegion(position);
}
return region;
}
/**
* If there is no active region for the given position, creates a new one and stores it in the map.
* @param position
*/
public static final Region createRegion(final Position position) {
return activeRegions.put(getKey(position), new Region());
}
/**
* Creates an array of all of the surrounding Regions, containing also null values, of regions
* that do and don't exist, and may or may not have entities inside of them.
* @param pos
* @return An 8 value array of the surrounding regions.
*/
public Region[] getSurroundingRegions(final Position pos) {
Region[] regions = new Region[8];
regions[0] = findRegion(new Position(pos.getX(), pos.getY() + REGION_SIZE, pos.getZ()));
regions[1] = findRegion(new Position(pos.getX(), pos.getY() - REGION_SIZE, pos.getZ()));
regions[2] = findRegion(new Position(pos.getX() - REGION_SIZE, pos.getY() + REGION_SIZE, pos.getZ()));
regions[3] = findRegion(new Position(pos.getX() + REGION_SIZE, pos.getY() + REGION_SIZE, pos.getZ()));
regions[4] = findRegion(new Position(pos.getX() - REGION_SIZE, pos.getY() - REGION_SIZE, pos.getZ()));
regions[5] = findRegion(new Position(pos.getX() + REGION_SIZE, pos.getY() - REGION_SIZE, pos.getZ()));
regions[6] = findRegion(new Position(pos.getX() + REGION_SIZE, pos.getY(), pos.getZ()));
regions[7] = findRegion(new Position(pos.getX() - REGION_SIZE, pos.getY(), pos.getZ()));
return regions;
}
/**
* Generates the key for a region. The key is 'x_y' where the x and y are replaced with the actual position.
* @param position
* @return
*/
public static final String getKey(final Position position) {
return new String((position.getX()/REGION_SIZE) +"_" + (position.getY()/REGION_SIZE));
}
/**
* Adds an Entity to the {@link Region} that it is in. Automatically creates the Region
* and adds the Entity if the Region doesn't exist.
* @param entity
*/
public static final void addToRegion(Entity entity) {
Region region = findRegion(entity.getPosition());
if(region == null) {
region = createRegion(entity.getPosition());
}
switch(entity.getEntityType()) {
case GAMEOBJECT:
region.addGroundObject((GroundObject) entity);
break;
case GROUNDITEM:
region.addGroundItem((GroundItem) entity);
break;
default:
break;
}
}
} |
package alien4cloud.tosca.parser.impl.advanced;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.nodes.Node;
import alien4cloud.component.ICSARRepositorySearchService;
import alien4cloud.model.components.AbstractPropertyValue;
import alien4cloud.model.components.CSARDependency;
import alien4cloud.model.components.FunctionPropertyValue;
import alien4cloud.model.components.IndexedInheritableToscaElement;
import alien4cloud.model.components.IndexedModelUtils;
import alien4cloud.model.components.IndexedNodeType;
import alien4cloud.model.components.IndexedToscaElement;
import alien4cloud.model.components.PropertyDefinition;
import alien4cloud.model.components.PropertyValue;
import alien4cloud.model.topology.NodeGroup;
import alien4cloud.model.topology.NodeTemplate;
import alien4cloud.model.topology.Topology;
import alien4cloud.paas.wf.AbstractActivity;
import alien4cloud.paas.wf.AbstractStep;
import alien4cloud.paas.wf.NodeActivityStep;
import alien4cloud.paas.wf.Workflow;
import alien4cloud.paas.wf.WorkflowsBuilderService;
import alien4cloud.paas.wf.WorkflowsBuilderService.TopologyContext;
import alien4cloud.paas.wf.util.WorkflowUtils;
import alien4cloud.tosca.model.ArchiveRoot;
import alien4cloud.tosca.parser.IChecker;
import alien4cloud.tosca.parser.ParsingContextExecution;
import alien4cloud.tosca.parser.ParsingError;
import alien4cloud.tosca.parser.ParsingErrorLevel;
import alien4cloud.tosca.parser.ToscaParsingUtil;
import alien4cloud.tosca.parser.impl.ErrorCode;
import alien4cloud.tosca.properties.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException;
import alien4cloud.tosca.properties.constraints.exception.ConstraintViolationException;
import alien4cloud.utils.services.ConstraintPropertyService;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
@Component
public class TopologyChecker implements IChecker<Topology> {
private static final String KEY = "topologyChecker";
@Resource
private ICSARRepositorySearchService searchService;
@Resource
private ConstraintPropertyService constraintPropertyService;
@Resource
private WorkflowsBuilderService workflowBuilderService;
@Override
public String getName() {
return KEY;
}
@Override
public void before(ParsingContextExecution context, Node node) {
ArchiveRoot archiveRoot = (ArchiveRoot) context.getRoot().getWrappedInstance();
// we need that node types inherited stuffs have to be merged before we start parsing node templates and requirements
mergeHierarchy(archiveRoot.getArtifactTypes(), archiveRoot);
mergeHierarchy(archiveRoot.getCapabilityTypes(), archiveRoot);
mergeHierarchy(archiveRoot.getNodeTypes(), archiveRoot);
mergeHierarchy(archiveRoot.getDataTypes(), archiveRoot);
mergeHierarchy(archiveRoot.getRelationshipTypes(), archiveRoot);
}
@Override
public void check(final Topology instance, ParsingContextExecution context, Node node) {
if (instance.isEmpty()) {
// if the topology doesn't contains any node template it won't be imported so add a warning.
context.getParsingErrors().add(
new ParsingError(ParsingErrorLevel.WARNING, ErrorCode.EMPTY_TOPOLOGY, null, node.getStartMark(), null, node.getEndMark(), ""));
}
final ArchiveRoot archiveRoot = (ArchiveRoot) context.getRoot().getWrappedInstance();
Set<CSARDependency> dependencies = archiveRoot.getArchive().getDependencies();
if (dependencies != null) {
instance.setDependencies(dependencies);
}
// here we need to check that the group members really exist
if (instance.getGroups() != null && !instance.getGroups().isEmpty()) {
int i = 0;
for (NodeGroup nodeGroup : instance.getGroups().values()) {
nodeGroup.setIndex(i++);
Iterator<String> groupMembers = nodeGroup.getMembers().iterator();
while (groupMembers.hasNext()) {
String nodeTemplateId = groupMembers.next();
NodeTemplate nodeTemplate = instance.getNodeTemplates().get(nodeTemplateId);
if (nodeTemplate == null) {
// add an error to the context
context.getParsingErrors().add(
new ParsingError(ParsingErrorLevel.WARNING, ErrorCode.UNKOWN_GROUP_MEMBER, null, node.getStartMark(), null, node.getEndMark(),
nodeTemplateId));
// and remove the member
groupMembers.remove();
} else {
Set<String> groups = nodeTemplate.getGroups();
if (groups == null) {
groups = Sets.newHashSet();
nodeTemplate.setGroups(groups);
}
groups.add(nodeGroup.getName());
}
}
}
}
// check properties inputs validity
if (instance.getNodeTemplates() != null && !instance.getNodeTemplates().isEmpty()) {
for (Entry<String, NodeTemplate> nodeEntry : instance.getNodeTemplates().entrySet()) {
String nodeName = nodeEntry.getKey();
NodeTemplate nodeTemplate = nodeEntry.getValue();
if (nodeEntry.getValue().getProperties() == null) {
continue;
}
IndexedNodeType nodeType = ToscaParsingUtil.getNodeTypeFromArchiveOrDependencies(nodeTemplate.getType(), archiveRoot, searchService);
if (nodeType == null) {
// Already caught in NodeTemplateChecker
continue;
}
for (Entry<String, AbstractPropertyValue> propertyEntry : nodeEntry.getValue().getProperties().entrySet()) {
String propertyName = propertyEntry.getKey();
AbstractPropertyValue propertyValue = propertyEntry.getValue();
if (nodeType.getProperties() == null || !nodeType.getProperties().containsKey(propertyName)) {
context.getParsingErrors().add(
new ParsingError(ParsingErrorLevel.ERROR, ErrorCode.UNRECOGNIZED_PROPERTY, nodeName, node.getStartMark(), "Property "
+ propertyName + " does not exist in type " + nodeType.getElementId(), node.getEndMark(), propertyName));
continue;
}
PropertyDefinition propertyDefinition = nodeType.getProperties().get(propertyName);
if (propertyValue instanceof FunctionPropertyValue) {
FunctionPropertyValue function = (FunctionPropertyValue) propertyValue;
String parameters = function.getParameters().get(0);
// check get_input only
if (function.getFunction().equals("get_input")) {
if (instance.getInputs() == null || !instance.getInputs().keySet().contains(parameters)) {
context.getParsingErrors().add(
new ParsingError(ParsingErrorLevel.ERROR, ErrorCode.MISSING_TOPOLOGY_INPUT, nodeName, node.getStartMark(), parameters,
node.getEndMark(), propertyName));
}
}
} else if (propertyValue instanceof PropertyValue<?>) {
try {
constraintPropertyService.checkPropertyConstraint(propertyName, ((PropertyValue<?>) propertyValue).getValue(), propertyDefinition,
archiveRoot);
} catch (ConstraintValueDoNotMatchPropertyTypeException | ConstraintViolationException e) {
StringBuilder problem = new StringBuilder("Validation issue ");
if (e.getConstraintInformation() != null) {
problem.append("for " + e.getConstraintInformation().toString());
}
problem.append(e.getMessage());
context.getParsingErrors().add(
new ParsingError(ParsingErrorLevel.ERROR, ErrorCode.VALIDATION_ERROR, nodeName, node.getStartMark(), problem.toString(),
node.getEndMark(), propertyName));
}
}
}
}
}
// manage the workflows
TopologyContext topologyContext = workflowBuilderService.buildCachedTopologyContext(new TopologyContext() {
@Override
public Topology getTopology() {
return instance;
}
@Override
public <T extends IndexedToscaElement> T findElement(Class<T> clazz, String id) {
return ToscaParsingUtil.getElementFromArchiveOrDependencies(clazz, id, archiveRoot, searchService);
}
});
finalizeParsedWorkflows(topologyContext, context, node);
// workflowBuilderService.initWorkflows(topologyContext);
}
/**
* Called after yaml parsing.
*/
private void finalizeParsedWorkflows(TopologyContext topologyContext, ParsingContextExecution context, Node node) {
if (topologyContext.getTopology().getWorkflows() == null || topologyContext.getTopology().getWorkflows().isEmpty()) {
return;
}
for (Workflow wf : topologyContext.getTopology().getWorkflows().values()) {
wf.setStandard(WorkflowUtils.isStandardWorkflow(wf));
if (wf.getSteps() != null) {
for (AbstractStep step : wf.getSteps().values()) {
if (step.getFollowingSteps() != null) {
Iterator<String> followingIds = step.getFollowingSteps().iterator();
while (followingIds.hasNext()) {
String followingId = followingIds.next();
AbstractStep followingStep = wf.getSteps().get(followingId);
if (followingStep == null) {
followingIds.remove();
// TODO: add an error in parsing context ?
context.getParsingErrors().add(
new ParsingError(ParsingErrorLevel.WARNING, ErrorCode.UNKNWON_WORKFLOW_STEP, null, node.getStartMark(), null, node
.getEndMark(), followingId));
} else {
followingStep.addPreceding(step.getName());
}
}
}
if (step instanceof NodeActivityStep) {
AbstractActivity activity = ((NodeActivityStep) step).getActivity();
if (activity == null) {
// add an error ?
} else {
activity.setNodeId(((NodeActivityStep) step).getNodeId());
}
}
}
}
WorkflowUtils.fillHostId(wf, topologyContext);
int errorCount = workflowBuilderService.validateWorkflow(topologyContext, wf);
if (errorCount > 0) {
context.getParsingErrors().add(
new ParsingError(ParsingErrorLevel.WARNING, ErrorCode.WORKFLOW_HAS_ERRORS, null, node.getStartMark(), null, node.getEndMark(), wf
.getName()));
}
}
}
private <T extends IndexedInheritableToscaElement> void mergeHierarchy(Map<String, T> indexedElements, ArchiveRoot archiveRoot) {
if (indexedElements == null) {
return;
}
for (T element : indexedElements.values()) {
mergeHierarchy(element, archiveRoot);
}
}
private <T extends IndexedInheritableToscaElement> void mergeHierarchy(T indexedElement, ArchiveRoot archiveRoot) {
List<String> derivedFrom = indexedElement.getDerivedFrom();
if (derivedFrom == null) {
return;
}
Map<String, T> hierarchy = Maps.newHashMap();
for (String parentId : derivedFrom) {
T parentElement = (T) ToscaParsingUtil.getElementFromArchiveOrDependencies(indexedElement.getClass(), parentId, archiveRoot, searchService);
hierarchy.put(parentElement.getId(), parentElement);
}
List<T> hierarchyList = IndexedModelUtils.orderByDerivedFromHierarchy(hierarchy);
hierarchyList.add(indexedElement);
for (int i = 0; i < hierarchyList.size() - 1; i++) {
T from = hierarchyList.get(i);
T to = hierarchyList.get(i + 1);
if (Objects.equal(to.getArchiveName(), archiveRoot.getArchive().getName())
&& Objects.equal(to.getArchiveVersion(), archiveRoot.getArchive().getVersion())) {
// we only merge element that come with current archive (the one we are parsing).
// by this way, we don't remerge existing elements
IndexedModelUtils.mergeInheritableIndex(from, to);
}
}
}
}
|
// Copyright (C) 2013 Mihai Preda
package pepper.app;
import android.app.Application;
public class App extends Application {
static Application self;
public App() {
self = this;
}
static {
System.loadLibrary("pepper");
}
}
|
package priorityQueueThreeWays;
import java.util.NoSuchElementException;
/**<pre>
* ********************************************************************************************************************
* PriorityQueue.java Interface *
* ********************************************************************************************************************
*
* <strong>Description:</strong> In this class I defined the methods used for a priority queue: enqueue, dequeue,
* getSize, isEmpty, incementSize, decrementSize and peek. These methods will be implemented by the three
* different priority queues implementing this class.
*
* For information about the other classes created for this program, please see their javadocs.
*
*********************************************************************************************************************
* @author VagnerMachado - QCID 23651127 - Queens College - Spring 2018 *
*********************************************************************************************************************
*
* @param T - a generic type that extends the Comparable interface
*
*
*<a href="http://www.facebook.com/vagnermachado84"> Do you like this code? Let me know! </a>
*</pre>
*/
public interface PriorityQueue<T>
{
public void enqueue(T item)throws NoSuchElementException;
public T dequeue() throws NoSuchElementException;
public boolean isEmpty();
public int getSize();
public T peek() throws NoSuchElementException;
}
|
package io.papermc.hangar.config;
import io.papermc.hangar.security.metadatasources.GlobalPermissionSource;
import io.papermc.hangar.security.metadatasources.HangarMetadataSources;
import io.papermc.hangar.security.metadatasources.ProjectPermissionSource;
import io.papermc.hangar.security.voters.GlobalPermissionVoter;
import io.papermc.hangar.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.method.MethodSecurityMetadataSource;
import org.springframework.security.access.vote.AbstractAccessDecisionManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
@Configuration
@AutoConfigureBefore(SecurityConfig.class)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
private final PermissionService permissionService;
@Autowired
public MethodSecurityConfig(PermissionService permissionService) {
this.permissionService = permissionService;
}
@Override
protected MethodSecurityMetadataSource customMethodSecurityMetadataSource() {
return new HangarMetadataSources(new GlobalPermissionSource(), new ProjectPermissionSource());
}
@Override
protected AccessDecisionManager accessDecisionManager() {
AbstractAccessDecisionManager manager = (AbstractAccessDecisionManager) super.accessDecisionManager();
manager.getDecisionVoters().add(new GlobalPermissionVoter(permissionService));
return manager;
}
}
|
package com.pelephone_mobile.songwaiting.service.interfaces;
public interface ISWPopUpfacebook
{
public void onPublishFacebook();
}
|
package com.dhruvmail.com.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class test {
public static void main(String[] args) throws DocumentException {
String filename = "A:\\email\\invoice.pdf";
Rectangle pageSize = new Rectangle(780, 525);
Document document = new Document(pageSize);
OutputStream file = null;
try {
file = new FileOutputStream(new File(filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PdfWriter.getInstance(document, file);
//PdfWriter.getInstance(document, response.getOutputStream());
document.open();
float[] colsWidth1 = {1f, 1f, 1f,1f,1f}; // Code 1
//Image image = Image.getInstance(path+"employee/payslip/view/fly-hind.jpg");
PdfPTable table = new PdfPTable(colsWidth1);
table.getDefaultCell().setBorder(0);
table.setWidthPercentage(100); // Code 2
table.setHorizontalAlignment(Element.ALIGN_LEFT);//Code 3
table.addCell("");
table.addCell("");
table.addCell("This is a genaric PDF");
table.addCell("");
table.addCell("");
document.add(table);
document.add( Chunk.NEWLINE );
document.add( Chunk.NEWLINE );
float[] colsWidth_main = {1f, 1f, 1f}; // Code 1
table = new PdfPTable(colsWidth_main);
table.getDefaultCell().setBorder(0);
table.setWidthPercentage(100); // Code 2
table.setHorizontalAlignment(Element.ALIGN_LEFT);//Code 3
table.addCell("");
try {
table.addCell(Image.getInstance("A:\\email\\images\\birds.jpg"));
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
table.addCell("");
document.add(table);
float[] colsWidth = {1f, 1f, 1f, 1f}; // Code 1
table = new PdfPTable(colsWidth);
table.getDefaultCell().setBorder(0);
table.setWidthPercentage(100); // Code 2
table.setHorizontalAlignment(Element.ALIGN_LEFT);//Code 3
//table.addCell("Employee ID");
//table.addCell("00000");
table.addCell("Name");
table.addCell("00000");
table.addCell("Recieved from");
table.addCell("00000");
table.addCell("Designation");
table.addCell("00000");
table.addCell("Email of sender");
table.addCell("CarbonatedFiji@gmail.com");
table.addCell("This is a gernaric table heading");
table.addCell("0000");
table.addCell("This is a gernaric table heading");
table.addCell("0000");
document.add(table);
document.add( Chunk.NEWLINE );
document.add( Chunk.NEWLINE );
Paragraph p = new Paragraph();
//p.add("This is a genaric sentance");
// p.setAlignment(Element.ALIGN_CENTER);
document.add(p);
Paragraph p2 = new Paragraph();
p2.add("The birds on the top are a JPG "); //no alignment
document.add( Chunk.NEWLINE );
document.add(p2);
document.close();
}
}
|
package com.example.ontheleash.Fragments;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.ontheleash.R;
import com.example.ontheleash.adapters.EditDogAdapter;
import com.example.ontheleash.dataClasses.User;
import static android.app.Activity.RESULT_OK;
public class EditDogsFragment extends Fragment {
private User user;
private RecyclerView recycler;
private EditDogAdapter adapter;
private final int IMAGE_DIALOG_REQUEST_CODE = 201;
public static final int EXTERNAL_STORAGE_REQUEST_CODE = 202;
public EditDogsFragment() {
// Required empty public constructor
}
public EditDogsFragment(User user) {
this.user = user;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_dogs, container, false);
recycler = view.findViewById(R.id.recycler);
adapter = new EditDogAdapter(user.getDogs(), getActivity(), this);
recycler.setLayoutManager(new LinearLayoutManager(getContext()));
recycler.setAdapter(adapter);
DividerItemDecoration divider = new DividerItemDecoration(getContext(), RecyclerView.VERTICAL);
divider.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.recycler_divider_gray));
recycler.addItemDecoration(divider);
return view;
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && data != null && data.getData() != null){
Uri uri = data.getData();
adapter.items.get(requestCode).uri = uri;
adapter.notifyDataSetChanged();
}
}
} |
package slimeknights.tconstruct.library.traits;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.world.BlockEvent;
import slimeknights.tconstruct.library.Util;
import slimeknights.tconstruct.library.modifiers.Modifier;
import slimeknights.tconstruct.library.modifiers.ModifierAspect;
import slimeknights.tconstruct.library.modifiers.ModifierNBT;
import slimeknights.tconstruct.library.utils.TagUtil;
import slimeknights.tconstruct.library.utils.TinkerUtil;
// Trait and modifier in one! Useful because modifiers are saved as traits
public abstract class AbstractTrait extends Modifier implements ITrait {
public static final String LOC_Name = Modifier.LOC_Name;
public static final String LOC_Desc = Modifier.LOC_Desc;
//private final String identifier;
protected final int color;
public AbstractTrait(String identifier, TextFormatting color) {
this(identifier, Util.enumChatFormattingToColor(color));
}
public AbstractTrait(String identifier, int color) {
super(Util.sanitizeLocalizationString(identifier));
//this.identifier = Util.sanitizeLocalizationString(identifier);
this.color = color;
// we assume traits can only be applied once.
// If you want stacking traits you'll have to do that stuff yourself :P
this.addAspects(new ModifierAspect.SingleAspect(this));
}
@Override
public String getIdentifier() {
return identifier;
}
@Override
public String getLocalizedName() {
return Util.translate(LOC_Name, getIdentifier());
}
@Override
public String getLocalizedDesc() {
return Util.translate(LOC_Desc, getIdentifier());
}
@Override
public boolean isHidden() {
return false;
}
/* Updating */
@Override
public void onUpdate(ItemStack tool, World world, Entity entity, int itemSlot, boolean isSelected) {
}
@Override
public void onArmorTick(ItemStack tool, World world, EntityPlayer player) {
}
/* Mining & Harvesting */
@Override
public void miningSpeed(ItemStack tool, PlayerEvent.BreakSpeed event) {
}
@Override
public void beforeBlockBreak(ItemStack tool, BlockEvent.BreakEvent event) {
}
@Override
public void afterBlockBreak(ItemStack tool, World world, IBlockState state, BlockPos pos, EntityLivingBase player, boolean wasEffective) {
}
@Override
public void blockHarvestDrops(ItemStack tool, BlockEvent.HarvestDropsEvent event) {
}
/* Attacking */
@Override
public boolean isCriticalHit(ItemStack tool, EntityLivingBase player, EntityLivingBase target) {
return false;
}
@Override
public float damage(ItemStack tool, EntityLivingBase player, EntityLivingBase target, float damage, float newDamage, boolean isCritical) {
return newDamage;
}
@Override
public void onHit(ItemStack tool, EntityLivingBase player, EntityLivingBase target, float damage, boolean isCritical) {
}
@Override
public void afterHit(ItemStack tool, EntityLivingBase player, EntityLivingBase target, float damageDealt, boolean wasCritical, boolean wasHit) {
}
@Override
public float knockBack(ItemStack tool, EntityLivingBase player, EntityLivingBase target, float damage, float knockback, float newKnockback, boolean isCritical) {
return newKnockback;
}
@Override
public void onBlock(ItemStack tool, EntityPlayer player, LivingHurtEvent event) {
}
/* Durability and repairing */
@Override
public int onToolDamage(ItemStack tool, int damage, int newDamage, EntityLivingBase entity) {
return newDamage;
}
@Override
public int onToolHeal(ItemStack tool, int amount, int newAmount, EntityLivingBase entity) {
return newAmount;
}
@Override
public void onRepair(ItemStack tool, int amount) {
}
/* Modifier things */
// The name the modifier tag is saved under
public String getModifierIdentifier() {
return identifier;
}
@Override
public boolean canApplyCustom(ItemStack stack) {
// can only apply if the trait isn't present already
NBTTagList tagList = TagUtil.getTraitsTagList(stack);
int index = TinkerUtil.getIndexInList(tagList, this.getIdentifier());
// not present yet
return index < 0;
}
@Override
public void updateNBT(NBTTagCompound modifierTag) {
updateNBTforTrait(modifierTag, color);
}
public void updateNBTforTrait(NBTTagCompound modifierTag, int newColor) {
ModifierNBT data = ModifierNBT.readTag(modifierTag);
data.identifier = getModifierIdentifier();
data.color = newColor;
// we ensure at least lvl1 for compatibility with the level-aspect
if(data.level == 0) {
data.level = 1;
}
data.write(modifierTag);
}
@Override
public void applyEffect(NBTTagCompound rootCompound, NBTTagCompound modifierTag) {
// add the trait to the traitlist so it gets processed
NBTTagList traits = TagUtil.getTraitsTagList(rootCompound);
// if it's not already present
for(int i = 0; i < traits.tagCount(); i++) {
if(identifier.equals(traits.getStringTagAt(i))) {
return;
}
}
traits.appendTag(new NBTTagString(identifier));
TagUtil.setTraitsTagList(rootCompound, traits);
}
protected boolean isToolWithTrait(ItemStack itemStack) {
return TinkerUtil.hasTrait(TagUtil.getTagSafe(itemStack), this.getIdentifier());
}
}
|
package finalexam;
import java.util.Scanner;
public class blackjack {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String Answer = "YES" ;
System.out.println("Do you want play a Blackjack game ");
if(Answer.equalsIgnoreCase("yes")){
player hand1= new player();
System.out.print("Player hand value: " );
int playerhand = hand1.hand();
System.out.println( playerhand );
Dealer hand2= new Dealer();
System.out.print("Dealer hand value: " );
int dealerhand = hand2.hand();
System.out.println( dealerhand );
String hit;
do{
System.out.println("Do you want to hit, yes or no ");
hit = input.nextLine();
if(hit.equalsIgnoreCase("yes"))
{
playerhand += hand1.hand();
System.out.print("Player hand value: " );
System.out.println( playerhand );
}
}while (hit.equalsIgnoreCase("yes") && playerhand < 21);
if ( playerhand > 21 )
{
System.out.println("you lose " );
}
if ( dealerhand > 21 )
{
System.out.println("dealer lost " );
}
if ( playerhand <= 21 && playerhand > dealerhand)
{
System.out.println("you win " );
}
if ( dealerhand <= 21 && playerhand < dealerhand)
{
System.out.println("dealer wins " );
}
System.out.println("Thank you for playing ");
}
}
}
|
/*
* @(#) As2RoutingInfoActionTest.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package junit.com.esum.wp.as2.as2routinginfo.struts;
import java.io.File;
import java.util.List;
import com.esum.appframework.struts.action.eSumActionServlet;
import servletunit.struts.MockStrutsTestCase;
/**
*
* @author feelman5@esumtech.com
* @version $Revision: 1.1 $ $Date: 2008/03/24 09:42:49 $
*/
public class As2RoutingInfoActionTest extends MockStrutsTestCase {
protected void setUp() throws Exception {
super.setUp();
setContextDirectory(new File("web"));
setServletConfigFile("/WEB-INF/web.xml");
setActionServlet(new eSumActionServlet());
}
public void testAppend() {
setRequestPathInfo("/AppendAs2RoutingInfo");
addRequestParameter("routingInfoId", "");
addRequestParameter("as2From", "");
addRequestParameter("as2To", "");
addRequestParameter("syncFlag", "");
addRequestParameter("msgEncFlag", "");
addRequestParameter("msgSignFlag", "");
addRequestParameter("mdnFlag", "");
addRequestParameter("mdnSignFlag", "");
addRequestParameter("adapterId", "");
addRequestParameter("regDate", "");
addRequestParameter("modifyDate", "");
actionPerform();
verifyForward("success");
verifyNoActionErrors();
Object object = getRequest().getAttribute("outputObject");
logger.info(object);
}
public void testModify() {
setRequestPathInfo("/ModifyAs2RoutingInfo");
addRequestParameter("routingInfoId", "");
addRequestParameter("as2From", "");
addRequestParameter("as2To", "");
addRequestParameter("syncFlag", "");
addRequestParameter("msgEncFlag", "");
addRequestParameter("msgSignFlag", "");
addRequestParameter("mdnFlag", "");
addRequestParameter("mdnSignFlag", "");
addRequestParameter("adapterId", "");
addRequestParameter("regDate", "");
addRequestParameter("modifyDate", "");
actionPerform();
verifyForward("success");
verifyNoActionErrors();
Object object = getRequest().getAttribute("outputObject");
logger.info(object);
}
public void testRemove() {
setRequestPathInfo("/RemoveAs2RoutingInfo");
addRequestParameter("routingInfoId", "");
actionPerform();
verifyForward("success");
verifyNoActionErrors();
Object object = getRequest().getAttribute("outputObject");
logger.info(object);
}
public void testRemoveList() {
setRequestPathInfo("/RemoveAs2RoutingInfoList");
addRequestParameter("routingInfoId", "");
actionPerform();
verifyForward("success");
verifyNoActionErrors();
Object object = getRequest().getAttribute("outputObject");
logger.info(object);
}
public void testSelect() {
setRequestPathInfo("/SelectAs2RoutingInfo");
addRequestParameter("routingInfoId", "");
actionPerform();
verifyForward("success");
verifyNoActionErrors();
Object object = getRequest().getAttribute("outputObject");
logger.info(object);
}
public void testSelectList() {
setRequestPathInfo("/SelectAs2RoutingInfoList");
actionPerform();
verifyForward("success");
verifyNoActionErrors();
List objectList = (List)getRequest().getAttribute("outputObject");
for (int i = 0 ; i < objectList.size() ; i++)
logger.info(objectList.get(i));
}
}
|
package com.atguigu.lgl;
/*
switch(๏ฟฝ๏ฟฝ๏ฟฝสฝ){
case ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ1:
๏ฟฝ๏ฟฝ๏ฟฝ1;
// break;
case ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ2:
๏ฟฝ๏ฟฝ๏ฟฝ2;
// break;
๏ฟฝ๏ฟฝ ๏ฟฝ๏ฟฝ
case ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝN:
๏ฟฝ๏ฟฝ๏ฟฝN;
// break;
default:
๏ฟฝ๏ฟฝ๏ฟฝ;
// break;
}
*/
import java.util.Scanner;
public class test2
{
public static void main(String[] args){
System.out.println("please input jijiemingcheng:");
Scanner s = new Scanner(System.in);
String mess = s.next();
switch ( mess)
{
case "chun":
System.out.println("๏ฟฝ๏ฟฝ๏ฟฝวด๏ฟฝ๏ฟฝ์ฃก");
break;
case "xia":
System.out.println("๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ์ฃก");
break;
case "qiu":
System.out.println("๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ์ฃก");
break;
case "dong":
System.out.println("๏ฟฝ๏ฟฝ๏ฟฝวถ๏ฟฝ๏ฟฝ์ฃก");
break;
default:
System.out.println("๏ฟฝใฒป๏ฟฝฺต๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝฯฃ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ");
break;
}
}
} |
package validation.annotations;
import validation.FXAbstractValidator;
import validation.RequiredValidator;
import java.lang.annotation.*;
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FXRequired {
public Class<? extends FXAbstractValidator> validation() default RequiredValidator.class;
public boolean required() default false;
public String message() default "This field must not be empty!";
}
|
package Selenium.Registration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class FillRegistration implements FillRegistrationInterface {
WebDriver browser;
public FillRegistration(WebDriver b){
this.browser = b;
}
@Override
public void visitRegister() {
browser.get("http://localhost:8080/SoftwareTesting/Register.jsp");
}
@Override
public void closeBrowser() {
browser.close();
}
@Override
public void fillForm() {
WebElement field;
field = browser.findElement(By.id("username"));
field.sendKeys("Afriggieri4");
field = browser.findElement(By.id("password"));
field.sendKeys("testing123");
field = browser.findElement(By.id("name"));
field.sendKeys("Andreas");
field = browser.findElement(By.id("surname"));
field.sendKeys("Friggieri");
field = browser.findElement(By.id("dob"));
field.sendKeys("1994/12/12");
field = browser.findElement(By.id("cc_num"));
field.sendKeys("371449635398431");
field = browser.findElement(By.id("cc_exp"));
field.sendKeys("2018/12");
field = browser.findElement(By.id("cvv"));
field.sendKeys("123");
}
@Override
public void fillForm(String username, String password, String type) {
WebElement field;
field = browser.findElement(By.id("username"));
field.sendKeys(username);
field = browser.findElement(By.id("password"));
field.sendKeys(password);
field = browser.findElement(By.id("name"));
field.sendKeys("Andreas");
field = browser.findElement(By.id("surname"));
field.sendKeys("Friggieri");
field = browser.findElement(By.id("dob"));
field.sendKeys("1994/12/12");
if (type == "premium" || type == "Premium") {
WebElement radiobutton = browser
.findElement(By.id("account_type1"));
radiobutton.click();
}
field = browser.findElement(By.id("cc_num"));
field.sendKeys("371449635398431");
field = browser.findElement(By.id("cc_exp"));
field.sendKeys("2018/12");
field = browser.findElement(By.id("cvv"));
field.sendKeys("123");
}
@Override
public void submitForm() {
WebElement registerbutton = browser.findElement(By.id("register"));
registerbutton.click();
}
@Override
public void clearField(String field) {
browser.findElement(By.id(field)).clear();
}
@Override
public List<WebElement> findByID(String name) {
List<WebElement> list = browser.findElements(By.id(name));
return list;
}
@Override
public List<WebElement> findByClass(String classname) {
return browser.findElements(By.className(classname));
}
}
|
package com.finance.service;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBookService {
@Test
public void testGetBookPrice() {
ApplicationContext context = new ClassPathXmlApplicationContext("./applicationContext.xml");
BookService bookService = (BookService) context.getBean("bookService");
System.out.println(bookService.getBookPrice());
}
@Test
public void testBuyBook() {
ApplicationContext context = new ClassPathXmlApplicationContext("./applicationContext.xml");
BookService bookService = (BookService) context.getBean("bookService");
bookService.buyBook();
}
}
|
package kr.co.hangsho.orders.service;
import java.util.List;
import kr.co.hangsho.customers.vo.Customer;
import kr.co.hangsho.orders.vo.OrderDetail;
public interface OrderDetailService {
List<OrderDetail> getOrderDetailsByCustomer(Customer customer);
}
|
// Copyright (c) 2014 PayPal. All rights reserved.
package com.paypal.cordova.sdk;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import com.paypal.android.sdk.payments.*;
public class PayPalMobileCordovaPlugin extends CordovaPlugin {
private CallbackContext callbackContext;
private String environment = PayPalConfiguration.ENVIRONMENT_PRODUCTION;
private String productionClientId = null;
private String sandboxClientId = null;
private PayPalConfiguration configuration = new PayPalConfiguration();
private Activity activity = null;
private boolean serverStarted = false;
private static final int REQUEST_SINGLE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static final int REQUEST_CODE_PROFILE_SHARING = 3;
@Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {
this.callbackContext = callbackContext;
this.activity = this.cordova.getActivity();
boolean retValue = true;
if (action.equals("version")) {
this.version();
} else if (action.equals("init")) {
this.init(args);
} else if (action.equals("prepareToRender")) {
this.prepareToRender(args);
} else if (action.equals("applicationCorrelationIDForEnvironment")) {
this.applicationCorrelationIDForEnvironment(args);
} else if (action.equals("renderSinglePaymentUI")) {
this.renderSinglePaymentUI(args);
} else if (action.equals("renderFuturePaymentUI")) {
this.renderFuturePaymentUI(args);
} else if (action.equals("renderProfileSharingUI")) {
this.renderProfileSharingUI(args);
} else {
retValue = false;
}
return retValue;
}
@Override
public void onDestroy() {
if (null != this.activity && serverStarted) {
this.activity.stopService(new Intent(this.activity, PayPalService.class));
}
super.onDestroy();
}
// internal implementation
private void version() {
this.callbackContext.success(Version.PRODUCT_VERSION);
}
private void init(JSONArray args) throws JSONException {
JSONObject jObject = args.getJSONObject(0);
this.productionClientId = jObject.getString("PayPalEnvironmentProduction");
this.sandboxClientId = jObject.getString("PayPalEnvironmentSandbox");
this.callbackContext.success();
}
private void prepareToRender(JSONArray args) throws JSONException {
// make sure we use the same environment ids
String env = args.getString(0);
if (env.equalsIgnoreCase("PayPalEnvironmentNoNetwork")) {
this.environment = PayPalConfiguration.ENVIRONMENT_NO_NETWORK;
} else if (env.equalsIgnoreCase("PayPalEnvironmentProduction")) {
this.environment = PayPalConfiguration.ENVIRONMENT_PRODUCTION;
this.configuration.clientId(this.productionClientId);
} else if (env.equalsIgnoreCase("PayPalEnvironmentSandbox")) {
this.environment = PayPalConfiguration.ENVIRONMENT_SANDBOX;
this.configuration.clientId(this.sandboxClientId);
} else {
this.callbackContext
.error("The provided environment is not supported");
return;
}
this.configuration.environment(environment);
// get configuration and update
if (args.length() > 1) {
JSONObject config = args.getJSONObject(1);
this.updatePayPalConfiguration(config);
}
// start service
this.startService();
this.callbackContext.success();
}
private void applicationCorrelationIDForEnvironment(JSONArray args) throws JSONException {
// Environment not used on android
//String env = args.getString(0);
String correlationId = PayPalConfiguration.getApplicationCorrelationId(this.cordova.getActivity());
this.callbackContext.success(correlationId);
}
private void startService() {
if (serverStarted) {
serverStarted = this.activity.stopService(new Intent(this.activity, PayPalService.class));
}
Intent intent = new Intent(this.activity, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, this.configuration);
this.activity.startService(intent);
serverStarted = true;
}
private void renderSinglePaymentUI(JSONArray args) throws JSONException {
if (args.length() != 1) {
this.callbackContext
.error("renderPaymentUI payment object must be provided");
return;
}
// get payment details
JSONObject paymentObject = args.getJSONObject(0);
String amount = paymentObject.getString("amount");
String currency = paymentObject.getString("currency");
String shortDescription = paymentObject.getString("shortDescription");
// invoice number is optional
String invoiceNumber = null;
if (paymentObject.has("invoiceNumber") && !paymentObject.isNull("invoiceNumber")) {
invoiceNumber = paymentObject.getString("invoiceNumber");
}
String paymentIntent = ("sale".equalsIgnoreCase(paymentObject.getString("intent"))) ? PayPalPayment.PAYMENT_INTENT_SALE : PayPalPayment.PAYMENT_INTENT_AUTHORIZE;
JSONObject paymentDetails = paymentObject.has("details") ? paymentObject.getJSONObject("details") : null;
// create payment object
PayPalPayment payment = new PayPalPayment(new BigDecimal(amount),
currency, shortDescription, paymentIntent);
payment.invoiceNumber(invoiceNumber);
payment.paymentDetails(this.parsePaymentDetails(paymentDetails));
Intent intent = new Intent(this.activity, PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
this.cordova.startActivityForResult(this, intent, REQUEST_SINGLE_PAYMENT);
}
private void renderFuturePaymentUI(JSONArray args) throws JSONException {
Intent intent = new Intent(this.activity, PayPalFuturePaymentActivity.class);
this.cordova.startActivityForResult(this, intent, REQUEST_CODE_FUTURE_PAYMENT);
}
private void renderProfileSharingUI(JSONArray args) throws JSONException {
if (args.length() != 1) {
this.callbackContext
.error("renderProfileSharingUI scopes must be provided");
return;
}
Intent intent = new Intent(this.activity, PayPalProfileSharingActivity.class);
// add codes
intent.putExtra(PayPalProfileSharingActivity.EXTRA_REQUESTED_SCOPES, getOauthScopes(args.getJSONArray(0)));
this.cordova.startActivityForResult(this, intent, REQUEST_CODE_PROFILE_SHARING);
}
private PayPalOAuthScopes getOauthScopes(JSONArray scopeList) throws JSONException {
/* create the set of required scopes
* Note: see https://developer.paypal.com/docs/integration/direct/identity/attributes/ for mapping between the
* attributes you select for this app in the PayPal developer portal and the scopes required here.
*/
Set<String> scopes = new HashSet<String>();
for (int i = 0; i < scopeList.length(); i++) {
String scope = scopeList.getString(i);
if (scope.equalsIgnoreCase("profile")) {
scopes.add(PayPalOAuthScopes.PAYPAL_SCOPE_PROFILE);
} else if (scope.equalsIgnoreCase("email")) {
scopes.add(PayPalOAuthScopes.PAYPAL_SCOPE_EMAIL);
} else if (scope.equalsIgnoreCase("phone")) {
scopes.add(PayPalOAuthScopes.PAYPAL_SCOPE_PHONE);
} else if (scope.equalsIgnoreCase("address")) {
scopes.add(PayPalOAuthScopes.PAYPAL_SCOPE_ADDRESS);
} else if (scope.equalsIgnoreCase("paypalattributes")) {
scopes.add(PayPalOAuthScopes.PAYPAL_SCOPE_PAYPAL_ATTRIBUTES);
} else if (scope.equalsIgnoreCase("futurepayments")) {
scopes.add(PayPalOAuthScopes.PAYPAL_SCOPE_FUTURE_PAYMENTS);
} else {
scopes.add(scope);
}
}
return new PayPalOAuthScopes(scopes);
}
private void updatePayPalConfiguration(JSONObject object) throws JSONException {
if (object == null || 0 == object.length()) {
return;
}
if (object.has("defaultUserEmail") && !object.isNull("defaultUserEmail")) {
this.configuration.defaultUserEmail(object.getString("defaultUserEmail"));
}
if (object.has("defaultUserPhoneCountryCode") && !object.isNull("defaultUserPhoneCountryCode")) {
this.configuration.defaultUserPhoneCountryCode(object.getString("defaultUserPhoneCountryCode"));
}
if (object.has("defaultUserPhoneNumber") && !object.isNull("defaultUserPhoneNumber")) {
this.configuration.defaultUserPhone(object.getString("defaultUserPhoneNumber"));
}
if (object.has("merchantName") && !object.isNull("merchantName")) {
this.configuration.merchantName(object.getString("merchantName"));
}
if (object.has("merchantPrivacyPolicyURL") && !object.isNull("merchantPrivacyPolicyURL")) {
this.configuration.merchantPrivacyPolicyUri(Uri.parse(object.getString("merchantPrivacyPolicyURL")));
}
if (object.has("merchantUserAgreementURL") && !object.isNull("merchantUserAgreementURL")) {
this.configuration.merchantUserAgreementUri(Uri.parse(object.getString("merchantUserAgreementURL")));
}
if (object.has("acceptCreditCards")) {
this.configuration.acceptCreditCards(object.getBoolean("acceptCreditCards"));
}
if (object.has("rememberUser")) {
this.configuration.rememberUser(object.getBoolean("rememberUser"));
}
if (object.has("forceDefaultsInSandbox")) {
this.configuration.forceDefaultsOnSandbox(object.getBoolean("forceDefaultsInSandbox"));
}
if (object.has("languageOrLocale") && !object.isNull("languageOrLocale")) {
this.configuration.languageOrLocale(object.getString("languageOrLocale"));
}
if (object.has("sandboxUserPassword") && !object.isNull("sandboxUserPassword")) {
this.configuration.sandboxUserPassword(object.getString("sandboxUserPassword"));
}
if (object.has("sandboxUserPin") && !object.isNull("sandboxUserPin")) {
this.configuration.sandboxUserPin(object.getString("sandboxUserPin"));
}
}
private PayPalPaymentDetails parsePaymentDetails(JSONObject object) throws JSONException {
if (object == null || 0 == object.length()) {
return null;
}
BigDecimal subtotal = object.has("subtotal") ? new BigDecimal(object.getString("subtotal")) : null;
BigDecimal shipping = object.has("shipping") ? new BigDecimal(object.getString("shipping")) : null;
BigDecimal tax = object.has("tax") ? new BigDecimal(object.getString("tax")) : null;
PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax);
return paymentDetails;
}
// onActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (REQUEST_SINGLE_PAYMENT == requestCode) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirmation = null;
if (intent.hasExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION)) {
confirmation = intent
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
this.callbackContext.success(confirmation.toJSONObject());
} else {
this.callbackContext
.error("payment was ok but no confirmation");
}
} else if (resultCode == Activity.RESULT_CANCELED) {
this.callbackContext.error("payment cancelled");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
this.callbackContext.error("An invalid Payment was submitted. Please see the docs.");
} else {
this.callbackContext.error(resultCode);
}
} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = null;
if (intent.hasExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION)) {
auth = intent.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
this.callbackContext.success(auth.toJSONObject());
} else {
this.callbackContext
.error("Authorization was ok but no code");
}
} else if (resultCode == Activity.RESULT_CANCELED) {
this.callbackContext.error("Future Payment user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
this.callbackContext.error("Possibly configuration submitted is invalid");
}
} else if (requestCode == REQUEST_CODE_PROFILE_SHARING) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = null;
if (intent.hasExtra(PayPalProfileSharingActivity.EXTRA_RESULT_AUTHORIZATION)) {
auth = intent.getParcelableExtra(PayPalProfileSharingActivity.EXTRA_RESULT_AUTHORIZATION);
this.callbackContext.success(auth.toJSONObject());
} else {
this.callbackContext
.error("Authorization was ok but no code");
}
} else if (resultCode == Activity.RESULT_CANCELED) {
this.callbackContext.error("Profile Sharing user canceled.");
} else if (resultCode == PayPalProfileSharingActivity.RESULT_EXTRAS_INVALID) {
this.callbackContext.error("Possibly configuration submitted is invalid");
}
}
}
}
|
package fr.univsavoie.istoage.clientflickr;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.jdom2.*;
import org.jdom2.input.SAXBuilder;
public class FlickrClient {
//public static final String CleFlickr = "2e6fb8cdda0792a3e4972d289b1a4ad9";
//public static final String CleSecrete = "fef365a6bf1e28cf";
public static final String UrlSoapFlickr = "http://api.flickr.com/services/soap/";
private String cleFlickr;
private String cleSecrete;
/**
* Generate a Flickr Soap Client to get some pictures for choosen Stage offer
* @param cleFlickr - App key for flickr
* @param cleSecrete - Secret App key for flickr
*/
public FlickrClient( String cleFlickr, String cleSecrete ) {
this.cleFlickr = cleFlickr;
this.cleSecrete = cleSecrete;
}
/**
* Return a picture from flickr database, using SOAP.
* @param tags - tags for the picture
* @return an Url of a picture mathcing tags
*/
public String getFlickerPicture( String tags ) {
String requestString = generateRequestString( tags );
String resultRequest = invokeFlickrSercice( requestString );
Element cleanResult = cleanXMLResult( resultRequest );
return generatePictureUrl( cleanResult );
}
/**
* Generate a correct envelope to send to flickr web service
* @param tags - tags to match the picture
* @return - the enveloppe string
*/
private String generateRequestString(String tags) {
String requestString = "<s:Envelope " +
"xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" " +
"xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\" >" +
"<s:Body>" +
"<x:FlickrRequest xmlns:x=\"urn:flickr\" >" +
"<method>flickr.photos.search</method>" +
"<api_key>" + cleFlickr + "</api_key>" +
"<tags>" + tags + "</tags>" +
"<tag_mode>all</tag_mode>" +
"<per_page>1</per_page>" +
"</x:FlickrRequest>" +
"</s:Body>" +
"</s:Envelope>";
return requestString;
}
/**
* Invoke the flickr soap service to get an image
* @param requestString
* @return xml answer
*/
private String invokeFlickrSercice(String requestString) {
String resultRequest = "";
try {
URL serviceUrl = new URL( UrlSoapFlickr );
HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection();
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
// Open the outStream to send the request
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write( requestString );
osw.flush();
osw.close();
// Open the receiver stream
InputStream is;
if (connection.getResponseCode() >= 400)
{
return null;
}
else
{
is = connection.getInputStream();
}
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new java.io.BufferedReader(isr);
// Put the whole answer in a string
String line = null;
while ((line = br.readLine()) != null)
{
resultRequest = resultRequest.concat(line);
}
}
// There's so many IOException possible that we have to catch'em all!
catch (IOException e) {
e.printStackTrace();
}
return resultRequest;
}
/**
* Remove the envelope from the result string
* Parse it with jdom and return the picture tag
* @param String resultRequest - resulString from the soap request to flickr
* @return jdom element
*/
private Element cleanXMLResult(String resultRequest) {
Element pictureElement = null;
if ( resultRequest == null )
{
System.out.println("Impossible de rรฉcupรฉrer une photo pour ces tags, essayez de changer de tags");
return null;
}
try {
InputStream inputStreamResult = new ByteArrayInputStream(resultRequest.getBytes());
SAXBuilder saxBuilder = new SAXBuilder();
Document documentResult = saxBuilder.build(inputStreamResult);
Element racineResult = documentResult.getRootElement();
InputStream inXML = new ByteArrayInputStream(racineResult.getValue().getBytes());
SAXBuilder sxbXML = new SAXBuilder();
Document docXML = sxbXML.build(inXML);
Element racine = docXML.getRootElement();
pictureElement = racine.getChild("photo");
}
catch (JDOMException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return pictureElement;
}
/**
* Generate picture url from XML element
* @param pictureElement - XML picture element
* @return the picture url
*/
private String generatePictureUrl(Element pictureElement) {
if ( pictureElement == null )
return null;
String pictureFarm = pictureElement.getAttributeValue("farm");
String pictureServer = pictureElement.getAttributeValue("server");
String pictureId = pictureElement.getAttributeValue("id");
String pictureSecret = pictureElement.getAttributeValue("secret");
String pictureUrl = "http://farm" + pictureFarm +
".staticflickr.com/" + pictureServer +
"/" + pictureId +
"_" + pictureSecret + ".jpg";
System.out.println( pictureUrl );
return pictureUrl;
}
}
|
package com.code515.report.report_demo.Repository;
import com.code515.report.report_demo.Entity.Organization;
import org.springframework.data.jpa.repository.JpaRepository;
public interface OrganizationRepository extends JpaRepository<Organization, Integer> {
Organization findByOrgNameAndBranchName(String orgName, String braName);
}
|
package ch.ffhs.ftoop.doppelgruen.quiz.commands;
import ch.ffhs.ftoop.doppelgruen.quiz.game.Location;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;
/**
* This parser reads user input and tries to interpret it as an command. Every time it is called it
* reads a line from the terminal and tries to interpret the line as a two-word command. It returns
* the command as an object of class Command.
*
* <p>The parser has a set of known command words. It checks user input against the known command,
* and if the input is not one of the known commands, it returns a command object that is marked as
* an unknown command.
*/
public class Parser {
private final CommandWords commands;
private final BufferedReader reader;
/**
* Creates a new parser
*
* @param inputStream An instance of the users input stream
* @throws NullPointerException If {@param inputStream} is null
*/
public Parser(final InputStream inputStream) {
Objects.requireNonNull(inputStream, "inputStream should not be null");
commands = new CommandWords();
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public void switchToLookingForGameCommands() {
commands.removeAllCommands();
}
public void switchToInGameCommands() {
commands.removeAllCommands();
for (CommandWord command : CommandWord.values()) {
if (command.isValidInGame()) {
commands.addCommand((command));
}
}
}
public void switchToLobbyCommands() {
commands.removeAllCommands();
for (CommandWord command : CommandWord.values()) {
if (command.isValidInLobby()) {
commands.addCommand((command));
}
}
}
/** @return The next command from the user. */
public Command getCommand(final Location playerLocation) throws IOException {
String inputLine;
String word1;
inputLine = reader.readLine();
if (inputLine == null) {
return null;
} else {
String[] tokenizer = inputLine.split(" ", 2);
word1 = tokenizer[0];
var sb = new StringBuilder();
// Exception for chatting without using command word in Lobby
if (playerLocation == Location.LOBBY && !word1.startsWith("/")) {
sb.append(word1);
word1 = "/chat";
}
if (tokenizer.length == 2) {
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(tokenizer[1]);
}
return new Command(
commands.getCommandWord(word1), (sb.toString().equals("")) ? null : sb.toString());
}
}
/** Print out a list of valid command words. */
public String getAllCommandsAsString() {
return commands.toString();
}
}
|
package com.gedesys.ifacade;
import com.gedesys.persistence.Opcion;
import java.util.List;
import javax.ejb.Remote;
/**
*
* @author econtreras
*/
@Remote
public interface OpcionesFacadeRemote {
Opcion createOpcion(String opcion, String usuario);
Opcion updateOpcion(Opcion opcion);
void deleteOpcion(short opcionId);
Opcion getOpcion(short opcionId);
List<Opcion> getAllOpciones();
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Controller.Admin;
import Business.MenuBAL;
import Entity.Menu;
import Utility.Session;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* @author TUNT
*/
@ManagedBean
@RequestScoped
public class MenuManagement extends Menu {
/** Creates a new instance of MenuManagement */
public MenuManagement() {
}
private String page;
private String redirect = "?faces-redirect=true";
public String addMenu() {
try {
MenuBAL.getInstance().addMenu(this);
page = "MenuList";
} catch (Exception e) {
page = "MenuManagement";
}
return page + redirect;
}
public List<Menu> getMenuList() {
return MenuBAL.getInstance().getMenuList();
}
public String viewDishByMenuID() {
page = "DishInMenu";
Session.set("menuID", this.getMenuID());
return page + redirect;
}
} |
import documents.*;
import forms.MainForm;
import users.userTypes.*;
import org.junit.Assert;
import org.junit.Test;
import storage.DatabaseManager;
import users.*;
import java.util.ArrayList;
public class TestCases2 {
final static String DATABASE_FILE_NAME = "TestCases";
/**
* Initial state: system does not have any documents, any patron.
* The system only contains one user who is a librarian.
* Action: librarian adds * 3 copies of book b1,
* * 2 copies of book b2,
* * 1 copy of book b3,
* * 2 Video materials: av1 and av2
* * patrons p1, p2 and p3
* Effect: number of documents in the System is 8 and the number of users is 4.
*/
@Test
public void TestCase1() {
//Initial state
DatabaseManager databaseManager = new DatabaseManager(DATABASE_FILE_NAME);
databaseManager.resetDatabase();
ArrayList<Copy> l1_checkedOutCopies = new ArrayList<Copy>();
ArrayList<Document> l1_requestedDocuments = new ArrayList<Document>();
UserCard librarian_1 = new UserCard("Irma", "Pins", new Librarian(), "8981351785", "north of London",
l1_checkedOutCopies, l1_requestedDocuments);
databaseManager.saveUserCard(librarian_1);
Session session = new Session(databaseManager.getUserCard(librarian_1.getId()).userType, 5, 3);
Assert.assertTrue("Session is leading by librarian.", Librarian.class.isAssignableFrom(session.getUser().getClass()));
//Assert.assertTrue("The databaseManager contains only one user", databaseManager.getAllUsers().size() == 1);
Assert.assertTrue("This only one user is a librarian.", (Librarian.class.isAssignableFrom(databaseManager.getUserCard(1).userType.getClass())));
Assert.assertTrue("There is no any documents in the databaseManager.", databaseManager.getAllDocuments().size() == 0);
///////////////////////////////////////////////////////////////
//Action
ArrayList<Copy> b1_copies = new ArrayList<Copy>();
ArrayList<String> b1_authors = new ArrayList<String>();
b1_authors.add("Thomas H. Cormen");
b1_authors.add("Charles E. Leiserson");
b1_authors.add("Ronald L. Rivest");
b1_authors.add("Clifford Stein");
ArrayList<String> b1_keywords = new ArrayList<String>();
b1_keywords.add("none");
Book b1 = new Book("Introduction to Algorithms", b1_authors,
b1_keywords, 0, b1_copies, "MIT Press", 2009, "Third edition", false);
databaseManager.saveDocuments(b1);
b1.setCopy(new Copy(b1, 1, 1));
b1.setCopy(new Copy(b1, 2, 1));
b1.setCopy(new Copy(b1, 3, 1));
databaseManager.saveDocuments(b1);
/////////////////////////////////////////////////////////////
ArrayList<Copy> b2_copies = new ArrayList<Copy>();
ArrayList<String> b2_authors = new ArrayList<String>();
b2_authors.add("Erich Gamma");
b2_authors.add("Ralph Johnson");
b2_authors.add("John Vlissides");
b2_authors.add("Richard Helm");
ArrayList<String> b2_keywords = new ArrayList<String>();
b2_keywords.add("none");
Book b2 = new Book("Design Patterns: Elements of Reusable Object-Oriented Software", b2_authors,
b2_keywords, 0, b2_copies, "Addison-Wesley Professional", 2003, "First edition", true);
databaseManager.saveDocuments(b2);
b2.setCopy(new Copy(b2, 1, 1));
b2.setCopy(new Copy(b2, 2, 1));
databaseManager.saveDocuments(b2);
///////////////////////////////////////////////////////////////
ArrayList<Copy> b3_copies = new ArrayList<Copy>();
ArrayList<String> b3_authors = new ArrayList<String>();
b3_authors.add("Brooks.Jr.");
b3_authors.add("Frederick P");
ArrayList<String> b3_keywords = new ArrayList<String>();
b3_keywords.add("none");
Book b3 = new Book("The Mythical Man-month", b3_authors,
b3_keywords, 0, b3_copies, "Addison-Wesley Longman Publishing Co.,Inc", 1995, "Second edition", false);
b3.setReference(true);
b3.setCopy(new Copy(b3, 1, 1));
databaseManager.saveDocuments(b3);
//////////////////////////////////////////////////////////////////////////////////////////////////////////
ArrayList<String> av1_keywords = new ArrayList<String>();
av1_keywords.add("none");
ArrayList<String> av1_authors = new ArrayList<String>();
av1_authors.add("Tony Hoare");
AVMaterial av1 = new AVMaterial("Null References: The Billion Dollar Mistake", av1_authors, av1_keywords, 0);
databaseManager.saveDocuments(av1);
av1.setCopy(new Copy(av1, 2, 1));
databaseManager.saveDocuments(av1);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ArrayList<String> av2_keywords = new ArrayList<String>();
av2_keywords.add("none");
ArrayList<String> av2_authors = new ArrayList<String>();
av2_authors.add("Claude Shannon");
AVMaterial av2 = new AVMaterial("Information Entropy", av2_authors, av2_keywords, 0);
databaseManager.saveDocuments(av2);
av2.setCopy(new Copy(av2, 2, 1));
databaseManager.saveDocuments(av2);
/////////////////////////////////////////////////////////////////////////////////////////////////
ArrayList<Copy> p1_checkedOutCopies = new ArrayList<Copy>();
ArrayList<Document> p1_requestedDocs = new ArrayList<Document>();
UserCard p1 = new UserCard(1010, "Sergey", "Afonso", new Faculty(), "30001", "Via Margutta, 3", p1_checkedOutCopies, p1_requestedDocs);
databaseManager.saveUserCard(p1);
/////////////////////////////////////////////////////////////////
ArrayList<Copy> p2_checkedOutCopies = new ArrayList<Copy>();
ArrayList<Document> p2_requestedDocs = new ArrayList<Document>();
UserCard p2 = new UserCard(1011, "Nadia", "Teixeira", new Student(), "30002", "Via Sacra, 13", p2_checkedOutCopies, p2_requestedDocs);
databaseManager.saveUserCard(p2);
//////////////////////////////////////////////////////////////////
ArrayList<Copy> p3_checkedOutCopies = new ArrayList<Copy>();
ArrayList<Document> p3_requestedDocs = new ArrayList<Document>();
UserCard p3 = new UserCard(1100, "Elvira", "Espindola", new Student(), "30003", "Via del Corso, 22", p3_checkedOutCopies, p3_requestedDocs);
databaseManager.saveUserCard(p3);
//////////////////////////////////////////////////////////////////
//Effect
int a = 0;// number of all copies of all docs i.e. all physically available in library
for (int i = 1; i <= databaseManager.getAllDocuments().size(); i++) {
if (!(databaseManager.getDocuments(i).getNumberOfAllCopies() == 0)) {
for (int j = 1; j <= databaseManager.getDocuments(i).getNumberOfAllCopies(); j++) {
a++;
}
}
}
Assert.assertTrue("Number of documents equals to 8", (a == 8));
// Assert.assertTrue("Number of users equals to 4", (databaseManager.getAllUsers().size() == 4));
}
/**
* Initial state: TC1
* Action: The librarian removes * 2 copies of book b1,
* * 1 copy of book b3
* * patron p2
* Effect: number of documents in the System is 5 and the number of users is 3.
*/
@Test
public void TestCase2() {
//Initial state
TestCase1();
DatabaseManager databaseManager = new DatabaseManager(DATABASE_FILE_NAME);
Session session = new Session((databaseManager.getUserCard(1).userType), 5, 3);
int a = 0;// number of all copies of all docs i.e. all physically available in library
for (int i = 1; i <= databaseManager.getAllDocuments().size(); i++) {
if (!(databaseManager.getDocuments(i).getNumberOfAllCopies() == 0)) {
for (int j = 1; j <= databaseManager.getDocuments(i).getNumberOfAllCopies(); j++) {
a++;
}
}
}
Assert.assertTrue("Number of documents equals to 8", (a == 8));
//Assert.assertTrue("Number of users equals to 4", (databaseManager.getAllUsers().size() == 4));
Assert.assertTrue("Session is leading by librarian", Librarian.class.isAssignableFrom(session.getUser().getClass()));
//Action
//Book b1 = (Book)databaseManager.getDocuments(1);
databaseManager.getDocuments(1).removeCopy(databaseManager.getDocuments(1).availableCopies.get(1));
databaseManager.saveDocuments(databaseManager.getDocuments(1));
databaseManager.getDocuments(1).removeCopy(databaseManager.getDocuments(1).availableCopies.get(0));
databaseManager.saveDocuments(databaseManager.getDocuments(1));
databaseManager.getDocuments(3).removeCopy(databaseManager.getDocuments(3).availableCopies.get(0));
databaseManager.saveDocuments(databaseManager.getDocuments(3));
databaseManager.removeUserCard(databaseManager.getUserCard(1011));
// Effect
int b = 0;// number of all copies of all docs i.e. all physically available in library
for (int i = 1; i <= databaseManager.getAllDocuments().size(); i++) {
if (!(databaseManager.getDocuments(i).getNumberOfAllCopies() == 0)) {
for (int j = 1; j <= databaseManager.getDocuments(i).getNumberOfAllCopies(); j++) {
b++;
}
}
}
Assert.assertTrue("Number of documents equals to 5", (b == 5));
//Assert.assertTrue("Number of users equals to 3", (databaseManager.getAllUsers().size() == 3));
}
/**
* Initial state: TC1
* Action: librarian checks the information of patron p1 and p3
* Effect: got all the information
*/
@Test
public void TestCase3() {
//Initial state
TestCase1();
DatabaseManager databaseManager = new DatabaseManager(DATABASE_FILE_NAME);
Session session = new Session((databaseManager.getUserCard(1).userType), 9, 3);
int c = 0;// number of all copies of all docs i.e. all physically available in library
for (int i = 1; i <= databaseManager.getAllDocuments().size(); i++) {
if (!(databaseManager.getDocuments(i).getNumberOfAllCopies() == 0)) {
for (int j = 1; j <= databaseManager.getDocuments(i).getNumberOfAllCopies(); j++) {
c++;
}
} else {
c++;
}
}
Assert.assertTrue("Number of documents equals to 8", (c == 8));
//Assert.assertTrue("Number of users equals to 4", (databaseManager.getAllUsers().size() == 4));
Assert.assertTrue("Session is leading by librarian", Librarian.class.isAssignableFrom(session.getUser().getClass()));
// Action and Effect
UserCard first = databaseManager.getUserCard(1010);
UserCard third = databaseManager.getUserCard(1100);
Assert.assertTrue("Name of p1 is correct.", ((first.name.equals(databaseManager.getUserCard(1010).name))
&& (first.name.equals("Sergey"))));
Assert.assertTrue("Surname of p1 is correct.", ((first.surname.equals(databaseManager.getUserCard(1010).surname))
&& (first.surname.equals("Afonso"))));
Assert.assertTrue("Address of p1 is correct.", ((first.address.equals(databaseManager.getUserCard(1010).address)
&& (first.address.equals("Via Margutta, 3")))));
Assert.assertTrue("Phone Number of p1 is correct.", ((first.phoneNumb.equals(databaseManager.getUserCard(1010).phoneNumb))
&& (first.phoneNumb.equals("30001"))));
Assert.assertTrue("id of p1 is correct.", ((first.getId() == databaseManager.getUserCard(1010).getId())
&& (first.getId() == 1010)));
Assert.assertTrue("User Type of p1 is correct", Faculty.class.isAssignableFrom(first.userType.getClass()));
Assert.assertTrue("List of checked out documents is correct", first.checkedOutCopies == databaseManager.getUserCard(1010).checkedOutCopies);
for (int i = 1; i <= first.checkedOutCopies.size(); i++) {
Assert.assertTrue("List of due dates of checked out documents is correct", first.checkedOutCopies.get(i).getDueDate().equals(databaseManager.getUserCard(1010).checkedOutCopies));
}
/////////////////////////////////////////////////////////////////////////////////////////////
Assert.assertTrue("Name of p2 is correct.", ((third.name.equals(databaseManager.getUserCard(1100).name))
&& (third.name.equals("Elvira"))));
Assert.assertTrue("Surname of p2 is correct.", ((third.surname.equals(databaseManager.getUserCard(1100).surname))
&& (third.surname.equals("Espindola"))));
Assert.assertTrue("Address of p2 is correct.", ((third.address.equals(databaseManager.getUserCard(1100).address)
&& (third.address.equals("Via del Corso, 22")))));
Assert.assertTrue("Phone Number of p2 is correct.", ((third.phoneNumb.equals(databaseManager.getUserCard(1100).phoneNumb))
&& (third.phoneNumb.equals("30003"))));
Assert.assertTrue("id of p2 is correct.", ((third.getId() == databaseManager.getUserCard(1100).getId())
&& (third.getId() == 1100)));
Assert.assertTrue("User Type of p2 is correct", Student.class.isAssignableFrom(third.userType.getClass()));
Assert.assertTrue("List of checked out documents is correct", third.checkedOutCopies == databaseManager.getUserCard(1100).checkedOutCopies);
for (int i = 1; i <= third.checkedOutCopies.size(); i++) {
Assert.assertTrue("List of due dates of checked out documents is correct", third.checkedOutCopies.get(i).getDueDate().equals(databaseManager.getUserCard(1100).checkedOutCopies));
}
}
/**
* Initial state: TC2
* Action: The librarian checks the information of patron p2 and p3
* Effect: got the information about p3 but not p3
*/
@Test
public void TestCase4() {
TestCase2();
DatabaseManager databaseManager = new DatabaseManager(DATABASE_FILE_NAME);
Assert.assertNull(databaseManager.getUserCard(1011));
Assert.assertEquals(databaseManager.getUserCard(1100).name, "Elvira");
Assert.assertEquals(databaseManager.getUserCard(1100).address, "Via del Corso, 22");
Assert.assertEquals(databaseManager.getUserCard(1100).phoneNumb, "30003");
Assert.assertEquals(databaseManager.getUserCard(1100).userType.getClass().getName().replace("users.userTypes", ""), ".Student");
Assert.assertEquals(databaseManager.getUserCard(1100).getId(), 1100);
}
/**
* Initial state: TC2
* Action: Patron p2 checks out book b1
* Effect: nothing happen
*/
@Test
public void TestCase5() {
TestCase2();
DatabaseManager databaseManager = new DatabaseManager(DATABASE_FILE_NAME);
Assert.assertNull(databaseManager.getUserCard(1011));
}
/**
* Initial state: TC2
* Action:
* p1 checks out b1
* p3 checks out b1
* p1 checks out b2
* the librarian checks the information of p1 and p3
* Effect: correct information about users
*/
@Test
public void TestCase6() {
TestCase2();
DatabaseManager databaseManager = new DatabaseManager(DATABASE_FILE_NAME);
Session session = new Session((databaseManager.getUserCard(1010).userType), 5, 3);
session.userCard = databaseManager.getUserCard(1010);
MainForm mainForm = new MainForm();
mainForm.setSession(session);
mainForm.setDatabaseManager(databaseManager);
mainForm.setActionManager(databaseManager.actionManager);
mainForm.selectDocument(1);
mainForm.checkOut(databaseManager.getDocuments(1));
///////////////////////////////////////////////////////////
Session session1 = new Session((databaseManager.getUserCard(1100).userType), 5, 3);
session1.userCard = databaseManager.getUserCard(1100);
mainForm.setSession(session1);
mainForm.selectDocument(1);
mainForm.checkOut(databaseManager.getDocuments(1));
mainForm.selectDocument(2);
mainForm.checkOut(databaseManager.getDocuments(2));
///////////////////////////////////////////////////////////
Assert.assertEquals(databaseManager.getUserCard(1010).name, "Sergey");
Assert.assertEquals(databaseManager.getUserCard(1010).address, "Via Margutta, 3");
Assert.assertEquals(databaseManager.getUserCard(1010).phoneNumb, "30001");
Assert.assertEquals(databaseManager.getUserCard(1010).userType.getClass().getName().replace("users.", ""), "userTypes.Faculty");
Assert.assertEquals(databaseManager.getUserCard(1010).getId(), 1010);
Assert.assertEquals(databaseManager.getUserCard(1010).checkedOutCopies.size(), 1);
Assert.assertEquals(databaseManager.getUserCard(1010).checkedOutCopies.get(0).getDueDate(), "2 April");
Assert.assertEquals(databaseManager.getUserCard(1100).name, "Elvira");
Assert.assertEquals(databaseManager.getUserCard(1100).address, "Via del Corso, 22");
Assert.assertEquals(databaseManager.getUserCard(1100).phoneNumb, "30003");
Assert.assertEquals(databaseManager.getUserCard(1100).userType.getClass().getName().replace("users.", ""), "userTypes.Student");
Assert.assertEquals(databaseManager.getUserCard(1100).getId(), 1100);
Assert.assertEquals(databaseManager.getUserCard(1100).checkedOutCopies.size(), 1);
Assert.assertEquals(databaseManager.getUserCard(1100).checkedOutCopies.get(0).getDueDate(), "19 March");
}
/**
* Initial state: TC1
* Action:
* p1 checks out books b1, b2, b3 and video material av1
* p2 checks out books b1, b2 and video material av2
* the librarian checks the information of p1 and p2
* Effect: correct information about users
*/
@Test
public void TestCase7() {
TestCase1();
DatabaseManager databaseManager = new DatabaseManager(DATABASE_FILE_NAME);
///////////////////////////////////////////////////////////////////////////////////////
Session session = new Session((databaseManager.getUserCard(1010).userType), 5, 3);
session.userCard = databaseManager.getUserCard(1010);
MainForm mainForm = new MainForm();
mainForm.setSession(session);
mainForm.setDatabaseManager(databaseManager);
mainForm.setActionManager(databaseManager.actionManager);
mainForm.selectDocument(1);
mainForm.checkOut(databaseManager.getDocuments(1));
mainForm.selectDocument(2);
mainForm.checkOut(databaseManager.getDocuments(2));
mainForm.selectDocument(3);
mainForm.checkOut(databaseManager.getDocuments(3));
mainForm.selectDocument(4);
mainForm.checkOut(databaseManager.getDocuments(4));
/////////////////////////////////////////////////////////////////////////////////////////
Session session1 = new Session((databaseManager.getUserCard(1011).userType), 5, 3);
session1.userCard = databaseManager.getUserCard(1011);
mainForm.setSession(session1);
mainForm.selectDocument(1);
mainForm.checkOut(databaseManager.getDocuments(1));
mainForm.selectDocument(2);
mainForm.checkOut(databaseManager.getDocuments(2));
mainForm.selectDocument(5);
mainForm.checkOut(databaseManager.getDocuments(5));
//////////////////////////////////////////////////////////////////////////////////////////
Session session2 = new Session((databaseManager.getUserCard(1).userType), 5, 3);
session2.userCard = databaseManager.getUserCard(1);
mainForm.setSession(session2);
UserCard user1 = databaseManager.getUserCard(1010);
Assert.assertEquals(user1.name + " " + user1.surname, "Sergey Afonso");
Assert.assertEquals(user1.address, "Via Margutta, 3");
Assert.assertEquals(user1.phoneNumb, "30001");
Assert.assertEquals(user1.getId(), 1010);
Assert.assertEquals(user1.userType.getClass().getName().replace("users.", ""), "userTypes.Faculty");
Assert.assertEquals(3, user1.checkedOutCopies.size());
Assert.assertEquals(user1.checkedOutCopies.get(0).getDocumentID(), databaseManager.getDocuments(1).getID());
Assert.assertEquals(user1.checkedOutCopies.get(0).getDueDate(), "2 April");
Assert.assertEquals(user1.checkedOutCopies.get(1).getDocumentID(), databaseManager.getDocuments(2).getID());
Assert.assertEquals(user1.checkedOutCopies.get(1).getDueDate(), "2 April");
Assert.assertEquals(user1.checkedOutCopies.get(2).getDocumentID(), databaseManager.getDocuments(4).getID());
Assert.assertEquals(user1.checkedOutCopies.get(2).getDueDate(), "19 March");
UserCard user2 = databaseManager.getUserCard(1011);
Assert.assertEquals(user2.name + " " + user2.surname, "Nadia Teixeira");
Assert.assertEquals(user2.address, "Via Sacra, 13");
Assert.assertEquals(user2.phoneNumb, "30002");
Assert.assertEquals(user2.getId(), 1011);
Assert.assertEquals(user2.userType.getClass().getName().replace("users.", ""), "userTypes.Student");
Assert.assertEquals(user2.checkedOutCopies.size(), 2);
Assert.assertEquals(user2.checkedOutCopies.get(0).getDocumentID(), databaseManager.getDocuments(1).getID());
Assert.assertEquals(user2.checkedOutCopies.get(0).getDueDate(), "26 March");
Assert.assertEquals(user2.checkedOutCopies.get(1).getDocumentID(), databaseManager.getDocuments(5).getID());
Assert.assertEquals(user2.checkedOutCopies.get(1).getDueDate(), "19 March");
}
/**
* Initial state:
* p1 checked-out b1 on February 9th and b2 on February 2nd
* p2 checked-out b1 on February 5th and av1 on February 17th
* Action:
* the librarian checks the due dates of documents checked out by p1
* the librarian checks the due dates of documents checked out by p2
* Effect: overdue should be right
*/
@Test
public void TestCase8() {
TestCase1();
DatabaseManager databaseManager = new DatabaseManager(DATABASE_FILE_NAME);
Session session = new Session((databaseManager.getUserCard(1010).userType), 9, 2);
session.userCard = databaseManager.getUserCard(1010);
MainForm mainForm = new MainForm();
mainForm.setSession(session);
mainForm.setDatabaseManager(databaseManager);
mainForm.setActionManager(databaseManager.actionManager);
mainForm.selectDocument(1);
mainForm.checkOut(databaseManager.getDocuments(1));
Session session1 = new Session((databaseManager.getUserCard(1010).userType), 2, 2);
session1.userCard = databaseManager.getUserCard(1010);
mainForm.setSession(session1);
mainForm.selectDocument(2);
mainForm.checkOut(databaseManager.getDocuments(2));
///////////////////////////////////////////////////////////////////////////////
Session session2 = new Session((databaseManager.getUserCard(1011).userType), 5, 2);
session2.userCard = databaseManager.getUserCard(1011);
mainForm.setSession(session2);
mainForm.selectDocument(1);
mainForm.checkOut(databaseManager.getDocuments(1));
Session session3 = new Session((databaseManager.getUserCard(1011).userType), 17, 2);
session3.userCard = databaseManager.getUserCard(1011);
mainForm.setSession(session3);
mainForm.selectDocument(4);
mainForm.checkOut(databaseManager.getDocuments(4));
////////////////////////////////////////////////////////////////////////////////////
Session sessionLib = new Session((databaseManager.getUserCard(1).userType), 5, 3);
sessionLib.userCard = databaseManager.getUserCard(1);
mainForm.setSession(sessionLib);
UserCard user1 = databaseManager.getUserCard(1010);
Assert.assertEquals(user1.checkedOutCopies.size(), 2);
Assert.assertEquals(user1.checkedOutCopies.get(0).getDocumentID(), databaseManager.getDocuments(1).getID());
Assert.assertEquals(user1.checkedOutCopies.get(0).getOverdue(sessionLib), 0);
Assert.assertEquals(user1.checkedOutCopies.get(1).getDocumentID(), databaseManager.getDocuments(2).getID());
Assert.assertEquals(user1.checkedOutCopies.get(1).getOverdue(sessionLib), 3);
UserCard user2 = databaseManager.getUserCard(1011);
Assert.assertEquals(user2.checkedOutCopies.size(), 2);
Assert.assertEquals(user2.checkedOutCopies.get(0).getDocumentID(), databaseManager.getDocuments(1).getID());
Assert.assertEquals(user2.checkedOutCopies.get(0).getOverdue(sessionLib), 7);
Assert.assertEquals(user2.checkedOutCopies.get(1).getDocumentID(), databaseManager.getDocuments(4).getID());
Assert.assertEquals(user2.checkedOutCopies.get(1).getOverdue(sessionLib), 2);
}
/**
* Initial state: TC1
* Action:
* simulate a power loss (stop the application)
* re-run the application
* the librarian checks patrons and documents of the system
* Effect: all information should be saved
*/
@Test
public void TestCase9() {
TestCase1();
DatabaseManager databaseManager = new DatabaseManager(DATABASE_FILE_NAME);
Session session = new Session(databaseManager.getUserCard(1).userType, 9, 3);
session.endSession();
DatabaseManager databaseManager1 = new DatabaseManager(DATABASE_FILE_NAME);
Assert.assertEquals(databaseManager1.getDocuments(1).availableCopies.size(), 3);
Assert.assertEquals(databaseManager1.getDocuments(2).availableCopies.size(), 2);
Assert.assertEquals(databaseManager1.getDocuments(3).availableCopies.size(), 1);
Assert.assertEquals(databaseManager1.getDocuments(4).availableCopies.size(), 1);
Assert.assertEquals(databaseManager1.getDocuments(5).availableCopies.size(), 1);
Assert.assertNotNull(databaseManager1.getUserCard(1010));
Assert.assertNotNull(databaseManager1.getUserCard(1011));
Assert.assertNotNull(databaseManager1.getUserCard(1100));
}
}
|
/*
* Joaquin Bello
*/
public class Ejercicio04 {
public static void main(String[] args) {
for (int numero = 320; numero >= 160; numero -= 20) {
System.out.println(numero);
}
}
}
|
package com.example.bigdata.service;
import com.example.bigdata.pojo.Screen;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
@Service
public class IOService {
public static final String SCREENS_PATH = "src/main/resources/static/screens/";
public static final String TEMPLATES_PATH = "src/main/resources/templates/";
public static final String TEMPLATE_PATH = "src/main/resources/templates/template";
public static final String SCREEN_PATH = "src/main/resources/templates/screen";
public static final String TEST = "src/main/resources/templates/screen20.html";
public void get() {
//String path = SCREENS_PATH + "15.html";
File f = new File(TEST);
System.out.println(f.exists());
}
/**
* ๆ นๆฎscreen_blocksๅๅปบๆจกๆฟ
* @param screen_id
* @param screen_blocks
*/
public void createTemplate(String screen_id, String screen_blocks) {
String template_id = "1";
String template_path = TEMPLATE_PATH + template_id + ".html";
String dest_path = TEMPLATES_PATH + "screen" + screen_id + ".html";
File template = new File(template_path);
File dest = new File(dest_path);
try {
Files.copy(template.toPath(), dest.toPath());
}catch (Exception e) {
e.printStackTrace();
}
createTemplateDir(screen_id);
createTemplateJSFile(screen_id, Integer.parseInt(screen_blocks));
createTemplateRest(screen_id, Integer.parseInt(screen_blocks));
}
/**
* ๅๅปบๆจกๆฟๅจstatic็ธๅบ็็ฎๅฝ
* @param screen_id
*
*/
public void createTemplateDir(String screen_id) {
File f1 = new File(SCREENS_PATH + "screen"+ screen_id + "/pivot.txt");
if(!f1.getParentFile().exists()) {
f1.getParentFile().mkdirs();
}
File f2 = new File(SCREENS_PATH + "screen"+ screen_id + "/options/pivot.txt");
if(!f2.getParentFile().exists()) {
f2.getParentFile().mkdirs();
}
}
public void createTemplateJSFile(String screen_id, int screen_blocks) {
String options_path = SCREENS_PATH + "screen" + screen_id + "/options/";
for(int i = 1; i <= screen_blocks; i++) {
String block_script_path = options_path + "block" + i + "_script.js";
File block_script = new File(block_script_path);
try{
block_script.createNewFile();
}catch (Exception e) {
e.printStackTrace();
}
}
}
public void createTemplateRest(String screen_id, int screen_blocks) {
String screen_path = SCREEN_PATH + screen_id + ".html";
File screen = new File(screen_path);
try (
// ๅๅปบๆไปถๅญ็ฌฆๆต
FileWriter fw = new FileWriter(screen, true);
// ็ผๅญๆตๅฟ
้กปๅปบ็ซๅจไธไธชๅญๅจ็ๆต็ๅบ็กไธ
PrintWriter pw = new PrintWriter(fw, true);
) {
for(int i = 1; i <= screen_blocks; i++) {
pw.print("<script type=\"text/javascript\" th:src=\"@{/static/screens/screen" + screen_id + "/options/block" + i+ "_script.js}\"></script>\n");
}
pw.print("<script type=\"text/javascript\" th:src=\"@{/static/screens/screen" + screen_id + "/options/set_options.js}\"></script>\n");
pw.print("<script type=\"text/javascript\" th:src=\"@{/static/screens/screen" + screen_id + "/options/set_datas.js}\"></script>\n");
pw.print("</body>\n");
pw.print("</html>\n");
pw.flush();
pw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.example.test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class TestExample {
@Test
void test() {
// fail("Not yet implemented");
System.out.println("test successfully");
AddExample ae=new AddExample();
int actual=ae.addmethod(5, 5);
int expected=11;
assertEquals(expected, actual);
}
}
|
package accountReceivable;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import javax.swing.*;
public class MenuWindow
{
//loads frame
private JFrame mF;
private JLabel header = new JLabel();
private JLabel body = new JLabel();
private JButton queryButton = new JButton("Queries");
private JButton optionsButton = new JButton("Options");
private JButton DBinit = new JButton("SQL DB Initialization");
private JButton readMe = new JButton("ReadME");
private JButton quitButton = new JButton("Quit");
public FirmDB ARDB;
public MenuWindow()
{
mF= new JFrame("AR");
mF.setResizable(false);
mF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mF.setLayout(new BorderLayout());
mF.setVisible(true);
}
//method that loads Panels onto the frame.
public void MenuWindowLayout()
{
JPanel textP = new JPanel(new FlowLayout());
header.setText("Group 123's Account Receivable Program");
header.setFont(new Font("Serif", Font.BOLD, 18));
textP.add(header);
textP.setBackground(Color.RED);
JPanel contentPanel = new JPanel();
GridLayout layout = new GridLayout(0,1);
layout.setHgap(10);
layout.setVgap(10);
contentPanel.setLayout(layout);
contentPanel.add(queryButton);
contentPanel.add(optionsButton);
contentPanel.add(DBinit);
contentPanel.add(readMe);
contentPanel.add(quitButton);
queryButton.setToolTipText("Select this to update the database or run a Query.");
optionsButton.setToolTipText("Select this to open the Options menu.");
DBinit.setToolTipText("Select this to intialize the SQL database to default values.");
readMe.setToolTipText("Select this to understand how the program works");
quitButton.setToolTipText("Select this to Quit.");
//Add action listener to button
queryButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the Querybutton");
PromptWindow lolz = new PromptWindow();
lolz.promptLayout();
}
});
optionsButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the Optionsbutton");
Options lolzz = new Options();
lolzz.optionsLayout();
}
});
DBinit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Execute when DBinit button is pressed
System.out.println("You initialized the SQL database!");
try
{
Connection conn = SimpleDataSource.getConnection();
Statement stat = conn.createStatement();
ARDB = new FirmDB();
Invoice tempI = new Invoice();
Customer tempC = new Customer();
int invCount = tempI.countInvoices();
int custCount = tempC.countCustomers();
}
catch (SQLException e1)
{
System.out.println("Initializing went wrong!");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
readMe.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Execute when readme is selected
System.out.println("You clicked readMe, you should be brought to the readme");
System.exit(0);
}
});
quitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked quitbutton, you should be returned to the IDE");
System.exit(0);
}
});
contentPanel.setBackground(Color.ORANGE);
mF.add(contentPanel, BorderLayout.SOUTH);
mF.add(textP, BorderLayout.NORTH);
mF.pack();
}
}
|
package Pro20.ValidParentheses;
import java.util.Stack;
public class Solution
{
public boolean isValid(String s)
{
char[] list = s.toCharArray();
Stack<Character> stack = new Stack<Character>();
for (char temp : list)
{
if (temp == '(' || temp == '[' || temp == '{')
{
stack.push(temp);
}
if (temp == '}' && (stack.isEmpty() || stack.pop() != '{'))
{
return false;
}
if (temp == ')' && (stack.isEmpty() || stack.pop() != '('))
{
return false;
}
if (temp == ']' && (stack.isEmpty() || stack.pop() != '['))
{
return false;
}
}
if (!stack.isEmpty())
{
return false;
}
return true;
}
} |
package df.repository.entry.moniker;
import df.repository.entry.moniker.legalentity.LegalEntityCode;
import java.util.Objects;
public final class Moniker implements Locatable {
String area;
String audience;
String type;
LegalEntityCode legalEntityCode;
Long effectAt;
String monikerValue;
public Moniker(String area, String audience, String type, LegalEntityCode legalEntityCode) {
this(area, audience, type, legalEntityCode, null);
}
public Moniker(String area, String audience, String type, LegalEntityCode legalEntityCode, Long effectAt) {
this.area = area;
this.audience = audience;
this.type = type;
this.legalEntityCode = legalEntityCode;
this.effectAt = effectAt;
if (this.effectAt == null) {
this.monikerValue = this.area + "." + this.type + "." + this.audience + "." + this.legalEntityCode;
} else {
this.monikerValue = this.area + "." + this.type + "." + this.audience + "." + this.legalEntityCode + "@" + this.effectAt;
}
}
@Override
public String value() {
return monikerValue;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Moniker)) return false;
Moniker moniker = (Moniker) o;
return Objects.equals(monikerValue, moniker.monikerValue);
}
@Override
public int hashCode() {
return Objects.hash(monikerValue);
}
@Override
public String toString() {
return "Moniker{" +
"area='" + area + '\'' +
", audience='" + audience + '\'' +
", type='" + type + '\'' +
", legalEntityCode=" + legalEntityCode +
", effectAt=" + effectAt +
", monikerValue='" + monikerValue + '\'' +
'}';
}
}
|
package edu.umich.dpm.sensorgrabber.stream;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.Wearable;
public class SendMessageTask extends AsyncTask<String, Void, MessageApi.SendMessageResult> {
private static final String TAG = "SendMessageTask";
private byte[] mData;
public SendMessageTask() {
mData = null;
}
public SendMessageTask(byte[] data) {
mData = data;
}
@Override
protected MessageApi.SendMessageResult doInBackground(String... path) {
Log.d(TAG, "SendMessageTask: " + path[0] + ", " + mData);
GoogleApiClient client = MessengerService.getGoogleApiClient();
Node node = MessengerService.getConnectedNode();
if (client != null && node != null) {
return Wearable.MessageApi.sendMessage(
MessengerService.getGoogleApiClient(),
MessengerService.getConnectedNode().getId(),
path[0],
mData
).await();
}
else {
return null;
}
}
}
|
package com.map_project;
public class MapLocationManager
{
}
|
package gov.inl.HZGenerator.BrickFactory;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferShort;
import java.awt.image.DataBufferUShort;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
/**
* Nathan Morrical. Summer 2017.
* A raw volume is a single file volume who's width, height, depth, and bits per pixel must be provided for interpreting
*/
public class RawVolume extends Volume {
File rawFile;
/* Constructor */
public RawVolume(String path, int width, int height, int depth, int bitsPerPixel, ByteOrder byteOrder) throws Exception {
rawFile = new File(path);
if (rawFile == null) throw new Exception("invalid raw path provided");
if (width <= 0 || height <= 0 || depth <= 0)
throw new Exception("invalid volume dimensions");
if (!(bitsPerPixel == 8 || bitsPerPixel == 16))
throw new Exception("invalid bits per pixel. RawVolume only supports 8 or 16 bpp");
this.width = width;
this.height = height;
this.depth = depth;
this.bytesPerPixel = bitsPerPixel / 8;
this.byteOrder = byteOrder;
}
/* Seeks to an offset dependent on width and height, and then reads either shorts or bytes to a buffered image */
@Override public BufferedImage getSlice(int i) {
try {
int zOffset = (i * width * height) * bytesPerPixel;
int type = (bytesPerPixel == 1) ? BufferedImage.TYPE_BYTE_GRAY : BufferedImage.TYPE_USHORT_GRAY;
if (type == BufferedImage.TYPE_BYTE_GRAY) {
BufferedImage currentSlice = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
byte[] rawBytes = ((DataBufferByte) currentSlice.getRaster().getDataBuffer()).getData();
RandomAccessFile raf = new RandomAccessFile(rawFile, "r");
raf.seek(zOffset);
raf.read(rawBytes, 0, width * height);
return currentSlice;
} else if (type == BufferedImage.TYPE_USHORT_GRAY) {
BufferedImage currentSlice = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_GRAY);
short[] rawBytes = ((DataBufferUShort) currentSlice.getRaster().getDataBuffer()).getData();
RandomAccessFile raf = new RandomAccessFile(rawFile, "r");
raf.seek(zOffset);
byte[] data = new byte[2 * width * height];
raf.read(data, 0, 2 * width * height);
ByteBuffer bb = ByteBuffer.wrap(data).order(this.byteOrder);
for (int j = 0; j < width * height; ++j)
rawBytes[j] = (short)(((data[2 * j + 0] & 0xff) << 8) + (data[2 * j + 1] & 0xff));
return currentSlice;
}
} catch (Exception e) {
System.out.println("Something went wrong while updating raw image.");
}
return null;
}
/* Just a list of numbers, each number referring to a slice */
@Override public List<String> getSliceList() {
List<String> names = new ArrayList<>();
for (int i = 0; i < depth; ++i) {
names.add("Slice #" + Integer.toString(i));
}
return names;
}
}
|
package com.firedata.qtacker.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.io.Serializable;
import java.util.Objects;
import java.util.HashSet;
import java.util.Set;
/**
* A Maker.
*/
@Entity
@Table(name = "maker")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@org.springframework.data.elasticsearch.annotations.Document(indexName = "maker")
public class Maker implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Column(name = "maker_name")
private String makerName;
@OneToMany(mappedBy = "maker")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Model> models = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMakerName() {
return makerName;
}
public Maker makerName(String makerName) {
this.makerName = makerName;
return this;
}
public void setMakerName(String makerName) {
this.makerName = makerName;
}
public Set<Model> getModels() {
return models;
}
public Maker models(Set<Model> models) {
this.models = models;
return this;
}
public Maker addModels(Model model) {
this.models.add(model);
model.setMaker(this);
return this;
}
public Maker removeModels(Model model) {
this.models.remove(model);
model.setMaker(null);
return this;
}
public void setModels(Set<Model> models) {
this.models = models;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Maker)) {
return false;
}
return id != null && id.equals(((Maker) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "Maker{" +
"id=" + getId() +
", makerName='" + getMakerName() + "'" +
"}";
}
}
|
package quiz.runner.suryawanshi;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.sun.org.apache.xerces.internal.impl.dv.xs.BooleanDV;
import quiz.model.Ground;
import quiz.model.Match;
import quiz.model.QuizDataProvider;
import quiz.model.Team;
public class QuizRunner {
private QuizRunner() {
}
public static void main(String[] args) {
List<Team> teams = QuizDataProvider.getTeams();
System.out.println(teams);
// Quiz1.main(args);
// quiz2(teams);
quiz3(teams);
}
/**
* Method for Quiz 2
*
* @param teams
*/
public static void quiz2(List<Team> teams) {
System.out.println("-------------- Quiz 2 Solution 1 ---------------------------");
teams.stream().collect(Collectors.toMap(Team::getName, Team::getHomeGround)).entrySet()
.forEach(System.out::println);
// System.out.println(map);
System.out.println("-------------- Quiz 2 Solution 2 ---------------------------");
// Usage of limit may be useful to improve performance as we know only
// one pune team is there/can user findfirst too
System.out.println(teams.stream().filter(team -> QuizDataProvider.TEAM1.equals(team.getName())).limit(1)
.flatMap(team -> team.getMatches().stream())
.collect(Collectors.groupingBy(Match::getVenue, Collectors.counting())));
System.out.println("-------------- Quiz 2 Solution 3 ---------------------------");
System.out.println(teams.stream().filter(team -> QuizDataProvider.TEAM1.equals(team.getName())).limit(1)
.flatMap(team -> team.getMatches().stream()).mapToInt(Match::getRunsScored).sum()); // .collect(Collectors.summingInt(Match::getRunsScored)).toString());
System.out.println("-------------- Quiz 2 Solution 4 ---------------------------");
System.out.println("Did Pune team play a match at " + Ground.WANKHEDE.name() + " = "
+ teams.stream().filter(team -> QuizDataProvider.TEAM1.equals(team.getName())).limit(1)
.flatMap(team -> team.getMatches().stream())
.anyMatch(match -> Ground.WANKHEDE.equals(match.getVenue())));
System.out.println("-------------- Quiz 2 Solution 5 ---------------------------");
System.out.println("Matchs win By Pune team = "
+ teams.stream().filter(team -> QuizDataProvider.TEAM1.equals(team.getName()))
.flatMap(team -> team.getMatches().stream())
.filter(match -> match.getRunsScored() > match.getRunsConceded()).count());
}
/**
* Method for Quiz 2
*
* @param teams
*/
public static void quiz3(List<Team> teams) {
System.out.println("-------------- Quiz 3 Solution 1 A ---------------------------");
teams.stream().flatMap(team -> team.getMatches().stream())
.filter(match -> match.getMatchDate().compareTo(LocalDate.of(2017, 4, 4)) == 0).distinct()
.forEach(System.out::println);
System.out.println("-------------- Quiz 3 Solution 1 B ---------------------------");
teams.stream().flatMap(team -> team.getMatches().stream())
.filter(match -> match.getMatchDate().equals(LocalDate.of(2017, 4, 4))).forEach(System.out::println);
System.out.println("-------------- Quiz 3 Solution 2 ---------------------------");
Optional<Match> minItem = teams.stream().flatMap(team -> team.getMatches().stream())
.min((match1, match2) -> match1.getMatchDate().compareTo(match2.getMatchDate()));
Optional<Match> maxItem = teams.stream().flatMap(team -> team.getMatches().stream())
.max((match1, match2) -> match1.getMatchDate().compareTo(match2.getMatchDate()));
System.out.println(ChronoUnit.DAYS.between(minItem.get().getMatchDate(), maxItem.get().getMatchDate()));
System.out.println(
Duration.between(minItem.get().getMatchDate().atTime(0, 0), maxItem.get().getMatchDate().atTime(0, 0))
.toDays());
System.out.println("-------------- Quiz 3 Solution 3 ---------------------------");
teams.stream().flatMap(team -> team.getMatches().stream())
.collect(Collectors.groupingBy(match -> match.getTeam1Name())).entrySet().forEach(System.out::println);
System.out.println("-------------- Quiz 3 Solution 4 ---------------------------");
teams.stream().flatMap(team -> team.getMatches().stream()).forEach(System.out::println);
System.out.println("-------------- Quiz 3 Solution 4 ---------------------------");
BigDecimal team2RunScored = BigDecimal.valueOf(360);
BigDecimal team2ballFaced = BigDecimal.valueOf(240);
BigDecimal team2RunConceded = BigDecimal.valueOf(390).divide(BigDecimal.valueOf(360), 3, RoundingMode.CEILING);
IntStream.rangeClosed(1, 120)
.filter(noOfBallreq -> BigDecimal.valueOf(0.109)
.compareTo((team2RunScored.divide(BigDecimal.valueOf(team2ballFaced.intValue() + noOfBallreq),
3, RoundingMode.CEILING)).subtract(team2RunConceded)) < 0)
.max().ifPresent(System.out::print);
}
}
|
/*
Copyright 2015 Alfio Zappala
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 co.runrightfast.zest.fragments.mixins.akka;
import akka.actor.ActorIdentity;
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
import akka.actor.Identify;
import akka.actor.Inbox;
import akka.actor.PoisonPill;
import akka.actor.Terminated;
import co.runrightfast.akka.AkkaUtils;
import static co.runrightfast.akka.AkkaUtils.USER;
import static co.runrightfast.akka.AkkaUtils.WILDCARD;
import static co.runrightfast.commons.utils.ConcurrentUtils.awaitCountdownLatchIgnoringInterruptedException;
import co.runrightfast.zest.composites.services.akka.ActorSystemService;
import com.google.common.collect.ImmutableList;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.qi4j.api.common.Optional;
import org.qi4j.api.injection.scope.Service;
import org.qi4j.api.service.ServiceActivation;
import scala.concurrent.ExecutionContext;
import scala.concurrent.duration.Duration;
/**
* The service identity will be used for :
*
* <ol>
* <li>as the ActorSystem's name
* <li>to load the TypeSafe config which will be used to create the ActorSystem
* </ol>
*
* @author alfio
*/
@Slf4j
public abstract class ActorSystemServiceMixin implements ActorSystemService, ServiceActivation {
private ActorSystem actorSystem;
@Optional
@Service
private ExecutionContext executionContext;
@Override
public ActorSystem actorSystem() {
return actorSystem;
}
@Override
public void activateService() throws Exception {
final Config config = ConfigFactory.load(identity().get());
if (executionContext != null) {
this.actorSystem = ActorSystem.create(
identity().get(),
config,
getClass().getClassLoader(),
executionContext
);
} else {
this.actorSystem = ActorSystem.create(
identity().get(),
config
);
}
}
/**
* Each of the top level actors are watched for terminations. A PoisonPill is sent to each of the top level actors. After all top level actors have
* terminated, then the actor system is terminated.
*
* @throws Exception if anything goes wrong
*/
@Override
public void passivateService() throws Exception {
awaitTopLevelActorsTerminated(getTopLevelActors());
terminateActorSystem();
}
private void awaitTopLevelActorsTerminated(final List<ActorRef> topLevelActors) {
if (!topLevelActors.isEmpty()) {
topLevelActors.forEach(actorRef -> actorRef.tell(PoisonPill.getInstance(), ActorRef.noSender()));
final CountDownLatch latch = new CountDownLatch(topLevelActors.size());
final Inbox inbox = Inbox.create(actorSystem);
topLevelActors.forEach(actorRef -> {
log.info("Waiting for top level actor to terminate : {}", actorRef.path());
inbox.watch(actorRef);
});
new Thread(() -> {
int totalWaitTimeSeconds = 0;
while (true) {
try {
final Terminated terminated = (Terminated) inbox.receive(Duration.create(1, TimeUnit.SECONDS));
log.info("Actor is terminated : {}", terminated.actor().path());
latch.countDown();
if (latch.getCount() == 0) {
return;
}
} catch (final TimeoutException ex) {
log.warn("awaitTopLevelActorsTerminated() : total wait time is {} secs", ++totalWaitTimeSeconds);
}
}
}).start();
awaitCountdownLatchIgnoringInterruptedException(latch, java.time.Duration.ofSeconds(10), "Waiting for top level actors to terminate");
}
}
private void terminateActorSystem() {
final CountDownLatch latch = new CountDownLatch(1);
this.actorSystem.registerOnTermination(() -> latch.countDown());
final String actorSystemName = this.actorSystem.name();
this.actorSystem.terminate();
awaitCountdownLatchIgnoringInterruptedException(latch, java.time.Duration.ofSeconds(10), String.format("Waiting for ActorSystem (%s) to terminate", actorSystemName));
log.info("ActorSystem has terminated : {}", actorSystemName);
}
private List<ActorRef> getTopLevelActors() {
final ActorSelection topLevelActorsSelection = this.actorSystem.actorSelection(AkkaUtils.actorPath(USER, WILDCARD));
final Inbox inbox = Inbox.create(actorSystem);
topLevelActorsSelection.tell(new Identify(Boolean.TRUE), inbox.getRef());
final ImmutableList.Builder<ActorRef> actorRefs = ImmutableList.builder();
while (true) {
try {
final ActorIdentity identity = (ActorIdentity) inbox.receive(Duration.create(1, TimeUnit.SECONDS));
if (identity.ref().isEmpty()) {
return actorRefs.build();
}
final ActorRef actorRef = identity.getRef();
log.info("top level actor : {}", actorRef.path());
actorRefs.add(actorRef);
} catch (final TimeoutException ex) {
return actorRefs.build();
}
}
}
}
|
//package com.socialteinc.socialate;
//
//import android.app.Activity;
//import android.app.Instrumentation;
//import android.content.Intent;
//import android.os.Looper;
//import android.support.annotation.NonNull;
//import android.support.design.widget.FloatingActionButton;
//import android.support.test.espresso.ViewAction;
//import android.support.test.espresso.action.ViewActions;
//import android.support.test.espresso.contrib.RecyclerViewActions;
//import android.support.test.rule.ActivityTestRule;
//import android.support.test.runner.AndroidJUnit4;
//import android.util.Log;
//import android.view.View;
//import com.google.android.gms.tasks.OnCompleteListener;
//import com.google.android.gms.tasks.Task;
//import com.google.firebase.FirebaseApp;
//import com.google.firebase.auth.AuthResult;
//import com.google.firebase.auth.FirebaseAuth;
//import com.google.firebase.database.DatabaseReference;
//import com.google.firebase.database.FirebaseDatabase;
//import org.junit.Before;
//import org.junit.FixMethodOrder;
//import org.junit.Rule;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.junit.runners.MethodSorters;
//
//import static android.support.test.espresso.Espresso.onView;
//import static android.support.test.espresso.action.ViewActions.*;
//import static android.support.test.espresso.assertion.ViewAssertions.matches;
//import static android.support.test.espresso.intent.Intents.intending;
//import static android.support.test.espresso.intent.matcher.IntentMatchers.toPackage;
//import static android.support.test.espresso.matcher.ViewMatchers.*;
//import static junit.framework.Assert.assertEquals;
//import static junit.framework.Assert.assertFalse;
//import static org.hamcrest.Matchers.allOf;
//
//
//@RunWith(AndroidJUnit4.class)
//@FixMethodOrder(MethodSorters.NAME_ASCENDING)
//public class CommentsTest2 {
// private FirebaseAuth mAuth;
//// FirebaseDatabase mFireBaseDatabase;
//// DatabaseReference mLikesDatabaseReference;
//// FloatingActionButton mLikeButton;
//
//
// @Rule
// public ActivityTestRule<ViewEntertainmentActivity> rule = new ActivityTestRule<>(ViewEntertainmentActivity.class);
//
// @Before
// public void login(){
// FirebaseApp.initializeApp(rule.getActivity());
// mAuth = FirebaseAuth.getInstance();
// mAuth.signInWithEmailAndPassword("joe@gmail.com", "sandile")
// .addOnCompleteListener(rule.getActivity(), new OnCompleteListener<AuthResult>() {
// @Override
// public void onComplete(@NonNull Task<AuthResult> task) {
// if (task.isSuccessful()) {
// // Sign in success, update UI with the signed-in user's information
// } else {
// // If sign in fails, display a message to the user.
// Log.w("login activity", "signInWithEmail:failure", task.getException());
//
// }
// }
// });
// }
//
//
// @Test
// public void isDisplayedTest() throws InterruptedException {
// Thread.sleep(15000);
//
// onView(withId(R.id.ViewAddedAreaOwnerText)).check(matches(isDisplayed()));
// onView(withId(R.id.ViewAddedAreaAddressText)).check(matches(isDisplayed()));
// onView(withId(R.id.ViewAddedAreaImageView)).check(matches(isDisplayed()));
// onView(withId(R.id.authorImageView)).check(matches(isDisplayed()));
//
// onView(withId(R.id.ViewAddedAreaImageView)).perform(swipeUp());
//
// onView(withId(R.id.ViewAddedAreaDescText)).check(matches(isDisplayed()));
// onView(withId(R.id.navigationImageView)).check(matches(isDisplayed()));
// //onView(withId(R.id.de)).check(matches(isDisplayed()));
//
// }
//
// @Test
// public void testComment() throws InterruptedException{
// Thread.sleep(15000);
// onView(withId(R.id.ViewAddedAreaImageView)).perform(swipeUp());
// onView(withId(R.id.ViewAddedAreaDescText)).perform(swipeUp());
// onView(isRoot()).perform(swipeUp());
// onView(isRoot()).perform(ViewActions.swipeUp());
//
//// onView(withId(R.id.commentEditText)).check(matches(isDisplayed()));
//// onView(withId(R.id.commentImageButton)).check(matches(isDisplayed()));
//// Thread.sleep(4000);
//
// }
//
//// @Test
//// public void commentsTest() throws InterruptedException{
//// Thread.sleep(9000);
//// onView(withId(R.id.entertainmentSpotRecyclerView)).perform(RecyclerViewActions.actionOnItemAtPosition(3,click()));
////
//// Thread.sleep(3000);
//// onView(withId(R.id.displayNameTextView)).check(matches(isDisplayed()));
//// onView(withId(R.id.describeEditText)).check(matches(isDisplayed()));
//// onView(withId(R.id.fullNameTextView)).check(matches(isDisplayed()));
//// onView(withId(R.id.imageView2)).check(matches(isDisplayed()));
//// }
//
// @Test
// public void likeTest() throws InterruptedException {
// Thread.sleep(15000);
// onView(withId(R.id.likeFloatingActionButton)).perform(click());
// //onView(isRoot()).perform(ViewActions.pressBack());
// Thread.sleep(4000);
// }
//
//// @Test
//// public void viewAuthorTest() throws InterruptedException {
//// Thread.sleep(15000);
//// onView(withId(R.id.ViewAddedAreaOwnerText)).check(matches(isClickable()));
//// //onView(withId(R.id.ViewAddedAreaOwnerText)).perform(click());
//// //onView(isRoot()).perform(pressBack());
//// Thread.sleep(4000);
//// }
////
////
//// @Test
//// public void NavigationTest() throws InterruptedException{
//// Thread.sleep(15000);
//// onView(withId(R.id.navigationImageView)).check(matches(isClickable()));
//// //onView(withId(R.id.navigationImageView)).check(matches(isFocusable()));
//// onView(withId(R.id.navigationImageView)).perform(click());
//// Thread.sleep(2000);
////
//// }
//
// @Test
// public void testComments() throws InterruptedException{
// Thread.sleep(15000);
// onView(withId(R.id.ViewAddedAreaImageView)).perform(swipeUp());
// onView(withId(R.id.ViewAddedAreaDescText)).perform(swipeUp());
// onView(isRoot()).perform(swipeUp());
// Thread.sleep(1000);
// onView(isRoot()).perform(ViewActions.swipeUp());
//
// onView(withId(R.id.comment_recyclerView)).check(matches(isDisplayed())); //
// onView(allOf(withId(R.id.comment_recyclerView),
// withParent(withId(R.id.cardView2)),
// withParent(withId(android.R.id.content)), isDisplayed()));
//
// onView(withId(R.id.comment_recyclerView)).perform(RecyclerViewActions.scrollToPosition(1));
// //onView(withId(R.id.comment_recyclerView)).perform(swipeUp());
// Thread.sleep(4000);
// }
//
//// @Test
//// public void navigationTest2() throws InterruptedException{
//// // Build the result to return when the activity is launched.
//// Intent resultData = new Intent();
//// //String phoneNumber = "123-345-6789";
//// //resultData.putExtra("phone", phoneNumber);
////
//// Instrumentation.ActivityResult result =
//// new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
////
//// // Set up result stubbing when an intent sent to "contacts" is seen.
//// intending(toPackage("com.google.android.apps.maps")).respondWith(result);
////
//// // User action that results in "contacts" activity being launched.
//// // Launching activity expects phoneNumber to be returned and displayed.
//// onView(withId(R.id.navigationImageView)).perform(click());
////
//// // Assert that the data we set up above is shown.
//// //onView(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)));
////
//// }
//
//
//} |
package qdu.java.recruit.renwu.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import qdu.java.recruit.renwu.dao.SuperUserDaoMapper;
import qdu.java.recruit.renwu.entity.Paper;
import qdu.java.recruit.renwu.entity.SuperUser;
import qdu.java.recruit.renwu.entity.User;
@Repository
public class SuperDaoService {
@Autowired
private SuperUserDaoMapper dao;
/*
* ่ถ
็บง็จๆท็ปๅฝ
*/
public SuperUser getUser(String username) {
SuperUser user = null;
try {
user = dao.getUser(username);
} catch (Exception e) {
e.printStackTrace();
System.err.println("่ทๅ็จๆทๅคฑ่ดฅ");
}
return user;
}
/*
* ่ทๅๆฎ้็จๆทๅ่กจ
*/
public List<User> getuserlist(int index) {
int begin, end = 10;
begin = index * end - end;
try {
List<User> list = dao.getuserlist(begin, end);
return list;
} catch (Exception e) {
e.printStackTrace();
System.err.println("ๆฅ่ฏขๅ่กจๅคฑ่ดฅ");
return null;
}
}
/*
* ่ทๅ้ฎๅทๅ่กจ
*/
public List<Paper> getpaperList(int index) {
int begin, end = 10;
begin = index * end - end;
try {
List<Paper> list = dao.getpaperList(begin, end);
return list;
} catch (Exception e) {
e.printStackTrace();
System.err.println("ๆฅ่ฏขๅ่กจๅคฑ่ดฅ");
return null;
}
}
/*
* ๅ ้คๆฎ้็จๆท
*/
public boolean deleteUser(int id) {
try {
dao.deleteUser(id);
return true;
} catch (Exception e) {
e.printStackTrace();
System.err.println("ๅ ้ค็จๆทๅคฑ่ดฅ");
return false;
}
}
/*
* ็นๅฎๆฅ่ฏขไธไธช็จๆท
*/
public User getTheUser(int id) {
try {
User user = dao.getTheUser(id);
return user;
} catch (Exception e) {
e.printStackTrace();
System.err.println("่ทๅๅไธช็จๆทๅคฑ่ดฅ");
return null;
}
}
}
|
package com.webstore.shoppingcart.dto.request;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
@Builder
public class UserRequestDTO {
@NotNull
@NotBlank
@Size(max = 50)
private String name;
@NotNull
@NotBlank
@Size(max = 50)
@Email
private String email;
}
|
/*
* (C) Mississippi State University 2009
*
* The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is
* a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries
* and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in
* http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in
* all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html.
*/
/**
* This stand-alone program takes a module name as an argument, or "all"
* to make all modules' manifests.
*
*
* THIS PROGRAM IS NOT YET IN WORKING ORDER!!!!!!!!!!!!!
* The comments are accurate (I think), but the argument parsing seems out of whack.
* I recommend fixing this to save time making manifests.
* Or come up with another method.
*
*
* @author Paul Cleveland
*
*/
import java.io.*;
public class ManifestMaker {
public static String DEF_DIR_WTCORE = "jars";
public static String DEF_DIR_SDL = "jars";
public static String DEF_DIR_XJ3D = "lib";
public static String DEF_DIR_MANIFEST = "manifests";
public static String DEF_MANIFEST_SUFFIX = "_MANIFEST.MF";
public static String DEF_MODULE_PACKAGE = "org.webtop.module";
public static String CONFIG_FILE = "manifestmaker.conf";
public static String[] DEF_MODULE_LIST = {};
//I got lazy and copied this from below.
static final String HELP_TEXT =
"Usage: # java ManifestMaker [-m MODULE_NAME] [-d MANIF_DIR] [-p PACKAGE.NAME] libdir1 libdir2 ..." +
"OPTIONS:\n" +
" -d : Specify the directory relative to execution where the manifest file\n" +
" is to be stored. MANIF_DIR must contain no spaces. If omitted this\n" +
" option defaults to 'manifests'. Remember that whatever you put after '-d'" +
" WILL be considered the directory to store the manifest in and WILL NO be\n" +
" considered for anything else.\n" +
"\n" +
" -m : Specifiy a module by giving it's MODULE_NAME. A manifest for that\n" +
" module will be created with the name MODULE_NAME_MANIFEST.MF in the\n" +
" directory MANIF_DIR. MODULE_NAME must contain no spaces.\n" +
"\n" +
" If this option is omitted, manifest files will be made with the\n" +
" described naming convention for all the names listed in manifestmaker.conf.\n" +
"\n" +
" -p : Specify the package that the module class belongs to, or default to org.webtop.module" +
"\n" +
" You must include at least one directory for libraries (libdir). There are\n" +
" no defaults for these options.\n" +
"\n" +
" Example: #java ManifestMaker -m Geometrical -d manifests libs jars\n" +
" This would run ManifestMaker to create the manifest GEOMETRICAL_MANIFEST.MF,\n" +
" including all the jar files in subdirectories 'libs' and 'jars' and store\n" +
" the created manifest in subdirectory 'manifests'.\n" +
"WARNING: THIS PROGRAM IS NOT VERY FAULT-TOLERANT";
/**
* See the HELP_TEXT member for a usage description, or simply run the program with
* no arguments.
*/
public static void main(String[] args) {
if(args.length < 2) {
System.err.println(HELP_TEXT);
System.exit(-1);
}
String moduleName = null;
int moduleNameIndex = 0;
String manifestDir = DEF_DIR_MANIFEST;
int manifestDirIndex = 0;
String manifestName = null;
String modulePackage = DEF_MODULE_PACKAGE;
int modulePackageIndex = 0;
int totalOptions = 0;
//Get option-value pairs.
for(int i=0; i<args.length && i<7; i++) {
//Module name given?
if(args[i]=="-m") {
i++;
moduleName = args[i];
moduleNameIndex = i;
i++;
totalOptions++;
}
else if(args[i]=="-d") {
i++;
manifestDir = args[i];
manifestDirIndex = i;
i++;
totalOptions++;
}
else if(args[i]=="-p") {
i++;
modulePackage = args[i];
modulePackageIndex = i;
i++;
totalOptions++;
}
}
System.out.println("module = " + moduleName + ", dir = " + manifestDir + ", package = " + modulePackage);
//Now we figure out where to start parsing library directories
int firstLibIndex = totalOptions*2 + 1; //*2 for -option <option_value>, +1 for next argument
System.out.println("first lib at index " + firstLibIndex);
//Get a list of all the libdirs
String[] libDirs = new String[args.length - firstLibIndex];
for(int i=firstLibIndex, j=0; i<args.length; i++)
libDirs[j] = args[i];
for(int i=0; i<libDirs.length; i++)
System.out.println("libDirs[i] = " + libDirs[i]);
//Once you have the names and directories, get a list of the jars.
String[][] jars = new String[libDirs.length][];
for(int i=0; i<jars.length; i++)
jars[i] = getJars(libDirs[i]);
//Note that by this time, 'moduleName' should either contain a name or be null.
if(moduleName==null) {
//Not so sure if this will work. I designed the makeManifest() method as the 'else' case below.
//Thorough testing suggested.
for(int i=0; i<DEF_MODULE_LIST.length; i++)
makeManifest(DEF_MODULE_LIST[i], modulePackage, manifestDir, jars);
}
//If module name specified, make that module's manifest
else {
makeManifest(moduleName, modulePackage, manifestDir, jars);
} // end else (moduleName specified)
} //end main()
/**
*
* @param moduleName Name of the module
* @param modulePackage Name of the module's package parent package (e.g. org.webtop.module)
* @param manifestDir Name of the directory to store the manifest in
* @param jars String[][] of jar filenames.
*/
private static void makeManifest(String moduleName, String modulePackage, String manifestDir, String[][] jars) {
/* Process:
* 1. Write generic manifest headers to contents
* 2. Write Main-class attribute to contents
* 3. Write Class-path attribute to contents
* 4. Write contents to fout
*/
FileWriter fout = null;
StringWriter contents = new StringWriter();
//Before getting started, let's make sure we can open the output file.
String manifestName = manifestDir + File.pathSeparator + moduleName.toUpperCase() + DEF_MANIFEST_SUFFIX;
System.out.println("Creating manifest " + manifestName);
try {
fout = new FileWriter(manifestName);
}
catch(IOException ioe) {
ioe.printStackTrace();
System.out.println("\n\nError: Could not open file " + manifestName);
System.exit(-1);
}
contents.write("MANIFEST-VERSION: 1.0\n");
contents.write("Main-Class: " + modulePackage + "." + moduleName + "\n");
//Add jars
/********************* NEW WAY ****************************/
contents.write("Class-path: ");
for(int i=0; i<jars.length; i++)
for(int j=0; j<jars[i].length; j++)
if(jars[i][j]!=null && jars[i][j]!="")
contents.write(jars[i][j]); //Should not put in a \n. MUST NOT!
/******************* END NEW WAY **************************/
//End the Class-path attribute with a newline...
contents.write("\n");
//Finally, print contents to the file fout.
try {
fout.write(contents.getBuffer().toString());
}
catch(IOException ioe) {
ioe.printStackTrace();
System.out.println("\n\nError: Could not write file " + manifestName);
System.exit(-1);
}
try {
fout.close();
}
catch(Exception e) {
System.out.println("Error closing manifest file!");
}
//Notifiy user that program is finished
System.out.println("Wrote manifest to " + manifestName);
System.out.println("Finished!");
} //end ManifestMaker.makeManifest()
/**
* Takes a directory as an argument and returns a String array with all
* the jar filenames in the given directory.
* @param dir Directory to be searched.
* @return Array of jar filenames in dir.
*/
public static String[] getJars(String dirname) {
return getResources(dirname, ".jar");
}
/**
* A generic method for getting resouces, just in case having a generic
* method proves handy one day.
*
* Generally, if this encounters a problem, it returns {""} so that the program
* will complete but no invalid data will be written to the manifest. This directory
* will just not have any files listed.
*
* @param dirname Directory to search
* @param _ext File extension to filter on
* @return Array of resource files ending in _ext
*/
public static String[] getResources(String dirname, String _ext) {
String[] resources = {""};
if(dirname==null) {
System.out.println("Warning, dirname null. Returning {\"\"}.");
return resources;
}
final String ext = _ext;
//Create a File object from 'dir'
File dir = null;
try {
dir = new File(dirname);
}
catch(NullPointerException npe) {
System.out.println("Error opening directory " + dirname + "!");
npe.printStackTrace();
}
//Check that 'dir' is a dir
if(!dir.isDirectory()) {
System.out.println(dirname + " is not a directory!");
System.out.println("Returning {\"\"}.");
return resources;
}
//So we have a handle to a valid directory. List the appropriate files.
resources = dir.list(
//This anonymous interface implementation will look for files ending in 'ext'
new FilenameFilter() {
public boolean accept(File dir, String filename) {
return !filename.equals(ext) &&
!filename.equals("") &&
filename.endsWith(ext);
}
}
);
return resources;
}//end ManifestMaker.getResources()
} //end class ManifestMaker
|
package org.jphototagger.program.module.programs;
import org.jphototagger.lib.swing.Dialog;
import org.jphototagger.lib.swing.util.ComponentUtil;
/**
* @author Elmar Baumann
*/
public class EditDefaultProgramsDialog extends Dialog {
private static final long serialVersionUID = 1L;
public EditDefaultProgramsDialog() {
super(ComponentUtil.findFrameWithIcon(), true);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
* content of this method is always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
private void initComponents() {//GEN-BEGIN:initComponents
panelEditDefaultPrograms = new org.jphototagger.program.module.programs.EditDefaultProgramsPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jphototagger/program/module/programs/Bundle"); // NOI18N
setTitle(bundle.getString("EditDefaultProgramsDialog.title")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelEditDefaultPrograms, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelEditDefaultPrograms, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private org.jphototagger.program.module.programs.EditDefaultProgramsPanel panelEditDefaultPrograms;
// End of variables declaration//GEN-END:variables
}
|
package com.sbs.sbsattend;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WatchTableActivity extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.table);
init();
}
private void init() {
webView = (WebView) findViewById(R.id.webView);
// WebViewๅ ่ฝฝweb่ตๆบ
webView.loadUrl("http://192.168.50.88:8890/jsjwork/");
//่ฎพ็ฝฎWebViewๅฑๆง๏ผ่ฝๅคๆง่กJavascript่ๆฌ
webView.getSettings().setJavaScriptEnabled(true);
//่ฎพ็ฝฎๅ ่ฝฝ่ฟๆฅ็้กต้ข่ช้ๅบๆๆบๅฑๅน
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
//ไผๅ
ไฝฟ็จ็ผๅญ
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
// ่ฆ็WebView้ป่ฎคไฝฟ็จ็ฌฌไธๆนๆ็ณป็ป้ป่ฎคๆต่งๅจๆๅผ็ฝ้กต็่กไธบ๏ผไฝฟ็ฝ้กต็จWebViewๆๅผ
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// ่ฟๅๅผๆฏtrue็ๆถๅๆงๅถๅปWebViewๆๅผ๏ผไธบfalse่ฐ็จ็ณป็ปๆต่งๅจๆ็ฌฌไธๆนๆต่งๅจ
view.loadUrl(url);
return true;
}
});
}
}
|
package com.kaizenmax.taikinys_icl.view;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.kaizenmax.taikinys_icl.R;
import com.kaizenmax.taikinys_icl.backgroundservices.DataDownloadService;
import com.kaizenmax.taikinys_icl.backgroundservices.ExampleService;
import com.kaizenmax.taikinys_icl.model.MobileDatabase;
import com.kaizenmax.taikinys_icl.pojo.DataSetMasterPojo;
import com.kaizenmax.taikinys_icl.pojo.FaMasterPojo;
import com.kaizenmax.taikinys_icl.pojo.FarmerDetailsPojo;
import com.kaizenmax.taikinys_icl.pojo.PromoFarmerMeetingPojo;
import com.kaizenmax.taikinys_icl.pojo.RetailerDetailsPojo;
import com.kaizenmax.taikinys_icl.pojo.UsersPojo;
import com.kaizenmax.taikinys_icl.pojo.VillagesPojo;
import com.kaizenmax.taikinys_icl.presenter.IndividualFarmerContactActivityPresenter;
import com.kaizenmax.taikinys_icl.presenter.IndividualFarmerContactActivityPresenterInterface;
import com.kaizenmax.taikinys_icl.util.MultiSelectionSpinner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class IndividualFarmerContactMainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
EditText dateOfActivityEditText;
Spinner cropCategorySpinner;
Spinner cropFocusSpinner;
MultiSelectionSpinner productFocusMultiSpinner;
EditText observationsEditText;
EditText farmerNameEditText;
AutoCompleteTextView villageNameEditText;
EditText farmerMobileEditText;
EditText landAcresEditText;
EditText expensesEditText;
TextView retailerDetailsTextView;
private android.support.v7.widget.LinearLayoutCompat parentLinearLayout;
public LinearLayout retailerLayout;
//Retailer details variables are also to be taken here
AutoCompleteTextView firmName;
EditText proprietorName;
EditText retailerMobile;
Button addRowBtn;
Button deleteRowBtn;
Button saveButton;
// VARIABLES OTHER THAN COMPONENTS
DatePickerDialog picker;
//MobileDatabase dbHelper;
RequestQueue requestQueue;
List<String> cropCategories;
List<String> cropFocusList;
String selectedCropCategory;
String selectedCropFocus;
private static IndividualFarmerContactMainActivity instance;
public static Integer dbCreateStatus=0;
public static Integer dbInsertSTatus=0;
public static Integer dbRetriveSTatus=0;
List<View> viewList;
List<RetailerDetailsPojo> retailerDetailsPojoList;
ProgressBar progressBar;
SharedPreferences sharedpreferences;
IndividualFarmerContactActivityPresenterInterface individualFarmerContactActivityPresenterInterface;
String clientName;
String faOfficeState;
MobileDatabase dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_individual_farmer_contact_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}); */
//
viewList=new ArrayList<View>();
cropCategories=new ArrayList<String>();
cropFocusList=new ArrayList<String>();
retailerDetailsPojoList=new ArrayList<RetailerDetailsPojo>();
dbHelper= new MobileDatabase(this);
//
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
// GETTING VALUES OF COMPONENTS
dateOfActivityEditText = findViewById(R.id.dateOfActivity);
dateOfActivityEditText.setInputType(InputType.TYPE_NULL);
// // it will not allow cursor to go to this field i.e non-focusable
// dateOfActivityEditText.setShowSoftInputOnFocus(false);
cropCategorySpinner = findViewById(R.id.cropCategory);
cropFocusSpinner = findViewById(R.id.cropFocus);
productFocusMultiSpinner = findViewById(R.id.productFocus);
observationsEditText = findViewById(R.id.observations);
farmerNameEditText = findViewById(R.id.farmerName);
villageNameEditText = findViewById(R.id.village);
farmerMobileEditText = findViewById(R.id.farmerMob);
landAcresEditText = findViewById(R.id.acres);
expensesEditText = findViewById(R.id.expenses);
retailerDetailsTextView=findViewById(R.id.retailerDetailsText);
firmName = findViewById(R.id.firmName);
proprietorName = findViewById(R.id.propName);
retailerMobile = findViewById(R.id.retailerMobile);
addRowBtn = findViewById(R.id.addButton);
deleteRowBtn = findViewById(R.id.deleteButton);
saveButton = findViewById(R.id.saveBtn);
instance=this;
individualFarmerContactActivityPresenterInterface = new IndividualFarmerContactActivityPresenter();
progressBar=findViewById(R.id.pBar);
progressBar.setVisibility(View.GONE);
//GETTING VALUES OF COMPONENTS ENDS
try {
clientName = individualFarmerContactActivityPresenterInterface.getClientName();
} catch (Exception e) {
e.printStackTrace();
}
try {
faOfficeState=individualFarmerContactActivityPresenterInterface.getStateName();
} catch (Exception e) {
e.printStackTrace();
}
//ADDING CALENDER ON DATE OF ACTIVITY
dateOfActivityEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar clndr = Calendar.getInstance();
int day = clndr.get(Calendar.DAY_OF_MONTH);
int month = clndr.get(Calendar.MONTH);
int year = clndr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(IndividualFarmerContactMainActivity.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
dateOfActivityEditText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.getDatePicker().setMaxDate(new Date().getTime());
picker.show();
dateOfActivityEditText.setFocusable(false);
}
});
//ADDING CALENDER ON DATE OF ACTIVITY ENDS
getDataSetEntriesMethod(); //method to get entries of all dataset table
// dbHelper = new MobileDatabase(this);
// ADDING RETAILER DETAILS LAYOUT
parentLinearLayout = findViewById(R.id.parent_linear_layout);
retailerLayout = findViewById(R.id.retailerDetails);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.retailer_details_multiple_layout, null);
// Add the new row before the add field button.
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 2);
firmName=rowView.findViewById(R.id.firmName);
viewList.add(rowView);
setAdapterOnFirmName(rowView);
// ADDING RETAILER DETAILS LAYOUT ENDS
//SETTING LIST IN PRODUCT FOCUS
List<String> productlist = new ArrayList<String>();
//String clientName = dbHelper.getClientName();
//String faOfficeState=dbHelper.getStateName();
try {
productlist=individualFarmerContactActivityPresenterInterface.getProductFocusList(clientName,faOfficeState);
productFocusMultiSpinner.setItems(productlist);
} catch (Exception e) {
e.printStackTrace();
}
// Toast.makeText(IndividualFarmerContactActivity.this, "ClientName "+clientName +" State"+faOfficeState, Toast.LENGTH_SHORT).show();
//SETTING LIST IN PRODUCT FOCUS ENDS
List<String> villageList=new ArrayList<String>();
// villageList=dbHelper.getVillageList();
try {
villageList = individualFarmerContactActivityPresenterInterface.getVillageList();
} catch (Exception e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,villageList);
villageNameEditText.setAdapter(adapter);
villageNameEditText.setThreshold(1);
// cropCategories=dbHelper.getCropCategories(); to be removed
try {
cropCategories=individualFarmerContactActivityPresenterInterface.getCropCategories();
} catch (Exception e) {
e.printStackTrace();
}
cropFocusList.add("Select Focus Crop*");
// villagesLocalTest();
//usersLocalTest();
//localTestingFaMaster();
// testingLocalRetrieval();//TEST method to retrieve local entries
//Adding List to Crop Category
ArrayAdapter<String> cropCategoryDataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, cropCategories);
cropCategoryDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cropCategorySpinner.setAdapter(cropCategoryDataAdapter);
//Adding List Crop Category Ends
// Adding List to CropFocus
ArrayAdapter<String> cropFocusDataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, cropFocusList);
cropFocusDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cropFocusSpinner.setAdapter(cropFocusDataAdapter);
//Adding List to CropFocus
//Adding Listener to Crop category so that crop Focus list can be according to selected crop category
cropCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedCropCategory= cropCategories.get(position);
// cropFocusList= dbHelper.getCropFocus(selectedCropCategory);
try {
cropFocusList= individualFarmerContactActivityPresenterInterface.getCropFocus(selectedCropCategory);
} catch (Exception e) {
e.printStackTrace();
}
ArrayAdapter<String> cropFocusDataAdapter = new ArrayAdapter<String>(IndividualFarmerContactMainActivity.this, android.R.layout.simple_spinner_dropdown_item, cropFocusList);
cropFocusDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cropFocusSpinner.setAdapter(cropFocusDataAdapter);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Adding Listener to Crop category so that crop Focus list can be according to selected crop category Ends
//Adding Listener to CropFocus to get selectedCropFocus
cropFocusSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedCropFocus= cropFocusList.get(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Adding Listener to CropFocus to get selectedCropFocus Ends
//Adding listener on save button
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(IndividualFarmerContactActivity.this, "dateOfActivity " + dateOfActivityEditText.getText(), Toast.LENGTH_SHORT).show();
String dateOfActivity_entered = dateOfActivityEditText.getText().toString();
String cropCategory_entered = selectedCropCategory;
String cropFocus_entered = selectedCropFocus;
//FOCUS MULTIPLE PRODUCTS ayga is line pr
String observations_entered = observationsEditText.getText().toString();
String farmerName_entered = farmerNameEditText.getText().toString();
String villageName_entered = villageNameEditText.getText().toString();
String farmerMobile_entered = farmerMobileEditText.getText().toString();
String landAcres_entered = landAcresEditText.getText().toString();
String expenses_entered = expensesEditText.getText().toString();
//RETAILER AYGA YHA is line m
String uploadFlagStatus = "No";
List<String> selectedProductsList = productFocusMultiSpinner.getSelectedStrings();
// Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
// setSupportActionBar(myToolbar);
if (dateOfActivity_entered.equalsIgnoreCase("") || cropCategory_entered.equalsIgnoreCase("")
|| cropFocus_entered.equalsIgnoreCase("")
|| selectedProductsList.size() == 0
|| farmerName_entered.equalsIgnoreCase("")
|| villageName_entered.equalsIgnoreCase("")
|| farmerMobile_entered.equalsIgnoreCase("")
|| landAcres_entered.equalsIgnoreCase("")
// removed by jyoti, bhavna in guidance of Vinod on 11/13/2019 || expenses_entered.equalsIgnoreCase("")
|| villageName_entered.trim().length()<2
|| farmerMobile_entered.trim().length()<10
) {
if (dateOfActivity_entered.equalsIgnoreCase("")) {
//dateOfActivityEditText.setHint("Please enter date of activity");//it gives user to hint
dateOfActivityEditText.setError("Please enter date of activity");//it gives user to info message //use any one //
}
if (cropCategory_entered.equalsIgnoreCase("Select Crop Category*")) {
// cropCategorySpinner.setHint("Please enter date of activity");//it gives user to hint
//cropCategorySpinner.setError("Please enter date of activity");//it gives user to info message //use any one //
TextView errorText = (TextView) cropCategorySpinner.getSelectedView();
errorText.setError("Please select crop category");
// errorText.setTextColor(Color.RED);//just to highlight that this is an error
// errorText.setText("my actual error text");//changes the selected item text to this
}
if (cropFocus_entered.equalsIgnoreCase("Select Crop Focus*")) {
// cropCategorySpinner.setHint("Please enter date of activity");//it gives user to hint
//cropCategorySpinner.setError("Please enter date of activity");//it gives user to info message //use any one //
TextView errorText = (TextView) cropFocusSpinner.getSelectedView();
errorText.setError("Please select crop focus");
// errorText.setTextColor(Color.RED);//just to highlight that this is an error
// errorText.setText("my actual error text");//changes the selected item text to this
}
if (selectedProductsList.size() == 0 ) {
// cropCategorySpinner.setHint("Please enter date of activity");//it gives user to hint
//cropCategorySpinner.setError("Please enter date of activity");//it gives user to info message //use any one //
TextView errorText = (TextView) productFocusMultiSpinner.getSelectedView();
errorText.setError("Please select product focus");
// errorText.setTextColor(Color.RED);//just to highlight that this is an error
// errorText.setText("my actual error text");//changes the selected item text to this
}
if (farmerName_entered.equalsIgnoreCase("")) {
// cropCategorySpinner.setHint("Please enter date of activity");//it gives user to hint
//cropCategorySpinner.setError("Please enter date of activity");//it gives user to info message //use any one //
farmerNameEditText.setError("Please enter farmer name");
//errorText.setTextColor(Color.RED);//just to highlight that this is an error
// errorText.setText("my actual error text");//changes the selected item text to this
}
if (villageName_entered.equalsIgnoreCase("")) {
//dateOfActivityEditText.setHint("Please enter date of activity");//it gives user to hint
villageNameEditText.setError("Please enter village");//it gives user to info message //use any one //
}
if (farmerMobile_entered.equalsIgnoreCase("")) {
//dateOfActivityEditText.setHint("Please enter date of activity");//it gives user to hint
farmerMobileEditText.setError("Please enter farmer mobile");//it gives user to info message //use any one //
}
if (landAcres_entered.equalsIgnoreCase("")) {
//dateOfActivityEditText.setHint("Please enter date of activity");//it gives user to hint
landAcresEditText.setError("Please enter land in acres");//it gives user to info message //use any one //
}
/* if (expenses_entered.equalsIgnoreCase("")) {
//dateOfActivityEditText.setHint("Please enter date of activity");//it gives user to hint
expensesEditText.setError("Please enter expenses");//it gives user to info message //use any one //
}
// removed by jyoti, bhavna in guidance of Vinod on 11/13/2019
*/
if(villageName_entered!=null && !villageName_entered.equals("") && villageName_entered.trim().length()<2)
{
villageNameEditText.setError("Please enter minimum two characters in village");
}
if(!farmerMobile_entered.trim().equals("") && farmerMobile_entered.trim().length()<10)
{
farmerMobileEditText.setError("Please enter ten digits in farmer mobile number");
}
} else {
// Toast.makeText(IndividualFarmerContactMainActivity.this, "HELLO", Toast.LENGTH_SHORT).show();
for (int i = 0; i < viewList.size(); i++) {
// Toast.makeText(IndividualFarmerContactMainActivity.this, "HII", Toast.LENGTH_SHORT).show();
EditText firmName = (viewList.get(i)).findViewById(R.id.firmName);
EditText retailerMobile = (viewList.get(i)).findViewById(R.id.retailerMobile);
EditText proprietorName = (viewList.get(i)).findViewById(R.id.propName);
// String as=zx.getText().toString();
RetailerDetailsPojo retailerDetailsPojo = new RetailerDetailsPojo();
retailerDetailsPojo.setFirmName(firmName.getText().toString());
retailerDetailsPojo.setRetailerMobile(retailerMobile.getText().toString());
retailerDetailsPojo.setPropName(proprietorName.getText().toString());
// Toast.makeText(IndividualFarmerContactMainActivity.this, "FirmName: " + firmName.getText().toString(), Toast.LENGTH_SHORT).show();
retailerDetailsPojoList.add(retailerDetailsPojo);
}
// String faOfficeDistrict=dbHelper.getFaOfficeDistrict();
String faOfficeDistrict="";
try {
faOfficeDistrict=individualFarmerContactActivityPresenterInterface.getFaOfficeDistrict();
} catch (Exception e) {
e.printStackTrace();
}
Calendar cal=Calendar.getInstance();
Date createdOn=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String createdOn_string = dateFormat.format(createdOn);
String createdby="";
try {
createdby=individualFarmerContactActivityPresenterInterface.getMobileFromSharedpreference();
} catch (Exception e) {
e.printStackTrace();
}
try {
individualFarmerContactActivityPresenterInterface.insertIFCdata("IFC", dateOfActivity_entered, villageName_entered,
cropFocus_entered, cropCategory_entered, farmerName_entered, farmerMobile_entered, landAcres_entered,
expenses_entered, observations_entered, uploadFlagStatus, retailerDetailsPojoList, selectedProductsList,
createdOn_string,createdby,clientName,faOfficeDistrict);
} catch (Exception e) {
e.printStackTrace();
}
//,farmerName_entered,farmerMobile_entered,landAcres_entered
// Toast.makeText(IndividualFarmerContactActivity.this, "Product ", Toast.LENGTH_SHORT).show();
dateOfActivityEditText.setText("");
cropCategorySpinner.setSelection(0);
cropFocusSpinner.setSelection(0);
productFocusMultiSpinner.setSelection(0);
//reset it also productFocusMultiSpinner
observationsEditText.setText("");
farmerMobileEditText.setText("");
villageNameEditText.setText("");
farmerNameEditText.setText("");
farmerMobileEditText.setText("");
landAcresEditText.setText("");
expensesEditText.setText("");
for (int i = 0; i < viewList.size(); i++) {
View view = viewList.get(i);
EditText firmName = view.findViewById(R.id.firmName);
EditText propName = view.findViewById(R.id.propName);
EditText retailerMobile = view.findViewById(R.id.retailerMobile);
//
firmName.setText("");
propName.setText("");
retailerMobile.setText("");
}
// proprietorName.setText("");
// retailerMobile.setText("");
Toast.makeText(IndividualFarmerContactMainActivity.this, "Saved successfully", Toast.LENGTH_LONG).show();
// Toast.makeText(IndividualFarmerContactActivity.this, "DB INSERT STATUS "+dbInsertSTatus, Toast.LENGTH_SHORT).show();
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
try {
individualFarmerContactActivityPresenterInterface.sendingDataToWebService();
} catch (Exception e) {
e.printStackTrace();
}
//sendingDataToWebService(); to be removed
}
}
}
});
//Adding listener on save button ends
//CODE TO START FOREGROUND SERVICE
Intent serviceIntent = new Intent(this, ExampleService.class);
serviceIntent.putExtra("inputExtra", "kuch bhi");
ContextCompat.startForegroundService(this, serviceIntent);
Intent serviceIntent2 = new Intent(this, DataDownloadService.class);
serviceIntent2.putExtra("inputExtra", "kuch bhiHo");
ContextCompat.startForegroundService(this, serviceIntent2);
//CODE TO START FOREGROUND SERVICE Ends
//CODE TO STOP FOREGROUND SERVICES
// Intent serviceIntent2 = new Intent(this, ExampleService.class);
//stopService(serviceIntent2);
} //On CREATE METHOD ENDING
public void getDataSetFromCloudAndLocalSave()
{
// Toast.makeText(this, "INSERTING DATA START :", Toast.LENGTH_SHORT).show();
// String url2 = "https://tvsfinal.herokuapp.com/service/dataSetMaster/E92M75GV9kUQnNURUWg4r9hge5";
progressBar.setVisibility(View.VISIBLE);
dateOfActivityEditText.setVisibility(View.GONE);
cropCategorySpinner.setVisibility(View.GONE);
cropFocusSpinner.setVisibility(View.GONE);
productFocusMultiSpinner.setVisibility(View.GONE);
observationsEditText.setVisibility(View.GONE);
farmerNameEditText.setVisibility(View.GONE);
villageNameEditText.setVisibility(View.GONE);
farmerMobileEditText.setVisibility(View.GONE);
landAcresEditText.setVisibility(View.GONE);
expensesEditText.setVisibility(View.GONE);
retailerDetailsTextView.setVisibility(View.GONE);
saveButton.setVisibility(View.GONE);
addRowBtn.setVisibility(View.GONE);
for (int i=0;i<viewList.size();i++)
{
View v=viewList.get(i);
v.findViewById(R.id.firmName).setVisibility(View.GONE);
v.findViewById(R.id.retailerMobile).setVisibility(View.GONE);
v.findViewById(R.id.propName).setVisibility(View.GONE);
v.findViewById(R.id.deleteButton).setVisibility(View.GONE);
}
String awsProdKey= "E92M75GV9kUQnQQNURUWg4r9hge5" ;
String herokuTestingTaikinysKey ="E92M75GV9kUQnNURUWg4r9hge5" ;
String url2="https://taikinys.kaizenmax.com/rest/service/dataSetMaster/E92M75GV9kUQnQQNURUWg4r9hge5";
requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
url2,
null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
// Do something with response
//mTextView.setText(response.toString());
// Process the JSON
try{
// Loop through the array elements
int count=0;
// Toast.makeText(IndividualFarmerContactActivity.this, "LENGTH OF FETCHED DATA :"+response.length(), Toast.LENGTH_SHORT).show();
dbHelper.deleteAllEntriesOfDataSetMaster(); //deleting data set entries before inserting
for(int i=0;i<response.length();i++){
// Get current json object
JSONObject dataSetMaster = response.getJSONObject(i);
// Get the current student (json object) data
// String clientName = student.getString("clientName");
// String dataSetTitle = student.getString("dataSetTitle");
// String createdOn = student.getString("createdOn");
String dataSetTitle = dataSetMaster.getString("dataSetTitle");
String dataSetDescription = dataSetMaster.getString("dataSetDescription");
String element1 = dataSetMaster.getString("element1");
String element2 = dataSetMaster.getString("element2");
String element3 = dataSetMaster.getString("element3");
String element4 = dataSetMaster.getString("element4");
String number1=dataSetMaster.getString("number1");
String number2=dataSetMaster.getString("number2");
String text1=dataSetMaster.getString("text1");
String text2=dataSetMaster.getString("text2");
String date1=dataSetMaster.getString("date1");
String date2=dataSetMaster.getString("date2");
String status=dataSetMaster.getString("status");
String createdOn=dataSetMaster.getString("createdOn");
String createdBy=dataSetMaster.getString("createdBy");
String id=dataSetMaster.getString("id");
String clientName=dataSetMaster.getString("clientName");
// Toast.makeText(IndividualFarmerContactActivity.this, "Index Retrieved "+i, Toast.LENGTH_SHORT).show();
try {
if(dataSetTitle.equals("ClientDistrictRetailer"))
{
String faOfficeDistrict=dbHelper.getFaOfficeDistrict();
if(element1.equals(faOfficeDistrict))
{
// Toast.makeText(IndividualFarmerContactActivity.this, "FA DISTRICT OFFICE : "+faOfficeDistrict, Toast.LENGTH_SHORT).show();
//Toast.makeText(IndividualFarmerContactActivity.this, "Firm Name "+element2, Toast.LENGTH_SHORT).show();
dbHelper.insertDataSetMaster(dataSetTitle, dataSetDescription, element1, element2, element3, element4
, number1, number2, text1, text2, date1, date2,
status, new Date(),
createdBy, clientName);
count++;
}
}
else {
dbHelper.insertDataSetMaster(dataSetTitle, dataSetDescription, element1, element2, element3, element4
, number1, number2, text1, text2, date1, date2,
status, new Date(),
createdBy, clientName);
count++;
// Toast.makeText(IndividualFarmerContactActivity.this, "Index INSERT "+i+" status "+status, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
// Toast.makeText(IndividualFarmerContactActivity.this, "Values Index"+i+" clientName: "+clientName+" dataSetTitle: "+dataSetTitle+" Created on: "+createdOn, Toast.LENGTH_SHORT).show();
// Display the formatted json data in text view
// mTextView.append(firstName +" " + lastName +"\nAge : " + age);
// mTextView.append("\n\n");
}
Intent intent = new Intent(IndividualFarmerContactMainActivity.this, IndividualFarmerContactMainActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
// Toast.makeText(IndividualFarmerContactActivity.this, "COUNT "+count, Toast.LENGTH_SHORT).show();
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(IndividualFarmerContactMainActivity.this, "ERROR "+error.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
}
}
);
requestQueue.add(jsonArrayRequest);
}
public void getDataSetEntriesMethod()
{
// Toast.makeText(this, "FETCHING DATA", Toast.LENGTH_SHORT).show();
final Cursor cursor = dbHelper.getAllDataSetEntries();
// Toast.makeText(this, "CURSOR SIZE "+cursor.getCount(), Toast.LENGTH_SHORT).show();
if(cursor.getCount()==0)
{
getDataSetFromCloudAndLocalSave();
}
else {
int x = 0;
if (cursor != null && cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex(DataSetMasterPojo.DATASETMASTER_COLUMN_ID));
String dataSetTitle = cursor.getString(cursor.getColumnIndex(DataSetMasterPojo.DATASETMASTER_COLUMN_DATASET_TITLE));
String status=cursor.getString(cursor.getColumnIndex(DataSetMasterPojo.DATASETMASTER_COLUMN_STATUS));
//String element1 = cursor.getString(cursor.getColumnIndex(MobileDatabase.DATASETMASTER_COLUMN_ELEMENT1));
// String element2 = cursor.getString(cursor.getColumnIndex(MobileDatabase.DATASETMASTER_COLUMN_ELEMENT2));
x++;
// Toast.makeText(this, "Id from Local DB"+x +" datasettitle "+dataSetTitle, Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "SERIAL: "+x+" STATUS: "+status, Toast.LENGTH_SHORT).show();
// do what ever you want here
} while (cursor.moveToNext());
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
}
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
cursor.close();
}
}
//Method to add retailer details Layout
public void addRetailerRow(View v) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.retailer_details_multiple_layout, null);
// Add the new row before the add field button.
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 2);
firmName = ((View) rowView.getParent().getParent()).findViewById(R.id.firmName);
viewList.add(rowView);
setAdapterOnFirmName(rowView);
// Toast.makeText(IndividualFarmerContactActivity.getInstance(), "FIRM NAME "+rowView.findViewById(R.id.farmerName), Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "FIRM NAME " + firmName.getText(), Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "Proprietor NAME "+proprietorName.getText(), Toast.LENGTH_SHORT).show();
//Toast.makeText(this, "Retailer Name "+retailerMobile.getText(), Toast.LENGTH_SHORT).show();
}
//Method to delete retailer details Layout
public void deleteRetailerRow(View v) {
// Toast.makeText(this, "aaaa ", Toast.LENGTH_SHORT).show();
//https://stackoverflow.com/questions/3995215/add-and-remove-views-in-android-dynamically
/* View namebar = View.findViewById(R.id.namebar);
((ViewGroup) namebar.getParent()).removeView(namebar); */
// Toast.makeText(IndividualFarmerContactMainActivity.getInstance(), "VIEW "+v, Toast.LENGTH_SHORT).show();
View namebar = ((View) v.getParent().getParent()).findViewById(R.id.retailerDetails);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
parent.removeView(namebar);
}
viewList.remove(namebar);
}
public void testingLocalRetrieval()
{
Cursor z=dbHelper.getAllPromoEntries();
Integer id=null;
if (z != null && z.moveToFirst()) {
do {
id = z.getInt(z.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_ID));
String flagStatus=z.getString(z.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_UPLOAD_FLAG));
String village=z.getString(z.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_VILLAGE));
// Toast.makeText(this, "ID "+id+" FlagStatus "+flagStatus+" Village "+village, Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "Farmer Name "+fmname, Toast.LENGTH_SHORT).show();
// do what ever you want here
// List<FarmerDetailsPojo> farmerDetailsPojoList= dbHelper.getFarmerDetails();
List<FarmerDetailsPojo> FarmerDetailsPojoList=dbHelper.getFarmerDetails(id);
for (int i=0;i<FarmerDetailsPojoList.size();i++)
{
FarmerDetailsPojo farmerDetailsPojo=FarmerDetailsPojoList.get(i);
String farmerName=farmerDetailsPojo.getFarmerName();
Toast.makeText(instance, "Farmer Name "+farmerName, Toast.LENGTH_SHORT).show();
}
List<RetailerDetailsPojo> retailerList=dbHelper.getRetailerDetails(id);
for (int i=0;i<retailerList.size();i++)
{
RetailerDetailsPojo retailerDetailsPojo=retailerList.get(i);
//Toast.makeText(instance, "Firm Name "+retailerDetailsPojo.getFirmName(), Toast.LENGTH_SHORT).show();
}
} while (z.moveToNext());
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
}
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
z.close();
}
// Sending data to Web services Starts
// public void sendingDataToWebService()
//Sending data to Web services Ends
public static IndividualFarmerContactMainActivity getInstance() {
return instance;
}
public void getDataSetFromCloudAndLocalSaveBackGroundService() {
// Toast.makeText(this, "INSERTING DATA START :", Toast.LENGTH_SHORT).show();
// String url2 = "https://tvsfinal.herokuapp.com/service/dataSetMaster/E92M75GV9kUQnNURUWg4r9hge5";
// String url2="https://tvsfinal.herokuapp.com/rest/service/dataSetMaster/E92M75GV9kUQnNURUWg4r9hge5";
String url2="https://taikinys.kaizenmax.com/rest/service/dataSetMaster/E92M75GV9kUQnQQNURUWg4r9hge5";
requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
url2,
null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
// Do something with response
//mTextView.setText(response.toString());
// Process the JSON
try{
// Loop through the array elements
int count=0;
// Toast.makeText(IndividualFarmerContactActivity.this, "LENGTH OF FETCHED DATA :"+response.length(), Toast.LENGTH_SHORT).show();
dbHelper.deleteAllEntriesOfDataSetMaster(); //deleting data set entries before inserting
for(int i=0;i<response.length();i++){
// Get current json object
JSONObject dataSetMaster = response.getJSONObject(i);
// Get the current student (json object) data
// String clientName = student.getString("clientName");
// String dataSetTitle = student.getString("dataSetTitle");
// String createdOn = student.getString("createdOn");
String dataSetTitle = dataSetMaster.getString("dataSetTitle");
String dataSetDescription = dataSetMaster.getString("dataSetDescription");
String element1 = dataSetMaster.getString("element1");
String element2 = dataSetMaster.getString("element2");
String element3 = dataSetMaster.getString("element3");
String element4 = dataSetMaster.getString("element4");
String number1=dataSetMaster.getString("number1");
String number2=dataSetMaster.getString("number2");
String text1=dataSetMaster.getString("text1");
String text2=dataSetMaster.getString("text2");
String date1=dataSetMaster.getString("date1");
String date2=dataSetMaster.getString("date2");
String status=dataSetMaster.getString("status");
String createdOn=dataSetMaster.getString("createdOn");
String createdBy=dataSetMaster.getString("createdBy");
String id=dataSetMaster.getString("id");
String clientName=dataSetMaster.getString("clientName");
// Toast.makeText(IndividualFarmerContactActivity.this, "Index Retrieved "+i, Toast.LENGTH_SHORT).show();
try {
if(dataSetTitle.equals("ClientDistrictRetailer"))
{
String faOfficeDistrict=dbHelper.getFaOfficeDistrict();
// Toast.makeText(IndividualFarmerContactActivity.this, "FA DISTRICT OFFICE : "+faOfficeDistrict, Toast.LENGTH_SHORT).show();
if(element1.equals(faOfficeDistrict))
{
dbHelper.insertDataSetMaster(dataSetTitle, dataSetDescription, element1, element2, element3, element4
, number1, number2, text1, text2, date1, date2,
status, new Date(),
createdBy, clientName);
count++;
}
}
else {
dbHelper.insertDataSetMaster(dataSetTitle, dataSetDescription, element1, element2, element3, element4
, number1, number2, text1, text2, date1.toString(), date2.toString(),
status, new Date(),
createdBy, clientName);
count++;
// Toast.makeText(IndividualFarmerContactActivity.this, "Index INSERT "+i+" status "+status, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
// Toast.makeText(IndividualFarmerContactActivity.this, "Values Index"+i+" clientName: "+clientName+" dataSetTitle: "+dataSetTitle+" Created on: "+createdOn, Toast.LENGTH_SHORT).show();
// Display the formatted json data in text view
// mTextView.append(firstName +" " + lastName +"\nAge : " + age);
// mTextView.append("\n\n");
}
// Toast.makeText(IndividualFarmerContactActivity.this, "COUNT "+count, Toast.LENGTH_SHORT).show();
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(IndividualFarmerContactMainActivity.this, "ERROR "+error.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
}
}
);
requestQueue.add(jsonArrayRequest);
}
public void localTestingFaMaster()
{
Cursor cursor=dbHelper.getFaMasterAllEntries();
Integer id=null;
if (cursor != null && cursor.moveToFirst()) {
do {
String firstName=cursor.getString(cursor.getColumnIndex(FaMasterPojo.FAMASTER_COLUMN_FA_FIRSTNAME));
String lastName=cursor.getString(cursor.getColumnIndex(FaMasterPojo.FAMASTER_COLUMN_FA_LASTNAME));
String clientName=cursor.getString(cursor.getColumnIndex(FaMasterPojo.FAMASTER_COLUMN_FA_CLIENTNAME));
String faOfficeTerritory=cursor.getString(cursor.getColumnIndex(FaMasterPojo.FAMASTER_COLUMN_FA_OFFICE_TERRITORY));
String faValidityFrom=cursor.getString(cursor.getColumnIndex(FaMasterPojo.FAMASTER_COLUMN_FA_VALIDITY_FROM));
String faValidityTo=cursor.getString(cursor.getColumnIndex(FaMasterPojo.FAMASTER_COLUMN_FA_VALIDITY_TO));
String faDistrict=cursor.getString(cursor.getColumnIndex(FaMasterPojo.FAMASTER_COLUMN_FA_OFFICE_DISTRICT));
String headquarter=cursor.getString(cursor.getColumnIndex(FaMasterPojo.FAMASTER_COLUMN_FA_HEADQUARTER));
String faOfficeRegionalOffice=cursor.getString(cursor.getColumnIndex(FaMasterPojo.FAMASTER_COLUMN_FA_OFFICE_REGIONAL_OFFICE));
String faOfficeState=cursor.getString(cursor.getColumnIndex(FaMasterPojo.FAMASTER_COLUMN_FA_OFFICE_STATE));
String status=cursor.getString(cursor.getColumnIndex(FaMasterPojo.FAMASTER_COLUMN_FA_STATUS));
/* Toast.makeText(this, "firstName "+firstName
+" lastName "+lastName
+" clientName "+clientName
+" faOfficeTerritory "+faOfficeTerritory
+" faValidityFrom "+faValidityFrom
+" faValidityTo "+faValidityTo
+" faDistrict "+faDistrict
+" headquarter "+headquarter
+" faOfficeRegionalOffice "+faOfficeRegionalOffice
+" faOfficeState "+faOfficeState
+" status "+status, Toast.LENGTH_SHORT).show();
*/
} while (cursor.moveToNext());
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
}
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
cursor.close();
}
public void usersLocalTest()
{
Cursor cursor=dbHelper.getUsersAllEntries();
if (cursor != null && cursor.moveToFirst()) {
do {
String userName=cursor.getString(cursor.getColumnIndex(UsersPojo.USERS_COLUMN_USERNAME));
String password=cursor.getString(cursor.getColumnIndex(UsersPojo.USERS_COLUMN_PASSWORD));
String otp=cursor.getString(cursor.getColumnIndex(UsersPojo.USERS_COLUMN_OTP));
String status=cursor.getString(cursor.getColumnIndex(UsersPojo.USERS_COLUMN_STATUS));
/* Toast.makeText(this, "UserName "+userName
+" password "+password
+" otp "+otp
+" status "+status, Toast.LENGTH_SHORT).show(); */
} while (cursor.moveToNext());
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
}
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
cursor.close();
}
public void villagesLocalTest()
{
Cursor cursor=dbHelper.getVillagesAllEntries();
if (cursor != null && cursor.moveToFirst()) {
do {
String villageName=cursor.getString(cursor.getColumnIndex(VillagesPojo.VILLAGES_COLUMN_VILLAGE_NAME));
// Toast.makeText(this, "VillageName "+villageName, Toast.LENGTH_SHORT).show();
} while (cursor.moveToNext());
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
}
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
cursor.close();
}
public void setAdapterOnFirmName(final View v) {
List<String> firmNameList = new ArrayList<String>();
// firmNameList = dbHelper.getFirmNameList(); //to be removed
individualFarmerContactActivityPresenterInterface = new IndividualFarmerContactActivityPresenter();
try {
firmNameList = individualFarmerContactActivityPresenterInterface.getFirmNameList();
} catch (Exception e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, firmNameList);
firmName = v.findViewById(R.id.firmName);
// firmName.setInputType(InputType.TYPE_NULL);
firmName.setAdapter(adapter);
firmName.setThreshold(1);
final View view=v;
firmName.setOnDismissListener(new AutoCompleteTextView.OnDismissListener() {
@Override
public void onDismiss() {
// Toast.makeText(IndividualFarmerContactActivity.this, "DISMISS", Toast.LENGTH_SHORT).show();
// String propName= dbHelper.getPropName(firmName.getText().toString()); to be removed
// String retailerMobile=dbHelper.getRetailerMobile(firmName.getText().toString()); to be removed
String propName= null;
try {
propName = individualFarmerContactActivityPresenterInterface.getPropName(firmName.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
String retailerMobile= null;
try {
retailerMobile = individualFarmerContactActivityPresenterInterface.getRetailerMobile(firmName.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
if(!propName.equals("") && !retailerMobile.equals("")) {
EditText propNameEditText = view.findViewById(R.id.propName);
propNameEditText.setText(propName);
EditText retailerMobileEditText=view.findViewById(R.id.retailerMobile);
retailerMobileEditText.setText(retailerMobile);
}
else
{
firmName.setError("Please enter firm name from suggested values only");
}
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.individual_farmer_contact_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
/* if (id == R.id.action_settings) {
return true;
} */
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.ifc) {
// IFC Activity clicked by user
Intent intent = new Intent(IndividualFarmerContactMainActivity.this, IndividualFarmerContactMainActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
} else if (id == R.id.fm) {
Intent intent = new Intent(IndividualFarmerContactMainActivity.this, FarmerMeetingActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
} else if (id == R.id.fd) {
Intent intent = new Intent(IndividualFarmerContactMainActivity.this, FieldDayActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
} else if (id == R.id.dv) {
Intent intent = new Intent(IndividualFarmerContactMainActivity.this, DiagnosticVisitActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
}
else if(id==R.id.mc){
Intent intent = new Intent(IndividualFarmerContactMainActivity.this, MandiCampaignActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
}
else if (id == R.id.demol3) {
Intent intent = new Intent(IndividualFarmerContactMainActivity.this, DemoL3Activity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
}
else if (id == R.id.demol3_progress) {
Intent intent = new Intent(IndividualFarmerContactMainActivity.this, DemoL3_InProgressActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
}
else if (id == R.id.pastRecord) {
Intent intent = new Intent(IndividualFarmerContactMainActivity.this, PastRecordActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
|
package solutionOne.main;
import cryptosystem.CryptoSystem;
import cryptosystem.SystPailler;
import env.Question;
import env.Response;
import utils.Utils;
import java.io.*;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Random;
public class Alice extends env.Alice {
//512 bits keys
protected static CryptoSystem.Keys myKeys = new CryptoSystem.Keys(
new BigInteger("130131071253097583747630659815310849918484884379289909856006370109970784534724825495191236462512378783183677819484358734488185023262931726371541157000582697678635072950262054111662819016748688091105817993027870610569899398194660590199929537141471532683874374881902914109920879611980119471552862103424780809051"),
new BigInteger("130131071253097583747630659815310849918484884379289909856006370109970784534724825495191236462512378783183677819484358734488185023262931726371541157000582674832385056297904239774454062772804023883965755324497040739286275501890568406332095860008753111205727375777376935205740256397971370659728114822056440290400")
);
public static BigInteger getPublicKey() {
return myKeys.pk;
}
public Alice(CryptoSystem cs) {
super(cs);
}
@Override
public void run() {
System.out.println("Hello my name is Alice. How are you ?");
System.out.println("Voici les reponses aux questions : ");
for (int i = 0; i < responses.size(); ++i) {
System.out.println(responses.get(i));
System.out.println(Utils.convertString(responses.get(i).getContent()));
}
// Server socket
try {
ServerSocket ss = new ServerSocket(10000);
for (;;)
{
Socket s = ss.accept();
// Chiffre l'ensemble des rรฉponses
LinkedList<BigInteger> listRepEncrypt = new LinkedList<>();
for (Response r : responses)
{
BigInteger rep = cs.chiffrer(Utils.convertString(r.getContent()), Alice.getPublicKey());
listRepEncrypt.add(rep);
}
// On envoie l'ensemble des rรฉponses
System.out.println("Liste de reponses encryptes : ");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
for (BigInteger b : listRepEncrypt) {
bw.write(b.toString() + '\n');
System.out.println(b.toString());
}
bw.write('\n');
bw.flush();
// On recoit la rรฉponse encryptรฉe par Bob, que l'on dรฉcrypte
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String value = br.readLine(); //BigInteger
BigInteger repBob = cs.dechiffrer(new BigInteger(value), myKeys);
System.out.println("Message reรงu dรฉcryptรฉ : " + repBob.toString());
// On encrypte maintenant avec la clรฉ de Bob
BigInteger repFinale = cs.chiffrer(repBob, Bob.getPublicKey());
bw.write(repFinale.toString());
bw.flush();
System.out.println("Rรฉponse finale : " + repFinale.toString());
// Fin de la communication
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
Question.initList();
Alice a = new Alice(new SystPailler());
a.start();
try {
a.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package com.inhatc.cs;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.inhatc.domain.CpubenchVO;
import com.inhatc.persistence.CpubenchDAO;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = {"file:src/main/webapp/WEB-INF/spring/**/root-context.xml"})
public class CpubenchDAOTest {
@Inject
private CpubenchDAO dao;
@Test
public void testInsertCpubench() throws Exception{
CpubenchVO vo = new CpubenchVO();
vo.setCPU_num(2);
vo.setCPU_name("test2");
vo.setBenchi_value(200);
vo.setPrice("3000");
dao.insert(vo);
}
@Test
public void readCpubench() throws Exception{
System.out.println(dao.read(001));
}
} |
package common.geo.yahoo;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ResultSet")
public class Yresponse {
private String error;
private String errorMessage;
private String locale;
private String quality;
private String found;
private Ylocation result;
@XmlElement(name="Error")
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
@XmlElement(name="ErrorMessage")
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
@XmlElement(name="Local")
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
@XmlElement(name="Quality")
public String getQuality() {
return quality;
}
public void setQuality(String quality) {
this.quality = quality;
}
@XmlElement(name="Found")
public String getFound() {
return found;
}
public void setFound(String found) {
this.found = found;
}
@XmlElement(name="Result")
public Ylocation getResult() {
return result;
}
public void setResult(Ylocation result) {
this.result = result;
}
}
|
package atm.parts;
import static java.lang.Integer.parseInt;
import java.util.Scanner;
public class CardReader{
private int status;
private int cardNumberRead;
public static final int NO_CARD = 0;
public static final int CARD_UNREADABLE = 1;
public static final int CARD_READ = 2;
/* Constructor */
public CardReader(){
status = NO_CARD;
}
/**
* Simulates the ejection of a debit card
*/
public void ejectCard(){
try{
Thread.sleep(2000);
}catch(InterruptedException e){}
status = NO_CARD;
}
/**
* Checks if there is a card in the card reader and returns its status
* Check the private constants at the beginning of the file for more info about the satus codes
*
* @return a status code
*/
public synchronized int checkForCard(){
try{
wait(1000);
}catch(InterruptedException e){}
/* We don't have any REAL card reader so we ask the user to type the card number */
Scanner input = new Scanner(System.in);
String cardNumber = input.nextLine();
if(cardNumber == null){
status = CARD_UNREADABLE;
}else{
try{
cardNumberRead = parseInt(cardNumber);
status = CARD_READ;
}catch(NumberFormatException e){
status = CARD_UNREADABLE;
}
}
return status;
}
/**
* Returns the number of the card read
*
* @return card number for current session
*/
public int cardNumber(){
return cardNumberRead;
}
}
|
package com.ut.healthelink.model;
import com.ut.healthelink.validator.NoHtml;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@Table(name = "ref_validationTypes")
public class validationType {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID", nullable = false)
private Integer id;
@NotEmpty
@NoHtml
@Column(name = "validationType", nullable = false)
private String validationType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getValidationType() {
return validationType;
}
public void setValidationType(String validationType) {
this.validationType = validationType;
}
}
|
package com.epam.university.spring;
import com.epam.university.spring.rest.client.BookingService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring/app-context.xml");
BookingService bookingService = context.getBean(BookingService.class);
Long price = bookingService.getTicketsPrice(0L, 1L, Collections.singletonList(6L));
bookingService.refill(1L, 5000L);
bookingService.bookTickets(0L, 1L, Arrays.asList(new Long[] {3L,4L,5L}));
bookingService.getAccount(1L);
bookingService.bookTicket(0L,1L, 2L);
byte[] pdf = bookingService.bookTicketsAcceptPdf(0L,1L, Arrays.asList(new Long[] {10L,11L,12L}));
FileOutputStream fos = new FileOutputStream("ticket.pdf");
fos.write(pdf);
fos.close();
}
}
|
package com.eshop.service.impl;
import com.eshop.dao.ClientDao;
import com.eshop.domain.Client;
import com.eshop.domain.ClientAddress;
import com.eshop.domain.Order;
import com.eshop.enums.Role;
import com.eshop.exception.LoginException;
import com.eshop.jms.MessageSender;
import com.eshop.service.ClientService;
import com.eshop.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Contains implementations of ClientService methods for working with the client.
*/
@Service
@Transactional
public class ClientServiceImpl implements ClientService {
@Autowired
private ClientDao dao;
@Autowired
private OrderService orderService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private MessageSender sender;
private Logger logger = Logger.getLogger("logger");
@Override
public Client getClientById(int id) {
return dao.getClientById(id);
}
@Override
public List<Client> getAllClientsByEmail(String email) {
return dao.getAllClientsByEmail(email);
}
@Override
public List<Client> getAllClients() {
return dao.getAllClients();
}
@Override
public void saveClient(Client client) {
dao.saveClient(client);
}
/**
* Check user's login already exists
* @param login user's login
* @return false if login already exists, true vice-versa
*/
@Override
public boolean checkLogin(String login) {
List<Client> clientByEmail = getAllClientsByEmail(login);
return clientByEmail.isEmpty();
}
/**
* Saves new client.
* @param firstName first name of a new client
* @param lastName last name of a new client
* @param birthDate birth date of a new client
* @param email email of a new client
* @param phone phone number of a new client
* @param password password of a new client
* @return true if client successfully saved, false if not
*/
@Override
public boolean registerNewClient(String firstName, String lastName, LocalDate birthDate, String email, String phone, String password) {
Client client = new Client();
client.setFirstName(firstName);
client.setLastName(lastName);
client.setBirthDate(birthDate);
client.setEmail(email);
client.setPhone(phone);
client.setPassword(passwordEncoder.encode(password));
client.setRoles(Collections.singleton(Role.ROLE_USER));
if (checkLogin(email)) {
saveClient(client);
return true;
} else {
throw new LoginException();
}
}
/**
* Edit client's personal data
* @param id id of a client
* @param firstName new first name
* @param lastName new last name
* @param password new password
* @param email new email
* @param phone new phone number
* @return instance of client with renewed data
*/
@Override
public Client editClientPersonalData(int id, String firstName, String lastName, String password, String email, String phone) {
Client client = getClientById(id);
client.setFirstName(firstName);
client.setLastName(lastName);
client.setPassword(passwordEncoder.encode(password));
client.setEmail(email);
client.setPhone(phone);
saveClient(client);
return client;
}
@Override
public ClientAddress getAddressById(int id) {
return dao.getAddressById(id);
}
@Override
public void saveAddress(ClientAddress address) {
dao.saveAddress(address);
}
/**
* Creates new address for client.
* @param country country of a new address
* @param city city of a new address
* @param postcode post code of a new address
* @param street street of a new address
* @param houseNumber house number of a new address
* @param flatNumber flat number of a new address
* @return instance of client with new address
*/
@Override
public Client createAddressForClient(String country, String city, int postcode, String street, int houseNumber, int flatNumber) {
ClientAddress address = new ClientAddress(country, city, postcode, street, houseNumber, flatNumber);
Client client0 = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Integer id = client0.getId();
Client client = getClientById(id);
Set<ClientAddress> addresses = client.getAddressList();
addresses.add(address);
client.setAddressList(addresses);
saveClient(client);
return client;
}
@Override
public void deleteAddressById(int id) {
try {
dao.deleteAddressById(id);
} catch (Exception ex) {
logger.info("Update or delete violates foreign key constraint");
}
}
@Override
public Client getClientForView() {
Client client = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Integer id = client.getId();
return getClientById(id);
}
/**
* Edit existing address of the client
* @param addressForEdit id if the address to edit
* @param country country of a new address
* @param city city of a new address
* @param postcode post code of a new address
* @param street street of a new address
* @param houseNumber house number of a new address
* @param flatNumber flat number of a new address
* @return instance of client with new address
*/
@Override
public Client editAddressForClient(int addressForEdit, String country, String city, int postcode, String street, int houseNumber, int flatNumber) {
Client client = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
ClientAddress newAddress = getAddressById(addressForEdit);
logger.info("Old address retrieved");
newAddress.setCountry(country);
newAddress.setCity(city);
newAddress.setPostCode(postcode);
newAddress.setStreet(street);
newAddress.setHouseNumber(houseNumber);
newAddress.setFlatNumber(flatNumber);
saveAddress(newAddress);
logger.info("New address saved");
Set<ClientAddress> addresses = client.getAddressList();
addresses.remove(getAddressById(addressForEdit));
addresses.add(newAddress);
client.setAddressList(addresses);
Integer id = client.getId();
return getClientById(id);
}
/**
* Creates list of 10 best clients (with most amounts of orders) for the particular period of time.
* @param start start date
* @param finish finish date
* @return list of 10 best clients
*/
@Override
public List<Client> getTenBestClientsPerPeriod(LocalDate start, LocalDate finish)
{
Map<Client, Long> ordersOfClientMap = new HashMap<>();
List<Order> ordersPerPeriod = orderService.getOrdersPerPeriod(start, finish);
List<Client> allClients = getAllClients();
for (Client client: allClients) {
long countOfOrderForClient = ordersPerPeriod.stream()
.filter(order -> order.getClient().equals(client))
.count();
ordersOfClientMap.put(client, countOfOrderForClient);
}
List<Long> amountOfOrders = ordersOfClientMap
.values()
.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
Set<Client> bestTenClients = new LinkedHashSet<>();
amountOfOrders.forEach(i -> {
for (Map.Entry<Client, Long> entry : ordersOfClientMap.entrySet()) {
if (i.equals(entry.getValue()))
bestTenClients.add(entry.getKey());
}
});
return bestTenClients.stream().limit(10).collect(Collectors.toList());
}
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
return dao.getClientByEmail(s);
}
public void setDao(ClientDao dao) {
this.dao = dao;
}
public void setOrderService(OrderService orderService) {
this.orderService = orderService;
}
} |
package org.launchcode.skillstracker.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@ResponseBody
//@RequestMapping(method={ RequestMethod.POST, RequestMethod.GET})
public class SkillsController {
@GetMapping
public String listSkills() {
String html =
"<html>" +
"<body>" +
"<h1>Skills Tracker</h1>" +
"<h2>We have a few skills we would like to learn. Here is the list!</h2>" +
"<ol>" +
"<li>Java</li>" +
"<li>JavaScript</li>" +
"<li>Python</li>" +
"</ol>" +
"</body>" +
"</html>";
return html;
}
@GetMapping("form")
public String skillsForm() {
String html =
"<html>" +
"<body>" +
"<form method='post' action='form'>" +
"<label for='name'>Name:</label><br>" +
"<input type='text' name='name' /><br>" +
"<label for='favoriteLanguage'>My favorite language:</label><br>" +
"<select name='favoriteLanguage'>" +
"<option value='java'>Java</option>" +
"<option value='javaScript'>JavaScript</option>" +
"<option value='python'>Python</option>" +
"</select><br>" +
"<label for='secondFavoriteLanguage'>My second favorite language:</label><br>" +
"<select name='secondFavoriteLanguage'>" +
"<option value='java'>Java</option>" +
"<option value='javaScript'>JavaScript</option>" +
"<option value='python'>Python</option>" +
"</select><br>" +
"<label for='thirdFavoriteLanguage'>My third favorite language:</label><br>" +
"<select name='thirdFavoriteLanguage'>" +
"<option value='java'>Java</option>" +
"<option value='javaScript'>JavaScript</option>" +
"<option value='python'>Python</option>" +
"</select><br>" +
"<input type='submit' value='Submit'/>" +
"</form>" +
"</body>" +
"</html>";
return html;
}
@PostMapping("form")
public String formHandler(@RequestParam String name,
@RequestParam String favoriteLanguage,
@RequestParam String secondFavoriteLanguage,
@RequestParam String thirdFavoriteLanguage) {
String html =
"<html>" +
"<body>" +
"<h1>" + name + "</h1>" +
"<ol>" +
"<li>" + favoriteLanguage+"</li>" +
"<li>" + secondFavoriteLanguage +"</li>" +
"<li>" + thirdFavoriteLanguage +"</li>" +
"</ol>" +
"</body>" +
"</html>";
return html;
}
}
|
/*
* 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 codigomorseinterfaces;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
/**
*
* @author Router1
*/
public class MorseFXMLController implements Initializable {
private String palabra="";
private String morse[] = {" .---- ", " ..--- ", " ... -- ", " ....- ", " ..... ",
" _.... ", " _ _... ", " - - -.. ", "----.", "-----", ".-", "-...",
"-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--",
"--..", ".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
"--.-", ".-.", "...", " - ", " ..- ", "...-", ".--", "-..-",
"-.--", "--..", " ", ".-.-.-", "--..--", "..--..", "---...",
"-....-", "!"," "};
String letras = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .,?:-!";
int posicion=0;
String suma="";
@FXML
private TextField entrada;
@FXML
private TextField salida;
@FXML
private void accionTraducir(ActionEvent event) {
palabra = entrada.getText();
for (int f = 0; f < palabra.length(); f++) {
posicion=letras.indexOf(palabra.charAt(f));
suma+=morse[posicion];
}
salida.setText(suma);
}
@FXML
private void accionBorrar(ActionEvent event) {
entrada.setText("");
salida.setText("");
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
|
package com.ymall.controller.portal;
import com.google.common.collect.Maps;
import com.ymall.common.ServerResponse;
import com.ymall.common.exception.IllegalException;
import com.ymall.service.FileService;
import com.ymall.util.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
/**
* Created by zc on 2017/6/16.
*/
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
private FileService fileService;
@RequestMapping(value = "upload_img", method = RequestMethod.POST)
public ServerResponse upload(HttpServletRequest request) throws IllegalException {
if (request instanceof MultipartHttpServletRequest) {
MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
if (file != null) {
//ๅฎไนไธดๆถๆไปถๅคน
String tmp_path = request.getSession().getServletContext().getRealPath("tmp");
String targetFileName = fileService.upload(file, tmp_path, PropertiesUtil.getProperty("cos.path.prefix"));
String url = PropertiesUtil.getProperty("cos.server.http.prefix") + targetFileName;
Map fileMap = Maps.newHashMap();
fileMap.put("uri", targetFileName);
fileMap.put("url", url);
return ServerResponse.createBySuccess(fileMap);
}
throw new IllegalException("ๆไปถไธ่ฝไธบ็ฉบ");
} else {
throw new IllegalException("่ฏทๆฑไธๆฏๆไปถ");
}
}
}
|
package Action;
import Service.accessRecord.AccessRecord;
import Service.healthScore.HealthScore;
import Service.user.Manager;
import Service.user.Student;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(name = "insertHealthScore",urlPatterns = "/insertHealthScore")
public class insertHealthScore extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//่ฎพ็ฝฎ็ผ็ ๆ ผๅผๅๅๆฐ
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
//่ทๅๅ็ซฏๆฐๆฎ
HttpSession httpSession = request.getSession();
Manager manager = (Manager) httpSession.getAttribute("aManager");
HealthScore healthScore = new HealthScore();
healthScore.setBuildingId(manager.getManager_Building_ID());
healthScore.setRoomId(request.getParameter("RoomId"));
healthScore.setScore(Float.parseFloat(request.getParameter("Score")));
healthScore.setRecordDate(request.getParameter("RecordDate"));
//ๅฐๆฐๆฎๅญๅ
ฅๆฐๆฎๅบ
String state = "";
if(HealthScore.insertHealthScore(healthScore))
{
state = "1";
}
else
{
state = "0";
}
//่ฟๅ็ธๅบๆฐๆฎ
JSONObject respJson = new JSONObject();
respJson.put("state",state);
response.getOutputStream().write(respJson.toString().getBytes("UTF-8"));
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
|
public abstract class MyAbstractSequentialList<E> extends MyAbstractList<E> {
/** Create a default list */
protected MyAbstractSequentialList() {
}
/** Create a list from an array of objects */
protected MyAbstractSequentialList(E[] objects) {
super(objects);
}
public java.util.Iterator<E> iterator() {
return listIterator();
}
public java.util.ListIterator<E> listIterator() {
return listIterator(0);
}
abstract public E getFirst();
abstract public E getLast();
abstract public void addFirst(E e);
abstract public void addLast(E e);
abstract public E removeFirst();
abstract public E removeLast();
abstract public java.util.ListIterator<E> listIterator(int index);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.