text
stringlengths
10
2.72M
package fr.lteconsulting.training.moviedb.servlet; import fr.lteconsulting.training.moviedb.ejb.GestionFabricants; import fr.lteconsulting.training.moviedb.model.Categorie; import fr.lteconsulting.training.moviedb.model.Fabricant; import fr.lteconsulting.training.moviedb.outil.Session; import fr.lteconsulting.training.moviedb.outil.Vues; import javax.ejb.EJB; 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 java.io.IOException; @WebServlet("/editionFabricant") public class EditionFabricantServlet extends HttpServlet { @EJB private GestionFabricants gestionFabricants; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Fabricant fabricant = null; try { int id = Integer.parseInt(req.getParameter("id")); fabricant = gestionFabricants.findById(id); if (fabricant == null) { resp.sendRedirect("fabricants"); return; } } catch (Exception e) { fabricant = new Fabricant(); fabricant.setNom("Nouveau fabricant"); fabricant.setAdresse("Toulouse"); } Vues.afficherEditionFabricant(req, resp, fabricant); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Fabricant fabricant = new Fabricant(); try { fabricant.setId(Integer.parseInt(req.getParameter("id"))); } catch (Exception e) { } fabricant.setNom(req.getParameter("nom")); fabricant.setAdresse(req.getParameter("adresse")); gestionFabricants.update(fabricant); resp.sendRedirect("fabricants"); } }
package com.qr_market.fragment.adapter; /** * Created by orxan on 11.05.2015. */ import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; import com.beardedhen.androidbootstrap.FontAwesomeText; import com.qr_market.R; import com.qr_market.util.MarketOrder; import com.qr_market.util.MarketProduct; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import java.util.Locale; /** * @author Kemal Sami KARACA * @since 26.04.2015 * @version v1.01 * * @description * Adapter of order list * * @last 12.05.2015 */ public class OrderFragmentListAdapter extends BaseExpandableListAdapter { /* private HashMap<String,List<MarketOrder>> list_child; public OrderFragmentListAdapter(HashMap<String, List<MarketOrder>> list_child, List<MarketOrder> orderList, Context context) { this.list_child = list_child; //this.orderList=orderList; this.context = context; } */ private Activity activity; private Context context; private OrderFragmentListAdapter orderListAdapter; private List<MarketOrder> orderList = MarketOrder.getOrderListInstance(); private List<MarketProduct> orderProductList = null; private LayoutInflater inflater; //private ViewHolder viewHolder; /** *********************************************************************************************** *********************************************************************************************** * CONSTRUCTOR *********************************************************************************************** *********************************************************************************************** */ public OrderFragmentListAdapter(Activity activity, List<MarketOrder> orderList) { this.activity = activity; this.context = activity.getApplicationContext(); this.orderListAdapter = OrderFragmentListAdapter.this; this.inflater = LayoutInflater.from(context); this.setOrderList(orderList); } @Override public Object getGroup(int groupPosition) { return this.orderList.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { if(this.orderList.get(groupPosition).getOrderProductList().size()!=0){ return this.orderList.get(groupPosition).getOrderProductList().get(childPosition); }else{ // GET PRODUCT LIST FROM SERVER // HTTP CALL MarketProduct myProduct = new MarketProduct(); myProduct.setProduct_amount(12); myProduct.setProduct_price("13"); return myProduct; } /* MarketProduct childProduct; try{ childProduct = this.orderList.get(groupPosition).getOrderProductList().get(childPosition); }catch (NullPointerException err){ // GET PRODUCT LIST FROM SERVER // HTTP CALL MarketProduct myProduct = new MarketProduct(); myProduct.setProduct_amount(12); myProduct.setProduct_price("13"); childProduct = myProduct; } return childProduct; */ } @Override public long getChildId(int i, int i1) { return 0; } @Override public int getChildrenCount(int groupPosition) { return 1; // return this.orderList.get(groupPosition).getOrderProductList().size(); } @Override public View getChildView(int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) { //--Here we are getting child values from current position-- MarketProduct currentProduct = (MarketProduct)getChild(groupPosition,childPosition); //--Here we are getting child view-- if(view==null){ LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = layoutInflater.inflate(R.layout.order_list_child_layout, null); } final TextView product_amount = (TextView)view.findViewById(R.id.ordered_product_amount); final TextView product_date = (TextView)view.findViewById(R.id.order_date); // final FontAwesomeText timeIcon = (FontAwesomeText) view.findViewById(R.id.order_time_icon); //--Set The child values to the related layout view-- product_amount.setText(""+currentProduct.getProduct_amount()); //Set Time Icon //timeIcon.setIcon("fa-clock-o"); return view; } @Override public int getGroupCount() { return this.orderList.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public View getGroupView(int groupPosition, boolean b, View view, ViewGroup viewGroup) { //--Here we are getting parent values from current position-- final MarketOrder parentOrderData = orderList.get(groupPosition); if(view==null){ LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = layoutInflater.inflate(R.layout.order_list_parent_layout, null); } final TextView market=(TextView)view.findViewById(R.id.market_name); final TextView market_city=(TextView)view.findViewById(R.id.market_city); final TextView market_adress=(TextView)view.findViewById(R.id.market_adress); final TextView product_date=(TextView)view.findViewById(R.id.date); final FontAwesomeText timeIcon = (FontAwesomeText) view.findViewById(R.id.order_time_icon); // --Set The parent values to the related layout view-- market.setText(parentOrderData.getCompanyName()); market_city.setText(parentOrderData.getAddress().getCity()); market_adress.setText(parentOrderData.getAddress().getBorough() + "/" + parentOrderData.getAddress().getLocality()); // DATE SETTINGS try { Calendar cal = Calendar.getInstance(); long date = Long.parseLong(parentOrderData.getDate(), 10); cal.setTimeInMillis(date); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm", Locale.ENGLISH); product_date.setText(simpleDateFormat.format(cal.getTime())); }catch (NumberFormatException e){ product_date.setText(parentOrderData.getDate()); } //Set Time Icon timeIcon.setIcon("fa-clock-o"); return view; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int i, int i1) { return true; } public List<MarketOrder> getOrderList() { return orderList; } public void setOrderList(List<MarketOrder> orderList) { this.orderList = orderList; } }
package com.comercial.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/acessos") public class AcessoController { @GetMapping("/login") public String login() { return "acesso/login"; } }
package com.rofour.baseball.service.report.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.rofour.baseball.controller.model.report.ReportUserSmsModelInfo; import com.rofour.baseball.dao.report.bean.ReportUserSmsModelBean; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.rofour.baseball.controller.model.report.ReportStoreSmsInfo; import com.rofour.baseball.controller.model.report.SearchStoreSmsDetailInfo; import com.rofour.baseball.controller.model.report.SearchStoreSmsTotalInfo; import com.rofour.baseball.dao.report.bean.ReportStoreSmsBean; import com.rofour.baseball.dao.report.bean.SearchStoreSmsDetailBean; import com.rofour.baseball.dao.report.bean.SearchStoreSmsTotalBean; import com.rofour.baseball.dao.report.mapper.ReportStoreSmsMapper; import com.rofour.baseball.exception.BusinessException; import com.rofour.baseball.service.report.ReportStoreSmsService; /** * @author ZXY * @ClassName: ReportStoreSmsImpl * @Description: 货源短信日报表服务实现 * @date 2016/4/26 13:48 */ @Service("reportStoreSmsService") public class ReportStoreSmsImpl implements ReportStoreSmsService { @Autowired @Qualifier("reportStoreSmsMapper") private ReportStoreSmsMapper dao; /** * @param storeName * @param storeId * @param supervisor * @param expressId * @param startDate * @param endDate * @param status * @param limit * @param offset * @return * @throws Exception * @Description: 货源短信报表 * @see com.rofour.baseball.service.report.ReportStoreSmsService#getStoreSmsDayReport(java.lang.String, * java.lang.String, java.lang.String, java.lang.String, * java.lang.String, java.lang.String, java.lang.String, * java.lang.Integer, java.lang.Integer) */ @Override public List<ReportStoreSmsInfo> getStoreSmsDayReport(String storeName, String storeId, String supervisor, String expressId, String startDate, String endDate, String status, Integer limit, Integer offset) throws Exception { if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) { // 查询日期不能为空 throw new BusinessException("08001"); } Map<String, Object> map = new HashMap<>(); if (!StringUtils.isBlank(storeName)) { map.put("storeName", storeName); } if (!StringUtils.isBlank(storeId)) { map.put("storeId", storeId); } if (!StringUtils.isBlank(supervisor)) { map.put("supervisor", supervisor); } if (!StringUtils.isBlank(expressId)) { map.put("expressId", expressId); } if (!StringUtils.isBlank(status)) { map.put("status", status); } map.put("startDate", startDate); map.put("endDate", endDate); map.put("limit", limit); map.put("offset", offset); List<ReportStoreSmsBean> smsBeans = dao.getStoreSmsDayReport(map); List<ReportStoreSmsInfo> smsInfos = new ArrayList<ReportStoreSmsInfo>(); ReportStoreSmsInfo info; for (ReportStoreSmsBean smsBean : smsBeans) { info = new ReportStoreSmsInfo(); BeanUtils.copyProperties(smsBean, info); smsInfos.add(info); } return smsInfos; } public int getStoreSmsReportCount(String storeName, String storeId, String supervisor, String expressId, String startDate, String endDate, String status) { if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) { // 查询日期不能为空 throw new BusinessException("08001"); } Map<String, String> map = new HashMap<>(); if (!StringUtils.isBlank(storeName)) { map.put("siteId", storeName); } if (!StringUtils.isBlank(storeId)) { map.put("storeId", storeId); } if (!StringUtils.isBlank(supervisor)) { map.put("supervisor", supervisor); } if (!StringUtils.isBlank(expressId)) { map.put("expressId", expressId); } if (!StringUtils.isBlank(status)) { map.put("status", status); } map.put("startDate", startDate); map.put("endDate", endDate); int totalCount = dao.getStoreSmsReportCount(map); return totalCount; } /** * @param storeId * @param startDate * @param endDate * @return * @Description: 短信报表汇总 * @see com.rofour.baseball.service.report.ReportStoreSmsService#selectStoreSmsTotalInfo(java.lang.String, * java.lang.String, java.lang.String) */ @Override public List<SearchStoreSmsTotalInfo> selectStoreSmsTotalInfo(String storeId, String startDate, String endDate) throws Exception { if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) { // 查询日期不能为空 throw new BusinessException("08001"); } Map<String, String> map = new HashMap<>(); if (!StringUtils.isBlank(storeId)) { map.put("storeId", storeId); } map.put("startDate", startDate); map.put("endDate", endDate); List<SearchStoreSmsTotalBean> smsBeans = dao.selectStoreSmsTotalInfo(map); List<SearchStoreSmsTotalInfo> smsInfos = new ArrayList<SearchStoreSmsTotalInfo>(); SearchStoreSmsTotalInfo info; for (SearchStoreSmsTotalBean smsBean : smsBeans) { info = new SearchStoreSmsTotalInfo(); BeanUtils.copyProperties(smsBean, info); smsInfos.add(info); } return smsInfos; } /** * @param storeId * @param startDate * @param endDate * @param status * @param beVirtual * @return * @Description: 短信统计--明细 * @see com.rofour.baseball.service.report.ReportStoreSmsService#searchStoreSmsDetails(java.lang.String, * java.lang.String, java.lang.String, java.lang.String, * java.lang.String) */ @Override public List<SearchStoreSmsDetailInfo> searchStoreSmsDetails(String storeId, String startDate, String endDate, String status, String beVirtual) throws Exception { if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) { // 查询日期不能为空 throw new BusinessException("08001"); } Map<String, String> map = new HashMap<>(); if (!StringUtils.isBlank(storeId)) { map.put("storeId", storeId); } if (!StringUtils.isBlank(status)) { map.put("status", status); } if (!StringUtils.isBlank(beVirtual)) { map.put("beVirtual", beVirtual); } map.put("startDate", startDate); map.put("endDate", endDate); List<SearchStoreSmsDetailBean> smsDetailBeans = dao.selectStoreSmsDetailInfo(map); List<SearchStoreSmsDetailInfo> smsDetailInfos = new ArrayList<SearchStoreSmsDetailInfo>(); SearchStoreSmsDetailInfo info; for (SearchStoreSmsDetailBean smsBean : smsDetailBeans) { info = new SearchStoreSmsDetailInfo(); BeanUtils.copyProperties(smsBean, info); smsDetailInfos.add(info); } return smsDetailInfos; } /** * 查询用户自定义短信模板 * * @param storeId * @param userName * @param phone * @param offset * @param limit * @return */ @Override public List<ReportUserSmsModelInfo> searchUserSmsModelList(String storeId, String userName, String phone, String modelContent, Integer offset, Integer limit) { Map<String, Object> map = new HashMap<>(); if (!StringUtils.isBlank(storeId)) { map.put("storeId", storeId); } if (!StringUtils.isBlank(userName)) { map.put("userName", userName); } if (!StringUtils.isBlank(phone)) { map.put("phone", phone); } if (!StringUtils.isBlank(modelContent)) { map.put("modelContent", modelContent); } map.put("offset", offset); map.put("limit", limit); List<ReportUserSmsModelBean> userSmsModelBeens = dao.getuserSmsModelList(map); List<ReportUserSmsModelInfo> userSmsModelInfos = new ArrayList<ReportUserSmsModelInfo>(); ReportUserSmsModelInfo info; for (ReportUserSmsModelBean smsBean : userSmsModelBeens) { info = new ReportUserSmsModelInfo(); BeanUtils.copyProperties(smsBean, info); userSmsModelInfos.add(info); } return userSmsModelInfos; } /** * 查询用户自定义短信模板数量 * * @param storeId * @param userName * @param phone * @return */ @Override public int getUserSmsModelListCount(String storeId, String userName, String phone, String modelContent) { Map<String, Object> map = new HashMap<>(); if (!StringUtils.isBlank(storeId)) { map.put("storeId", storeId); } if (!StringUtils.isBlank(userName)) { map.put("userName", userName); } if (!StringUtils.isBlank(phone)) { map.put("phone", phone); } if (!StringUtils.isBlank(modelContent)) { map.put("modelContent", modelContent); } return dao.getuserSmsModelListCount(map); } }
package com.diegolirio.report.models; import java.util.List; public class NotaFiscal { private long id; private int numero; private String cnpj; private String data; private List<NotaProduto> notaProdutos; public long getId() { return id; } public void setId(long id) { this.id = id; } public int getNumero() { return numero; } public void setNumero(int numero) { this.numero = numero; } public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public String getData() { return data; } public void setData(String data) { this.data = data; } public List<NotaProduto> getNotaProdutos() { return notaProdutos; } public void setNotaProdutos(List<NotaProduto> notaProdutos) { this.notaProdutos = notaProdutos; } }
package com.algaworks.curso.jpa.ecommerce.model; import java.math.BigDecimal; import java.util.List; import java.util.Set; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor @Entity @Table(name = "produto") public class Produto extends EntidadeAbstrata { private static final long serialVersionUID = 1L; @Column(nullable = false) private String nome; private String descricao; @Column(nullable = false) private BigDecimal preco; @JsonIgnoreProperties({ "categoria", "subcategorias" }) @ManyToMany @JoinTable(name = "produto_categoria", joinColumns = @JoinColumn( name = "produto_id"), inverseJoinColumns = @JoinColumn(name = "categoria_id")) private List<Categoria> categorias; @ElementCollection @CollectionTable(name = "produto_tag", joinColumns = @JoinColumn(name = "produto_id")) @Column(name = "tag") private Set<String> tags; @ElementCollection @CollectionTable(name = "produto_atributo", joinColumns = @JoinColumn(name = "produto_id")) private List<Atributo> atributos; }
package com.smxknife.lock.mysql; import java.util.Arrays; import java.util.Objects; /** * @author smxknife * 2021/6/11 */ public class GracefulClose { public static void close(AutoCloseable... closeables) { Arrays.asList(closeables).stream().filter(Objects::nonNull).forEach(closeable -> { try { closeable.close(); } catch (Exception e) { e.printStackTrace(); } }); } }
package ch.springcloud.lite.core.codec; public interface CloudDecoder { Object decode(String val, Class<?> type); }
package com.itheima.core.service; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.itheima.core.BrandCheckService; import com.itheima.core.dao.good.BrandCheckDao; import com.itheima.core.dao.good.BrandDao; import com.itheima.core.dao.seller.SellerDao; import com.itheima.core.pojo.good.Brand; import com.itheima.core.pojo.good.BrandCheck; import com.itheima.core.pojo.good.BrandCheckQuery; import com.itheima.core.pojo.seller.Seller; import entity.PageResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class BrandCheckServiceImpl implements BrandCheckService { @Autowired private BrandDao brandDao; @Autowired private BrandCheckDao brandCheckDao; @Autowired private SellerDao sellerDao; @Override public void add(BrandCheck brandCheck, String name) { Brand brand = new Brand(); brand.setName(brandCheck.getName()); brandDao.insertSelective(brand); brandCheck.setCheckStatus("0"); brandCheck.setSellerId(name); Seller seller = sellerDao.selectByPrimaryKey(name); brandCheck.setSellerName(seller.getName()); brandCheckDao.insertSelective(brandCheck); } @Override public PageResult<BrandCheck> search(Integer pageNum, Integer pageSize, BrandCheck brandCheck, String name) { PageHelper.startPage(pageNum,pageSize); BrandCheckQuery query = new BrandCheckQuery(); BrandCheckQuery.Criteria criteria = query.createCriteria(); criteria.andSellerIdEqualTo(name); if (null != brandCheck.getName() && !"".equals(brandCheck.getName().trim())){ criteria.andNameLike("%"+brandCheck.getName().trim()+"%"); } Page<BrandCheck> p = (Page<BrandCheck>) brandCheckDao.selectByExample(query); return new PageResult<>(p.getTotal(),p.getResult()); } @Override public BrandCheck findOne(Long id) { return brandCheckDao.selectByPrimaryKey(id); } @Override public PageResult search(Integer page, Integer rows) { PageHelper.startPage(page,rows); Page<BrandCheck> p = (Page<BrandCheck>) brandCheckDao.selectByExample(null); return new PageResult(p.getTotal(),p.getResult()); } @Override public void updateStatus(Long[] ids, String status) { BrandCheck brandCheck = new BrandCheck(); brandCheck.setCheckStatus(status); for (Long id : ids) { brandCheck.setId(id); brandCheckDao.updateByPrimaryKeySelective(brandCheck); } } }
package com.fleet.batch.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobExecutionListener; public class CsvJobExecutionListener implements JobExecutionListener { private static final Logger logger = LoggerFactory.getLogger(CsvJobExecutionListener.class); private long startTime; private long endTime; @Override public void beforeJob(JobExecution jobExecution) { startTime = System.currentTimeMillis(); logger.info("job process start..."); } @Override public void afterJob(JobExecution jobExecution) { endTime = System.currentTimeMillis(); logger.info("job process end..."); logger.info("execution time: " + (endTime - startTime) + "ms"); } }
package com.boardex.demo.domain.entity; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Table(name = "board") public class BoardEntity extends TimeEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "articleNumber") private Long articleNumber; @Column(name = "writer", length = 100, nullable = false) private String writer; @Column(name = "title", length = 100, nullable = false) private String title; @Column(name = "content",columnDefinition = "TEXT", nullable = false) private String content; @Builder public BoardEntity(Long articleNumber, String writer, String title, String content) { this.articleNumber = articleNumber; this.writer = writer; this.title = title; this.content = content; } }
package com.tao.service; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class MailService { private static final String host = "smtp.qq.com"; private static final String fromMail = "1162165740@qq.com"; private static final String mailPassword = "1162165740m"; private String subject; private String toMail; private Properties props; private MimeMessage message; private Session session; public MailService(){ props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); subject = "Your commodity from "+fromMail+" !"; this.session = session; this.session= Session.getDefaultInstance(props, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(fromMail, mailPassword); } }); } public void sendMail(String imageUrl,String toMail) throws AddressException, MessagingException{ this.toMail = toMail; message = new MimeMessage(session); message.setFrom(new InternetAddress(fromMail)); message.addRecipient(Message.RecipientType.TO, new InternetAddress( toMail)); message.setSubject(subject); // Send message BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("TaoMeiRen,good luck!"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(imageUrl); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(imageUrl); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport transport = session.getTransport("smtp"); transport.send(message); } }
package com.thatman.testservice.client; import com.thatman.testservice.Entity.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; @Component @FeignClient(name = "service20",fallback = TestServiceTwoClientFallback.class) public interface TestServiceTwoClient { @GetMapping(value ="test/getUser") User getUser(); }
package com.cgm.twitter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.cgm.twitter.data.ArtefactBuilder; @Controller public class FriendsController { @RequestMapping(value = "/friends", method = RequestMethod.GET) @ResponseBody protected ModelAndView getUser(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("redirect:/home"); if (request.getSession().getAttribute("userName") != null) { System.out.println("Session in GET : " + request.getSession().getAttribute("userName").toString()); model = new ModelAndView("friends"); model.addObject("friend", ArtefactBuilder.getFriends()); } return model; } }
package com.qcwp.carmanager.enumeration; import java.io.File; /** * Created by qyh on 2017/1/7. */ public class PathEnum { public final static String UserInfo ="UserInfo", BOOK_directory ="BOOK"+ File.separator, APK_PATH="APK"+ File.separator, APK_Name="hykd.apk", WIFI_Name="hykd.txt"; }
package Assignment_1; public class Parallelogram extends Quadrilateral { private int height; Parallelogram(int x1, int x2, int x3, int x4, int y1, int y2, int y3, int y4, int height) { setCoordinates(x1,x2,x3,x4,y1,y2,y3,y4); this.height = height; } float area() { float A = (float)Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); return A*height; } }
package espwg; import java.math.BigDecimal; import org.hibernate.Session; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.Path; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Button; import org.zkoss.zul.Decimalbox; import org.zkoss.zul.Include; import org.zkoss.zul.Textbox; import org.zkoss.zul.Window; import db.HibernateUtil; import model.User; import serviceEspwg.NewUserService; import services.UserServices; import util.MessageUtil; import util.SessionUtil; public class NewUserForm extends GenericForwardComposer { private static final long serialVersionUID = 1L; // general component yang kebanyakan dipakai di hampir semua form Include content = (Include) Path.getComponent("//main/content"); User u, generatedUser; Window winNewUser; Textbox tbFullName, tbUserID, tbPassword, tbEmail, tbPhone, tbAccName, tbAccNo, tbBank; Decimalbox dbCredit; Button btnSave, btnGenerateUserId; public void doAfterCompose(Component win) throws Exception { super.doAfterCompose(win); // Get admin User u = SessionUtil.getUser(); } public void clearUI() { BigDecimal a = null; tbFullName.setText(""); tbUserID.setText(""); tbPassword.setText(""); tbEmail.setText(""); tbPhone.setText(""); tbAccName.setText(""); tbAccNo.setText(""); tbBank.setText(""); try { dbCredit.setValue(a); } catch (Exception e) { // TODO: handle exception } } public boolean validate(User generatedUser) { String errMessage = ""; errMessage = NewUserService.validateRequest(generatedUser, u.getUserId()); if (errMessage.equals("")) { return true; } else { MessageUtil.errorDialog(errMessage); return false; } } public void onClick$btnGenerateUserId() { tbUserID.setText(NewUserService.generateUserId().toString()); } public void onClick$btnSave() { Boolean sure = false; sure = MessageUtil .confirmation("You are going to fill " + dbCredit.getValue() + " credits to this user, are you sure ?"); if (sure) { generatedUser = new User(); try { generatedUser.setUserName(tbFullName.getText().toString()); generatedUser.setUserId(tbUserID.getText().toString()); generatedUser.setUserPass(tbPassword.getText().toString()); generatedUser.setEmail(tbEmail.getText().toString()); generatedUser.setPhone(tbPhone.getText().toString()); generatedUser.setAccName(tbAccName.getText().toString()); generatedUser.setAccNo(tbAccNo.getText().toString()); generatedUser.setBank(tbBank.getText().toString()); generatedUser.setCredit(dbCredit.getValue()); if (validate(generatedUser)) { String err = NewUserService.sentRequest(generatedUser, u.getUserId()); if (err.equals("") || err == null) { alert("Success"); } else { alert(err); } } } catch (Exception e) { e.printStackTrace(); } } clearUI(); refreshUser(u); } public void refreshUser(User user) { User refreshedUser = UserServices.getUserById(user.getUserId()); SessionUtil.initSession(refreshedUser); Executions.sendRedirect("Main.zul"); } }
package View; import Model.MainModel; import Utils.Data; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import static javax.swing.JFrame.EXIT_ON_CLOSE; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.DefaultTableModel; import java.math.MathContext; /** * * @author layfon */ public final class Frame{ JFrame f; MainModel m = null; JScrollPane sp; JPanel panel2, jplPanel, panel; JTabbedPane tabbedPane; /** *create jframe with tabs and calls start method to create instance of mainmodel */ public Frame(){ start(); // calls start method, which will create instance of mainmodel which will contain teamlist instances f=new JFrame("Football Team List Application"); //create new JFrame with ok as title tab();// calls method that will create jtabbed pane with panel f.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("football.png"))); JPanel panel4 = new JPanel(); // new panel to hold buttons // panel4.setPreferredSize(new Dimension(400,40)); JButton n = new JButton("National"); JButton c = new JButton("Conference"); JButton t = new JButton("TeamList"); //implement actionlistener on both button to listen for mouse clicks n.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ //tabbedPane.setVisible(false); tabbedPane.setComponentAt(0, panel2= createInnerPanel2("National")); // when pressed the component at jtabbedpane (first one teamlist =0) contents in panel will be changed to national //createInnerPanel2 method is called and it takes national as parameter // the return will be jpanel with only national team } }); c.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ tabbedPane.setComponentAt(0, panel2 =createInnerPanel2("Conference")); } }); t.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ tabbedPane.setComponentAt(0, panel2 =createInnerPanel2("TeamList")); } }); panel4.add(n);// add button to panel4 panel4.add(c); panel4.add(t); f.add(panel4, BorderLayout.SOUTH); // we use borderlayout and put the panel4 containing jbuttons in south //Get current monitor screensize // this will put the window in center of current monitor screen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); // get current monitor dimension double width = screenSize.getWidth(); double height = screenSize.getHeight(); //calculate centre of screen/monitor int x = (int) ((width-1500)/2); int y = (int) ((height-500)/2); //set frame in center f.setBounds(x, y, 1500, 500); f.setVisible(true); f.setDefaultCloseOperation(EXIT_ON_CLOSE); //closes the application when JFrame is closed } public void start(){ Data d = new Data(); // new instance of Data m = new MainModel(); // new instance of MainModel m.setTeamList(d.readTeam("football_teams.txt")); // calls mainmodel instance m method setTeamList to create new ARRAYLIST<team> and the argument will be return arraylist from data instance d method readTeam m.setMatches(d.readMatches("football_matches.txt")); } //create tabbpane public void tab(){ //jtabbedpane object takes care of mouse and keyboard events tabbedPane = new JTabbedPane(); //create a tabbed pane panel = createInnerPanel2("TeamList");//creates jpanel to show TEAMLIST table tabbedPane.addTab("Teamlist", panel);//adds tab/panel compoonents to tabbedpane //only made for first teamlist tab because the panel on it will be changed by JButton if pressed so to revert it back to orginal we need to change panel content tabbedPane.addChangeListener(new ChangeListener() { //listens to tab @Override public void stateChanged(ChangeEvent evt) { JTabbedPane tabbedPane = (JTabbedPane)evt.getSource(); //get which tab was pressed/changed to // Get current tab int tab = tabbedPane.getSelectedIndex(); if(tab==0){ //if tab is first one panel = createInnerPanel2("TeamList"); // put the orginal teamlist in the panel2 tabbedPane.setComponentAt(0, panel); } } }); panel2 = createInnerPanel2("National");// Maybe iN FUTURE we can put MATCHES OF TEAM in these tabs tabbedPane.add("National", panel2);// title and component to be displayed when clicked panel2 = createInnerPanel2("Conference"); tabbedPane.add("Conference",panel2); // ******** WE MIGHT NEED THESE EXTRA TABS IN FUTURE ******* f.setLayout(new BorderLayout()); f.add(tabbedPane, BorderLayout.CENTER); //f.setLayout(new GridLayout(1,1)); //sets layout as grid with 1,1 //f.add(tabbedPane); //adds tabbedpane to jframe } // method called when creating panel for tabbedpane //takes in parameter as national, conference or teamlist //takes in parameter as national, conference or teamlist private JPanel createInnerPanel2(String nope) { jplPanel = new JPanel(); //creates a new panel lister(nope); //lister method called which returns scrollpane sp jplPanel.add(sp);//scrollpane will be added to panel jplPanel.setLayout(new GridLayout(1,1)); // we use grid layout jplPanel.setLayout(new GridLayout(1,1)); // we use grid layout return jplPanel; } /** *This method will be called when we want to create list of jtable on jplPanel * we use text as parameter and the arugument can be National or Conference * the parameter is compared with team list and looped through teamlist only * team with national or conference league will be put into jtable * * @param text * @return */ public JScrollPane lister(String text){ DefaultTableModel model = new DefaultTableModel(); JTable table = new JTable(model); //jtable with parameter of model model.addColumn("Teamname"); //colum for jtable model.addColumn("Coaches"); model.addColumn("Division"); model.addColumn("League"); model.addColumn("Fulltime"); model.addColumn("Number of Coaches"); if(text.equalsIgnoreCase("TeamList")){ //create row of team list using loop for(int i=0; i<m.getTeamList().size(); i++) { model.addRow(new Object[]{m.getTeamList().get(i).getName(), m.getTeamList().get(i).getCoachesAsString(), m.getTeamList().get(i).getDivision(), m.getTeamList().get(i).getLeague(), m.getTeamList().get(i).isFulltime(), m.getTeamList().get(i).getCoachesNumber()}); } model.addRow(new Object[]{"Average of coaches", " " , " ", " ", " ", m.getAvgCoaches()});// we are couting average for whole team so we can use method m.getAvgCoaches here model.addRow(new Object[]{"Avg Round UP ", " " , " ", " ", " ", Math.ceil(m.getAvgCoaches())}); }else{ double totalCoaches =0; // counter total number of coaches who might be national or conference double counter =0 ; // count the total number of team double averageCoaches ; //create row of team list using loop for(int i=0; i<m.getTeamList().size(); i++) { if(m.getTeamList().get(i).getLeague().equalsIgnoreCase(text)) { counter = counter +1; totalCoaches = totalCoaches + m.getTeamList().get(i).getCoachesNumber(); // get total coaches for national or conference model.addRow(new Object[]{m.getTeamList().get(i).getName(), m.getTeamList().get(i).getCoachesAsString(), m.getTeamList().get(i).getDivision(), m.getTeamList().get(i).getLeague(), m.getTeamList().get(i).isFulltime(),m.getTeamList().get(i).getCoachesNumber()}); } else{ //do nothing } } averageCoaches = totalCoaches / counter; // calculate total average coaches for national and conference loop model.addRow(new Object[]{"Average of coaches", " " , " ", " ", " ", averageCoaches}); model.addRow(new Object[]{"Avg coaches Rounded Up", " " , " ", " ", " ", Math.ceil(averageCoaches)}); // put rounded up average of coaches for natioanl or conference in JTABLE } table.getColumnModel().getColumn(1).setMinWidth(550); //set the column size of coaches to 550 sp = new JScrollPane(table); //put the table insde scrollpane so we can scroll return sp; //returns scrollpane to caller } }
package com.capgemini.service; import java.util.Date; import java.util.List; import com.capgemini.exceptions.NoSuchPaymentFoundException; import com.capgemini.exceptions.PaymentFailureException; import com.capgemini.model.Payment; public interface PaymentService { public boolean parkingBookingPayment(Payment payment) throws PaymentFailureException; public Payment findPaymentById(long paymentId) throws NoSuchPaymentFoundException; public List<Payment> findPaymentByDate(Date paymentDate) throws NoSuchPaymentFoundException; }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.internal.ep; import java.util.logging.Level; import java.util.logging.Logger; import org.overlord.rtgov.common.service.Service; import org.overlord.rtgov.ep.EPContext; import org.overlord.rtgov.ep.ResultHandler; /** * This class provides services to the EventProcessor * implementations that process the events. * * NOTE: Retained the internal version for compatibility with FSW 6.0. This class * can be deprecated once this is no longer an issue. */ public class DefaultEPContext implements EPContext { private static final Logger LOG=Logger.getLogger(DefaultEPContext.class.getName()); private static final ThreadLocal<Object> RESULT=new ThreadLocal<Object>(); private java.util.Map<String,Service> _services=null; private java.util.Map<String,Object> _parameters=null; private ResultHandler _handler=null; /** * The default constructor. */ public DefaultEPContext() { } /** * This constructor initializes the service map. * * @param services The map of services available */ public DefaultEPContext(java.util.Map<String,Service> services) { _services = services; } /** * This constructor initializes the service map. * * @param services The map of services available * @param parameters The map of parameters avaiable */ public DefaultEPContext(java.util.Map<String,Service> services, java.util.Map<String,Object> parameters) { _services = services; _parameters = parameters; } /** * This method sets the result handler. * * @param handler The asynchronous result handler * * NOTE: This mechanism is experimental, so may change in the future. */ public void setResultHandler(ResultHandler handler) { _handler = handler; } /** * This method sets the service map. * * @param services The services */ public void setServices(java.util.Map<String,Service> services) { _services = services; } /** * {@inheritDoc} */ public void logInfo(String info) { LOG.info(info); } /** * {@inheritDoc} */ public void logWarning(String warning) { LOG.warning(warning); } /** * {@inheritDoc} */ public void logError(String error) { LOG.severe(error); } /** * {@inheritDoc} */ public void logDebug(String debug) { if (LOG.isLoggable(Level.FINE)) { LOG.fine(debug); } } /** * {@inheritDoc} */ public void handle(Object result) { if (LOG.isLoggable(Level.FINEST)) { LOG.finest(">>> "+this+": Handle result="+result); } if (_handler != null) { if (result instanceof java.io.Serializable) { _handler.handle((java.io.Serializable)result); } else { LOG.severe("Result from event processor is not serializable: "+result); } } else { RESULT.set(result); } } /** * This method retrieves the result forwarded by the rule. * * @return The result, or null if not defined */ public Object getResult() { Object ret=RESULT.get(); if (LOG.isLoggable(Level.FINEST)) { LOG.finest(">>> "+this+": Get result="+ret); } return (ret); } /** * {@inheritDoc} */ public Service getService(String name) { Service ret=null; if (_services != null) { ret = _services.get(name); } return (ret); } /** * {@inheritDoc} */ public Object getParameter(String name) { Object ret=null; if (_parameters != null) { ret = _parameters.get(name); } return (ret); } }
package com.yinghai.a24divine_user.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.support.annotation.IdRes; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.text.TextPaint; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.yinghai.a24divine_user.R; /** * Created by chenjianrun on 2017/9/19. */ public class NoteView extends RelativeLayout{ //================常量============================= private static final String TAG = "NoteView"; public static final int LEFT = 0; public static final int RIGHT = 1; public static final int TOP = 2; public static final int BOTTOM = 3; //===========自定义属性系列开始======================= private int mImageHeight; //图标的高度 private int mTextSize; //文本的字体大小,单位是 px private int mTextToImage; //文本到图标的距离 private int mMarginVertical; //垂直方向的边距 private int mMarginHorizontal; //水平方向的边距 private String mTextContent; //签的内容 private Drawable mImageSrc; //图标资源 private int mTurn; //签头的方向 private int mIconColor; //图标的颜色 private int mTextColor; //文本的颜色 private int mBackground; //背景颜色 private int mNormalBackground; //背景颜色,正常 private int mPressBackgroup; //背景颜色,按下 private Drawable mBackgroundDrawable; //背景颜色 //================默认值============================ private int defaultImageHeight = 25; //默认的的图标宽高 private int defaultTextSize = 12; //默认的文字大小,单位是 px private int defaultTextToImage = 5; //默认的图标和文字的间距 private int mTextLenght; //文字的总长度 private int mNoteMinWidth; //签允许最小的宽度 private int mNoteMinHeight; //签允许最小的高度 private int mNoteRadius; //签头的圆角半径 @IdRes private int mImageViewId = 0X1000; //ImageView 的 id @IdRes private int mTextViewId = 0X1001; //Textview 的 id private int myheight; private boolean hasBackground = false; public NoteView(Context context) { this(context,null); } public NoteView(Context context, AttributeSet attrs) { this(context, attrs,0); } public NoteView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); final TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.NoteView, defStyleAttr, 0); mImageHeight = typedArray.getDimensionPixelOffset(R.styleable.NoteView_note_iamgeHeight,dp2px(context,defaultImageHeight)); mTextSize = typedArray.getDimensionPixelSize(R.styleable.NoteView_note_textSize,sp2px(context,defaultTextSize)); mMarginVertical = typedArray.getDimensionPixelOffset(R.styleable.NoteView_note_marginVertical,mImageHeight/2); mMarginHorizontal = typedArray.getDimensionPixelOffset(R.styleable.NoteView_note_marginHorizontal,mImageHeight/2); mTextToImage = typedArray.getDimensionPixelOffset(R.styleable.NoteView_note_textToImage,dp2px(context,defaultTextToImage)); mTextContent = typedArray.getString(R.styleable.NoteView_note_textContent); mImageSrc = typedArray.getDrawable(R.styleable.NoteView_note_imageSrc); mTurn = typedArray.getInt(R.styleable.NoteView_note_turn,0); mNormalBackground = typedArray.getColor(R.styleable.NoteView_note_background,Color.WHITE); mPressBackgroup = typedArray.getColor(R.styleable.NoteView_note_background,ContextCompat.getColor(getContext(),R.color.grey_light2)); mBackground = mNormalBackground; mBackgroundDrawable = typedArray.getDrawable(R.styleable.NoteView_note_backgroundDrawable); mTextColor = typedArray.getColor(R.styleable.NoteView_note_textColor,Color.BLACK); mIconColor = typedArray.getColor(R.styleable.NoteView_note_iconColor,0); typedArray.recycle(); RoundRectShape roundRectShape = new RoundRectShape(getRectRadius(), null, null); ShapeDrawable drawable=new ShapeDrawable(roundRectShape); setBackground(drawable); hasBackground = true; createImageView(); createTextView(); computeLenght(); } /** * 用来计算文字长度、最小宽度、最小高度 */ private void computeLenght(){ mTextLenght = getTextViewLenght(); int maxWidth = Math.max(mImageHeight,mTextLenght/mTextContent.length()); if (mTurn == TOP || mTurn == BOTTOM){ //签头向上或向下 //最小高度 = 文字长度 + 图标长度 + 垂直间距 + 文字图标间距 mNoteMinHeight = mTextLenght + mImageHeight + mMarginVertical * 4 + mTextToImage; //最小宽度 = (文字高度和图标间的最大值)+ 水平边距 mNoteMinWidth = maxWidth + mMarginHorizontal * 2; }else{ //签头向左或向右 //最小高度 = (文字高度和图标间的最大值)+ 水平边距 mNoteMinHeight = maxWidth + mMarginVertical * 2; //最小宽度 = 文字长度 + 图标长度 + 垂直间距 + 文字图标间距 mNoteMinWidth = mTextLenght + mImageHeight + mMarginHorizontal * 4 +mTextToImage; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(getRequestMeasureSpec(widthMeasureSpec,mNoteMinWidth), getRequestMeasureSpec(heightMeasureSpec,mNoteMinHeight)); } /** * 用来计算符合要求的 MeasureSpec(宽高) * @param measureSpec * @param requestMinLength 需求限制的最小长度(业务需求,保证能够完整显示图标和文字的长度) * @return */ private int getRequestMeasureSpec(int measureSpec, int requestMinLength){ int mode = MeasureSpec.getMode(measureSpec); int size = MeasureSpec.getSize(measureSpec); int mReturnSize; if (mode == MeasureSpec.EXACTLY){ mReturnSize = size; }else{ mReturnSize = requestMinLength; } return MeasureSpec.makeMeasureSpec(mReturnSize,mode); } @Override protected void onDraw(Canvas canvas) { if (mBackgroundDrawable==null) { RoundRectShape roundRectShape = new RoundRectShape(getRectRadius(), null, null); ShapeDrawable drawable=new ShapeDrawable(roundRectShape); drawable.getPaint().setColor(mBackground); drawable.getPaint().setAntiAlias(true); drawable.getPaint().setStyle(Paint.Style.FILL);//描边 setBackground(drawable); }else{ setBackground(mBackgroundDrawable); } super.onDraw(canvas); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mBackground = mPressBackgroup; invalidate(); break; case MotionEvent.ACTION_OUTSIDE: mBackground = mNormalBackground; invalidate(); break; case MotionEvent.ACTION_UP: mBackground = mNormalBackground; invalidate(); break; default: break; } return super.onTouchEvent(event); } /** * 获取矩形的圆角半径(onDraw 之后调用) * @return 返回的数组表示矩形 (01 左上 23右上 45右下 67左下) 圆角半径 */ private float[] getRectRadius(){ float radius; if (mTurn == TOP || mTurn == BOTTOM) { radius = getWidth() / 2; }else{ radius = getHeight() / 2; } switch (mTurn){ case LEFT: return new float[]{radius,radius,0,0,0,0,radius,radius}; case TOP: return new float[]{radius,radius,radius,radius,0,0,0,0}; case RIGHT: return new float[]{0,0,radius,radius,radius,radius,0,0}; case BOTTOM: return new float[]{0,0,0,0,radius,radius,radius,radius}; default: break; } return null; } private void createImageView(){ LayoutParams layoutParams = new LayoutParams(mImageHeight,mImageHeight); switch (mTurn){ case LEFT: layoutParams.setMargins(mMarginHorizontal,mMarginVertical,mTextToImage,mMarginVertical); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); layoutParams.addRule(RelativeLayout.CENTER_VERTICAL); break; case TOP: layoutParams.setMargins(mMarginHorizontal,mMarginVertical,mMarginHorizontal,mTextToImage); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); break; case RIGHT: layoutParams.setMargins(mTextToImage,mMarginVertical,mMarginHorizontal,mMarginVertical); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); layoutParams.addRule(RelativeLayout.CENTER_VERTICAL); break; case BOTTOM: layoutParams.setMargins(mMarginHorizontal,mTextToImage,mMarginHorizontal,mMarginVertical); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); break; default: break; } ImageView imageView = new ImageView(getContext()); imageView.setLayoutParams(layoutParams); imageView.setScaleType(ImageView.ScaleType.FIT_XY); imageView.setImageDrawable(mImageSrc); imageView.setId(mImageViewId); if (mIconColor != 0) { DrawableCompat.setTint(imageView.getDrawable(),mIconColor); } addView(imageView); } private void createTextView(){ LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); switch (mTurn){ case LEFT: layoutParams.setMargins(0,mMarginVertical,mMarginHorizontal,mMarginVertical); layoutParams.addRule(RelativeLayout.RIGHT_OF,mImageViewId); layoutParams.addRule(RelativeLayout.CENTER_VERTICAL); break; case TOP: layoutParams.setMargins(mMarginHorizontal,0,mMarginHorizontal,mMarginVertical); layoutParams.addRule(RelativeLayout.BELOW,mImageViewId); layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); break; case RIGHT: layoutParams.setMargins(mMarginHorizontal,mMarginVertical,0,mMarginVertical); layoutParams.addRule(RelativeLayout.LEFT_OF,mImageViewId); layoutParams.addRule(RelativeLayout.CENTER_VERTICAL); break; case BOTTOM: layoutParams.setMargins(mMarginHorizontal,mMarginVertical,mMarginHorizontal,0); layoutParams.addRule(RelativeLayout.ABOVE,mImageViewId); layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); break; default: break; } TextView textView = new TextView(getContext()); textView.setLayoutParams(layoutParams); textView.setText(mTextContent); textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,mTextSize); textView.setGravity(Gravity.CENTER); textView.setId(mTextViewId); textView.setTextColor(mTextColor); if (mTurn == TOP || mTurn == BOTTOM){ textView.setEms(1); }else{ textView.setLines(1); } addView(textView); } /** * 获取textview 中字符串显示的像素长度 * @return */ private int getTextViewLenght(){ TextView textView = new TextView(getContext()); textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,mTextSize); TextPaint textPaint = textView.getPaint(); return (int) textPaint.measureText(mTextContent); } // @Override // protected void onAttachedToWindow() { // super.onAttachedToWindow(); // final ViewTreeObserver viewTreeObserver = getViewTreeObserver(); // viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { // @Override // public void onGlobalLayout() { // viewTreeObserver.removeOnGlobalLayoutListener(this); // ValueAnimator valueAnimator = ValueAnimator.ofInt(mMarginVertical,getHeight()); // valueAnimator.setDuration(2000); // //时间插器,值的变化速率 // valueAnimator.setInterpolator(new CycleInterpolator(2)); // valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { // @Override // public void onAnimationUpdate(ValueAnimator animation) { // // int height = (Integer) animation.getAnimatedValue(); // getLayoutParams().height = height; // requestLayout(); // Log.d(TAG, "height: "+height); // } // }); // valueAnimator.start(); // } // }); // } public int getMyheight() { return myheight; } public void setMyheight(int myheight) { this.myheight = myheight; LayoutParams layoutParams = (LayoutParams) getLayoutParams(); layoutParams.height = myheight; setLayoutParams(layoutParams); invalidate(); } private int dp2px(Context context, float dpValue) { final float densityScale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * densityScale + 0.5f); } public static int sp2px(Context context, float spValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } }
package com.mobica.rnd.parking.parkingbe; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @SpringBootApplication @EnableMongoRepositories("com.mobica.rnd.parking.parkingbe.repository") public class ParkingBeApplication { public static void main(String[] args) { SpringApplication.run(ParkingBeApplication.class, args); } }
package com.itheima.mobileplayer64.ui.activity; import java.util.ArrayList; import java.util.List; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.widget.TextView; import com.itheima.mobileplayer64.R; import com.itheima.mobileplayer64.adapter.MainFragmentPagerAdapter; import com.itheima.mobileplayer64.ui.fragment.AudioListFragment; import com.itheima.mobileplayer64.ui.fragment.VideoListFragment; import com.nineoldandroids.view.ViewHelper; import com.nineoldandroids.view.ViewPropertyAnimator; public class MainActivity extends BaseActivity { /** 当ViewPager发生变化的时候被回调 */ private final class OnVideoPageChangeListener implements OnPageChangeListener { @Override /** 当有界面被选中时返回被选中的position */ public void onPageSelected(int position) { // 更新tab updateTabs(position); } @Override /** 当有滑动时间发生时,返回当前第一个可见page的position,以及手指所在的位置*/ public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // logE("MainActivity.onPageScrolled.position="+position+";offsetPixels="+positionOffsetPixels+";Offset="+positionOffset); // 移动大小 = 起始位置 + 偏移位置 // 起始位置 = position * 指示器宽度 // 偏移位置 = positionOffsetPixels / 页数 // int offsetX = positionOffsetPixels /mFragments.size(); int offsetX = (int) (positionOffset * indicate_line.getWidth()); int startX = position * indicate_line.getWidth(); int translationX = startX + offsetX; // 根据移动大小修改指示器位置 ViewHelper.setTranslationX(indicate_line, translationX); } @Override /** 当滑动状态发生变更时被回调 */ public void onPageScrollStateChanged(int state) { } } private ViewPager viewPager; private List<Fragment> mFragments; private TextView tv_video; private TextView tv_audio; private View indicate_line; @Override /** 返回Activity使用的布局id */ protected int getLayoutResId() { return R.layout.activity_main; } @Override /** 执行findViewById操作 */ protected void initView() { viewPager = (ViewPager) findViewById(R.id.main_viewpager); tv_video = (TextView) findViewById(R.id.main_tv_video); tv_audio = (TextView) findViewById(R.id.main_tv_audio); indicate_line = findViewById(R.id.main_indicate_line); } @Override /** 执行注册监听器和适配器的操作 */ protected void initListener() { mFragments = new ArrayList<Fragment>(); viewPager.setAdapter(new MainFragmentPagerAdapter(getSupportFragmentManager(), mFragments)); viewPager.setOnPageChangeListener(new OnVideoPageChangeListener()); } @Override /** 获取界面上要使用的数据,执行初始化操作 */ protected void initData() { // 填充Fragment列表 mFragments.add(new VideoListFragment()); mFragments.add(new AudioListFragment()); // 初始化标签栏大小 updateTabs(0); // 初始化指示器宽度 int screenW = getWindowManager().getDefaultDisplay().getWidth(); indicate_line.getLayoutParams().width = screenW / mFragments.size(); indicate_line.requestLayout(); } @Override /** 处理在BaseActivity未处理的点击事件 */ protected void processClick(View v) { } /** 更新所有的Tab */ private void updateTabs(int position) { // 当视频被选中则放大,否则缩小 updateTab(position, tv_video, 0); // 当视频被选中则放大,否则缩小 updateTab(position, tv_audio, 1); } /** 更新指定位置的Tab */ private void updateTab(int position, TextView currentTextView, int currentPosition) { // TODO ViewPropertyAnimator与ObjectAnimator区别 if (position == currentPosition) { currentTextView.setTextColor(getResources().getColor(R.color.green)); ViewPropertyAnimator.animate(currentTextView).scaleX(1.2f).setDuration(200); ViewPropertyAnimator.animate(currentTextView).scaleY(1.2f).setDuration(200); } else { currentTextView.setTextColor(getResources().getColor(R.color.halfwhite)); ViewPropertyAnimator.animate(currentTextView).scaleX(1.0f).setDuration(200); ViewPropertyAnimator.animate(currentTextView).scaleY(1.0f).setDuration(200); } } }
package com.tencent.tencentmap.mapsdk.a; class cf$1 implements Runnable { private /* synthetic */ cf a; cf$1(cf cfVar) { this.a = cfVar; } public final void run() { if (this.a.b != null && this.a.a != null) { this.a.a.a(this.a.b); } } }
package com.lsz.common; import com.google.common.base.MoreObjects; import javax.annotation.Resources; import java.io.*; import java.net.URL; import static com.google.common.base.Preconditions.checkArgument; /* * Created by ex-lingsuzhi on 2018/4/16. */ public class FileUtils { public static String FileUTF8ToStr(File file){ if (file.isDirectory() || !file.exists()) { return null; } FileInputStream fileInputStream = null; InputStreamReader inputStreamReader = null; try { fileInputStream = new FileInputStream(file); inputStreamReader = new InputStreamReader(fileInputStream, "utf-8"); // BufferedReader br = new BufferedReader(inputStreamReader); StringBuffer strBuf = new StringBuffer(); while (inputStreamReader.ready()) { strBuf.append((char) inputStreamReader.read()); } return strBuf.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { inputStreamReader.close(); fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } public static void strToFileUTF8(String fileName, String strBuff) { FileOutputStream out = null; OutputStreamWriter osw = null; File file = new File(fileName); if (file.exists()){ file.delete(); } try { out = new FileOutputStream(file); osw = new OutputStreamWriter(out, "utf-8"); osw.write(strBuff); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (osw != null) osw.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); } } } public static URL getResource(String resourceName) { ClassLoader loader = MoreObjects.firstNonNull( Thread.currentThread().getContextClassLoader(), Resources.class.getClassLoader()); URL url = loader.getResource(resourceName); checkArgument(url != null, "resource %s not found.", resourceName); return url; } }
package com.atgem.googleplay; import java.lang.reflect.Type; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import bean.AllInfoMessage; import bean.BarpostItem; import bean.Url; import com.atgem.ailisidemo.WorksActivity; import com.atgem.lunbodemo.HomeActivity; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.heima52.pullrefresh.view.RefreshListView; import com.heima52.pullrefresh.view.RefreshListView.OnRefreshListener; import com.lidroid.xutils.BitmapUtils; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest.HttpMethod; public class AllInfoMessageActivity extends Activity { private List<AllInfoMessage> list; private RefreshListView lv; AllInfoMessAdapter adapter ; GridView gv; int[] images=new int[]{R.drawable.home1,R.drawable.tuijian1,R.drawable.zixun,R.drawable.yuyue1}; private Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { //更新UI adapter.notifyDataSetChanged(); lv.completeRefresh(); }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_all_info_message); lv = (RefreshListView) findViewById(R.id.lv_allinfomess); gv=(GridView) findViewById(R.id.gv_news); lv.setOnRefreshListener(new OnRefreshListener() { @Override public void onPullRefresh() { //需要联网请求服务器的数据,然后更新UI requestDataFromServer(true); } @Override public void onLoadingMore() { requestDataFromServer(true); } }); showAcitonBar(); String url =Url.url+":8080/Alisi2/AllInfoMessageServlet"; initData(url); /* lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(position==1){ System.out.println("位置是:"+position); Intent intent = new Intent(AllInfoMessageActivity.this,InfoMessageActivity.class); startActivity(intent); } } }); */ lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { // TODO Auto-generated method stub if(position==1) { Intent intent = new Intent(AllInfoMessageActivity.this,InfoMessageActivity.class); startActivity(intent); } } }); gv.setAdapter(new GvAdapter()); gv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { // TODO Auto-generated method stub switch (position) { case 0: Intent intent_home=new Intent(AllInfoMessageActivity.this,HomeActivity.class); startActivity(intent_home); break; case 1: Intent intent3=new Intent(AllInfoMessageActivity.this,WorksActivity.class); startActivity(intent3); break; /* case 2: Intent intent3=new Intent(AllInfoMessageActivity.this,AllInfoMessageActivity.class); startActivity(intent3); break;*/ case 3: Intent intent4=new Intent(AllInfoMessageActivity.this,OrderMainActivity.class); startActivity(intent4); break; default: break; } } }); } /** * 模拟向服务器请求数据 */ private void requestDataFromServer(final boolean isLoadingMore){ new Thread(){ public void run() { SystemClock.sleep(3000);//模拟请求服务器的一个时间长度 Timestamp a = new Timestamp(new Date().getTime()); if(isLoadingMore){ list.add(new AllInfoMessage(3,Url.url+":8080/Alisi2/images/canvas5.png")); // barpostItems.add(new BarpostItem(b_name, b_position, b_icon, content, image, time, commentCount, zanCount, belong)) }else { // barpostItems.add(new ); //list.add(new BarpostItem("刘远","小职员","Url.url+"10.40.7.71:8080/Alisi2/upload/ee78adcc-f739-40ef-b99e-d8c86847370f.png","完美发型!","Url.url+"10.40.7.71:8080/Alisi2/upload/9304bb26-7266-4e8f-a8dc-adc9934fcee1.png",a, 5,5,"3")); list.add(new AllInfoMessage(3,Url.url+":8080/Alisi2/images/canvas5.png")); } //在UI线程更新UI handler.sendEmptyMessage(0); }; }.start(); } private void initData(String url) { HttpUtils httputil = new HttpUtils(); httputil.send(HttpMethod.GET, url, new RequestCallBack<String>() { @Override public void onFailure(HttpException error, String msg) { // TODO Auto-generated method stub } @Override public void onSuccess(ResponseInfo<String> allinfomesslist) { String json = allinfomesslist.result; Gson gson = new Gson(); list = new ArrayList<AllInfoMessage>(); Type type = new TypeToken<List<AllInfoMessage>>() { }.getType(); list = gson.fromJson(json, type); for(AllInfoMessage o:list){ System.out.println(o.getIm_id()+o.getIm_logo()); } adapter = new AllInfoMessAdapter( list); lv.setAdapter(adapter); } }); } class AllInfoMessAdapter extends BaseAdapter{ List<AllInfoMessage> list1; private LayoutInflater inflater = LayoutInflater.from(AllInfoMessageActivity.this); public AllInfoMessAdapter(List<AllInfoMessage> list) { this.list1 = list; System.out.println(list1.size()); } @Override public int getCount() { return list1.size(); } @Override public Object getItem(int position) { return list1.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { AllInfoMessage allInfoMessage = list1.get(position); if( convertView == null ){ convertView = inflater.inflate(R.layout.activity_all_info_message_items, null); } ImageView logo = (ImageView) convertView.findViewById(R.id.iv_ifomesslogo); BitmapUtils utils = new BitmapUtils(AllInfoMessageActivity.this); utils.display(logo, allInfoMessage.getIm_logo()); return convertView; } } public void showAcitonBar(){ ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); ActionBar.LayoutParams lp =new ActionBar.LayoutParams( ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View titleView = inflater.inflate(R.layout.action_bar_title, null); actionBar.setCustomView(titleView, lp); actionBar.setDisplayShowHomeEnabled(false);//去掉导航 actionBar.setDisplayShowTitleEnabled(false);//去掉标题 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); actionBar.setDisplayShowCustomEnabled(true); TextView tv_title=(TextView) actionBar.getCustomView().findViewById(R.id.title); tv_title.setText("资讯"); ImageButton imageBtn = (ImageButton) actionBar.getCustomView().findViewById(R.id.image_btn); imageBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } class GvAdapter extends BaseAdapter{ @Override public int getCount() { // TODO Auto-generated method stub return images.length; } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return images[arg0]; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { // TODO Auto-generated method stub View view=View.inflate(AllInfoMessageActivity.this,R.layout.gv_item,null); if(arg1==null){ // View view=View.inflate(HomeActivity.this,R.layout.gv_item,null); arg1=view; } ImageView imageView=(ImageView) view.findViewById(R.id.iv_item); imageView.setImageResource(images[arg0]); return view; } } }
import java.util.Scanner; public class SumAndAverage { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("정수를 몇 개 더하시겠습니까? "); int n = input.nextInt(); System.out.print(n + "개의 정수를 차례로 입력하시오: "); float sum=0; for (int i=0; i < n; i++) sum = sum + input.nextInt(); System.out.println("정수의 합 = " +sum); System.out.printf("평균 = %.2f", sum/n); } }
import java.io.IOException; import java.util.HashMap; import java.util.Map; import XMLReader.SigninData; import ECSConnecter.SigninConnecter; public class testSignin { public static void main(String[] args) { try { signintest(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void signintest() throws IOException { Map<String, String> map = new HashMap<String, String>(); map.put("name", "kbyyd4"); map.put("password", "123456798"); SigninConnecter signconn = new SigninConnecter(map); signconn.getXML(); signconn.readXML(); SigninData data = signconn.getData(); System.out.println(data.getResult()); System.out.println(data.getId()); } }
package com.semantyca.skyra.modules.operator.service; import com.semantyca.nb.core.dataengine.jpa.model.constant.ExistenceState; import com.semantyca.nb.core.rest.outgoing.Outcome; import com.semantyca.nb.core.service.AbstractService; import com.semantyca.nb.core.user.IUser; import com.semantyca.officeframe.modules.reference.dao.ExplorationStatusDAO; import com.semantyca.officeframe.modules.reference.model.ExplorationStatus; import com.semantyca.skyra.ApplicationConst; import com.semantyca.skyra.modules.operator.dao.ExplorationDAO; import com.semantyca.skyra.modules.operator.model.Exploration; import com.semantyca.skyra.modules.operator.model.embedded.PointCoordiantes; import com.semantyca.skyra.modules.operator.other.KMLParser; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; @Path(ApplicationConst.BASE_URL + "explorations") @RequestScoped public class ExplorationsResource extends AbstractService<Exploration> { @Inject private ExplorationDAO dao; @Inject private ExplorationStatusDAO explorationStatusDAO; @Override protected ExplorationDAO getDao() { return dao; } protected Exploration composeNew(IUser user) { Exploration entityInst = new Exploration(); entityInst.setAuthor(user.getId()); entityInst.setTitle(""); ExplorationStatus status = explorationStatusDAO.findByIdentifier("planned"); entityInst.setStatus(status); entityInst.setExistenceState(ExistenceState.NOT_SAVED); entityInst.setStartTime(entityInst.getRegDate()); dao.add(entityInst); return entityInst; } @POST @Path("uploadFile") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile(List<Attachment> attachments, @Context HttpServletRequest request) { List<PointCoordiantes> coordinates = new ArrayList<>(); Outcome outcome = attachmentRequestHandler(attachments); KMLParser parser = new KMLParser(); coordinates.addAll(parser.process(outcome.temporaryFileName)); outcome.addPayload(coordinates); return Response.status(Response.Status.CREATED).entity(outcome).build(); } @GET @Path("action/getCoordinates") @Produces(MediaType.APPLICATION_JSON) public Response getExploration() { List<Exploration> coordinates = new ArrayList<>(); List<Exploration> list = getDao().findAll(); for (Exploration exploration : list) { if (exploration.getFlightPath().size() > 0) { coordinates.add(exploration); } } Outcome outcome = new Outcome(); return Response.status(Response.Status.CREATED).entity(outcome.addPayload(coordinates)).build(); } }
package day2; import java.util.concurrent.TimeUnit; import org.hamcrest.Matchers; import org.json.simple.JSONObject; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import io.restassured.RestAssured; import static io.restassured.RestAssured.*; public class GitHub { @BeforeTest public void BeforeTest() { RestAssured.baseURI="https://api.github.com/orgs/ORG/repos"; RestAssured.authentication=RestAssured.oauth2("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"); } @Test(enabled=true) public void gettingAllRepositories() { given() .auth() .oauth2("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") .when() .get() .then() .log() .body() .statusCode(200); } @Test(enabled=true) public void createRepositories() { JSONObject data=new JSONObject(); data.put("name","RestAssured1"); data.put("description","I am created by Rest Assured Tool"); data.put("home page", "https://github.com/Sarthak-thecreator"); given() .auth() .oauth2("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") .header("Content-Type","application/json") .body(data.toJSONString()) .when() .post("https://api.github.com/orgs/ORG/repos") .then() .log() .headers() .statusCode(201) .time(Matchers.lessThan(8000L),TimeUnit.MILLISECONDS); } }
package model.dao; import entities.Model; import java.util.List; import java.util.Map; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.engine.spi.FilterDefinition; import org.primefaces.model.SortOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository("modelDao") public class ModelDaoImpl implements ModelDao{ private SessionFactory sessionFactory; @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession(){ return sessionFactory.getCurrentSession(); } @Override public List<Model> modelLazyList(int first,int pageSize,String sortField,SortOrder sortOrder,Map<String,Object> filters){ String field=null; String order=null; List<Model> l=null; if(sortField!=null){ switch(sortField){ case "name":field="name"; break; case "year":field="year"; break; case "fuel":field="fuel"; break; case "brand.country":field="brand.country"; break; } if(sortOrder.toString().equalsIgnoreCase("ascending")){ order="asc"; }else{ order="desc"; } } if(filters.containsKey("name")){ getSession().enableFilter("name").setParameter("nameParam", filters.get("name")); } if(filters.containsKey("year")){ //Integer i=Integer.parseInt(filters.get("year").toString()); getSession().enableFilter("year").setParameter("yearParam",filters.get("year").toString()); } if(filters.containsKey("fuel")){ getSession().enableFilter("fuel").setParameter("fuelParam", filters.get("fuel")); } if(filters.containsKey("brand.country")){ getSession().enableFilter("country").setParameter("countryParam", filters.get("brand.country")); } if(sortField==null){ l=getSession().createQuery("select m from Model m").setFirstResult(first).setMaxResults(pageSize).list(); }else{ l=getSession().createQuery("select m from Model m order by "+field+" "+order).setFirstResult(first).setMaxResults(pageSize).list(); } return l; } @Override public int count(Map<String,Object> filters){ if(filters.containsKey("name")){ getSession().enableFilter("name").setParameter("nameParam", filters.get("name")); } if(filters.containsKey("year")){ getSession().enableFilter("year").setParameter("yearParam", filters.get("year")); } if(filters.containsKey("fuel")){ getSession().enableFilter("fuel").setParameter("fuelParam", filters.get("fuel")); } if(filters.containsKey("brand.country")){ getSession().enableFilter("country").setParameter("countryParam", filters.get("brand.country")); } return getSession().createQuery("select m from Model m").list().size(); } @Override public List<Model> lista(){ return getSession().createQuery("select m from Model m").list(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jidouauto.mvvm.rxjava.transformer; import com.jidouauto.mvvm.rxjava.LifecycleSource; import io.reactivex.*; import io.reactivex.functions.Function; import io.reactivex.functions.Predicate; import org.reactivestreams.Publisher; import java.util.concurrent.CancellationException; /** * @author eddie * <p> * 提供将业务流程和lifecycle绑定的实现 * @see {@link LifecycleSource} */ public final class LifecycleTransformer<T> implements ObservableTransformer<T, T>, FlowableTransformer<T, T>, SingleTransformer<T, T>, MaybeTransformer<T, T>, CompletableTransformer { final Observable<?> observable; public static <T, R> LifecycleTransformer<T> bindUntilEvent(final Observable<R> lifecycle, final R... events) { checkNotNull(lifecycle, "lifecycle == null"); checkNotNull(events, "event == null"); return bind(takeUntilEvent(lifecycle, events)); } private static <T> T checkNotNull(T reference, Object errorMessage) { if (reference == null) { throw new NullPointerException(String.valueOf(errorMessage)); } else { return reference; } } public static <T, R> LifecycleTransformer<T> bind(final Observable<R> lifecycle) { return new LifecycleTransformer<>(lifecycle); } private static <R> Observable<R> takeUntilEvent(final Observable<R> lifecycle, final R... events) { return lifecycle.filter(new Predicate<R>() { @Override public boolean test(R lifecycleEvent) throws Exception { for (R event : events) { if (lifecycleEvent.equals(event)) { return true; } } return false; } }); } public LifecycleTransformer(Observable<?> observable) { if (null == observable) { throw new NullPointerException("observable is null"); } this.observable = observable; } @Override public ObservableSource<T> apply(Observable<T> upstream) { return upstream.takeUntil(observable); } @Override public Publisher<T> apply(Flowable<T> upstream) { return upstream.takeUntil(observable.toFlowable(BackpressureStrategy.LATEST)); } @Override public SingleSource<T> apply(Single<T> upstream) { return upstream.takeUntil(observable.firstOrError()); } @Override public MaybeSource<T> apply(Maybe<T> upstream) { return upstream.takeUntil(observable.firstElement()); } @Override public CompletableSource apply(Completable upstream) { return Completable.ambArray(upstream, observable.flatMapCompletable(CANCEL_COMPLETABLE)); } static final Function<Object, Completable> CANCEL_COMPLETABLE = new Function<Object, Completable>() { @Override public Completable apply(Object ignore) throws Exception { return Completable.error(new CancellationException()); } }; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LifecycleTransformer<?> that = (LifecycleTransformer<?>) o; return observable.equals(that.observable); } @Override public int hashCode() { return observable.hashCode(); } @Override public String toString() { return "LifecycleTransformer{" + "observable=" + observable + '}'; } }
package sso.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 類說明:spring 應用 單例 * @author Ken * @version 創建時間2016-01-25 */ public class SpringContextUtil { private static ApplicationContext context; public static ApplicationContext getApplicationContext() { if (context == null) { //通配符 context = new ClassPathXmlApplicationContext("classpath:/config/spring/*Context.xml"); } return context; } public static void setApplicationContext(ApplicationContext outcontext) { context = outcontext; } }
package com.nxtlife.mgs.jpa; import java.util.Collection; import java.util.Date; import java.util.List; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.repository.query.Param; import com.nxtlife.mgs.entity.activity.Activity; import com.nxtlife.mgs.entity.session.Event; import com.querydsl.core.types.Predicate; public interface SessionRepository extends JpaRepository<Event, Long>, QuerydslPredicateExecutor<Event> { public List<Event> findAll(Predicate predicate); public Event findByCidAndActiveTrue(String cid); public List<Event> findAllByGradesCidAndClubCidAndTeacherCidAndActiveTrue(String gradeCid, String clubCid, String teacherCid, Pageable pageable); public List<Event> findAllByGradesCidAndClubCidAndActiveTrue(String gradeCid, String clubCid, Pageable pageable); public List<Event> findAllByGradesCidAndClubCidAndStartDateGreaterThanAndStartDateLessThanAndActiveTrue( String gradeCid, String clubCid, Date rangeBegin, Date rangeEnd, Sort sort); public List<Event> findAllByGradesCidAndClubCidAndStartDateGreaterThanAndStartDateLessThanAndTeacherCidAndActiveTrue( String gradeCid, String clubCid, Date rangeBegin, Date rangeEnd, String teacherCid, Sort sort); @Query(value = "select e from Event e join e.grades g where g.cid =:gradeCid and e.club in :clubs and e.teacher.cid = :teacherCid and e.active = true group by e.club , e.startDate ,e.teacher") public List<Event> findAllByGradesCidAndClubInAndTeacherCidAndActiveTrueGroupByClubId( @Param("gradeCid") String gradeCid, @Param("clubs") Collection<Activity> clubs, @Param("teacherCid") String teacherCid, Pageable pageable); @Query(value = "select e from Event e join e.grades g where g.cid =:gradeCid and e.club in :clubs and e.active = true group by e.club , e.startDate ,e.teacher") public List<Event> findAllByGradesCidAndClubInAndActiveTrueGroupByClubId(@Param("gradeCid") String gradeCid, @Param("clubs") Collection<Activity> clubs, Pageable pageable); @Query(value = "select e from Event e join e.grades g where g.cid =:gradeCid and e.club in :clubs and e.startDate > :rangeBegin and e.startDate < :rangeEnd and e.active = true group by e.club , e.startDate, e.teacher") public List<Event> findAllByGradesCidAndClubInAndStartDateGreaterThanAndStartDateLessThanAndActiveTrueGroupByClubId( @Param("gradeCid") String gradeCid, @Param("clubs") Collection<Activity> clubs, @Param("rangeBegin") Date rangeBegin, @Param("rangeEnd") Date rangeEnd, Sort sort); @Query(value = "select e from Event e join e.grades g where g.cid =:gradeCid and e.club in :clubs and e.startDate > :rangeBegin and e.startDate < :rangeEnd and e.teacher.cid = :teacherCid and e.active = true group by e.club , e.startDate, e.teacher") public List<Event> findAllByGradesCidAndClubInAndStartDateGreaterThanAndStartDateLessThanAndTeacherCidAndActiveTrueGroupByClubId( @Param("gradeCid") String gradeCid, @Param("clubs") Collection<Activity> clubs, @Param("rangeBegin") Date rangeBegin, @Param("rangeEnd") Date rangeEnd, @Param("teacherCid") String teacherCid, Sort sort); public List<Event> findAllByTeacherCidAndClubCidAndActiveTrue(String teacherCid, String clubCid, Pageable pageable); public List<Event> findAllByTeacherCidAndClubCidAndStartDateGreaterThanAndStartDateLessThanAndActiveTrue( String teacherCid, String clubCid, Date rangeBegin, Date rangeEnd, Sort sort); @Query(value = "select e from Event e where e.teacher.cid =:teacherCid and e.club in :clubs and e.active = true group by e.club , e.startDate ,e.teacher") public List<Event> findAllByTeacherCidAndClubInAndActiveTrueGroupByClubId(@Param("teacherCid") String teacherCid, @Param("clubs") List<Activity> clubs, Pageable pageable); @Query(value = "select e from Event e where e.teacher.cid =:teacherCid and e.club in :clubs and e.startDate > :rangeBegin and e.startDate < :rangeEnd and e.active = true group by e.club , e.startDate ,e.teacher") public List<Event> findAllByTeacherCidAndClubInAndStartDateGreaterThanAndStartDateLessThanAndActiveTrueGroupByClubId( @Param("teacherCid") String teacherCid, @Param("clubs") Collection<Activity> clubs, @Param("rangeBegin") Date rangeBegin, @Param("rangeEnd") Date rangeEnd, Sort sort); @Modifying @Query(value = "update Event s set s.active = ?2 where s.cid = ?1 and s.active = true") public int deleteByCidAndActiveTrue(String cid ,Boolean active); public boolean existsByCidAndActiveTrue(String sessionId); }
package Employee_task_Galya; public class ContractEmployee extends Employee { protected String federalTaxIDMember = "123456"; public ContractEmployee (String federalTaxIDMember, String employeeID){ } @Override public void getFullInfo() { System.out.println("Employee FIN is " + federalTaxIDMember); System.out.println("Employee ID is " + employeeID); } }
package com.valleskeyp.primerhyme; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import com.valleskeyp.primerhyme.CreateView.ResponseReceiver; import android.app.IntentService; import android.content.Intent; public class RhymeService extends IntentService { public RhymeService() { super("RhymeService"); } @Override protected void onHandleIntent(Intent intent) { String word = intent.getStringExtra("word"); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://rhymebrain.com/talk?function=getRhymes&word=" + word); String rhymeList; try { HttpResponse httpResponse = httpClient.execute(httpPost); InputStream inputStream = httpResponse.getEntity().getContent(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); String bufferedStrChunk = null; while((bufferedStrChunk = bufferedReader.readLine()) != null){ stringBuilder.append(bufferedStrChunk); } rhymeList = stringBuilder.toString(); if (rhymeList != null) { Intent broadcastIntent = new Intent(); broadcastIntent.setAction(ResponseReceiver.RHYME_RESPONSE); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("rhymeList", rhymeList); sendBroadcast(broadcastIntent); } } catch (ClientProtocolException cpe) { System.out.println("First Exception cause of HttpResponese :" + cpe); cpe.printStackTrace(); } catch (IOException ioe) { System.out.println("Second Exception cause of HttpResponse :" + ioe); ioe.printStackTrace(); } } }
package Unidade2; import java.applet.Applet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; public class AloMundo extends Applet { /* 1) Escrever o Applet AloMundo e implementar os métodos do seu Ciclo de Vida. */ private static final long serialVersionUID = 1L; @Override public void init() { System.out.println("Inicializando..."); } @Override public void paint(Graphics g) { g.setColor(Color.BLUE); g.setFont(new Font("Times New Roman", Font.BOLD, 30)); this.setBackground(Color.GREEN); this.setSize(400, 100); g.drawString("Versão JVM: " +System.getProperty("java.version"), 20, 20); g.drawString("Versão S.O: " +System.getProperty("os.name"), 50, 50); //g.drawRect(0, 0, 150, 150); //g.setColor(Color.CYAN); //g.setFont(new Font("Times New Roman", Font.BOLD,16)); //g.drawString("Alo Mundo", 20, 20); } @Override public void start() { System.out.println("Executando..."); } @Override public void stop() { System.out.println("Parando..."); } @Override public void destroy() { System.out.println("Eliminando..."); } /*1) Escrever no método paint() do Applet AloMundo as propriedades do computador (versão da JVM e do Sistema operacional) em que o mesmo está sendo executado. - Obs: A cor de fundo do applet deverá ser verde; a cor da fonte do texto deverá ser azul; e a fonte Times New Roman 30 Bold. - Dica: use a classe System e os métodos setBackground(...), setColor(...) e setFont(...), respectivamente. */ /* Para rodar a classe: Run As > Java Applet */ /* Para criar esta classe: */ /* Superclass retira-se: java.lang.Object informa JApplet > Brownser seleciona JApplet - javax.swing*/ }
package pl.edu.wat.wcy.pz.project.server.controller; import lombok.AllArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.*; import pl.edu.wat.wcy.pz.project.server.dto.TicTacToeDTO; import pl.edu.wat.wcy.pz.project.server.dto.TicTacToeGameDTO; import pl.edu.wat.wcy.pz.project.server.dto.TicTacToeGameStateDTO; import pl.edu.wat.wcy.pz.project.server.dto.TicTacToeMoveDTO; import pl.edu.wat.wcy.pz.project.server.entity.game.TicTacToeGame; import pl.edu.wat.wcy.pz.project.server.service.TicTacToeService; import java.util.List; @AllArgsConstructor @CrossOrigin @RestController @RequestMapping("/games") public class TicTacToeController { private TicTacToeService ticTacToeService; private SimpMessagingTemplate template; @PostMapping("/tictactoe") public ResponseEntity<?> createGame(@RequestBody TicTacToeDTO ticTacToeDTO) { UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = principal.getUsername(); TicTacToeGameDTO createdGameDto = ticTacToeService.createGame(ticTacToeDTO, username); template.convertAndSend("/tictactoe/add", createdGameDto); return new ResponseEntity<>(createdGameDto, HttpStatus.OK); } @GetMapping("/tictactoe/{gameId}") public TicTacToeGameDTO getGame(@PathVariable Long gameId) { return ticTacToeService.getGame(gameId); } @GetMapping("/tictactoe/games/active") public List<TicTacToeGame> getActiveGame() { UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = principal.getUsername(); return ticTacToeService.getActiveGames(username); } @GetMapping("/tictactoe/list") public List<TicTacToeGameDTO> getAvailableGames() { UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return ticTacToeService.getAvailableGames(principal.getUsername()); } @GetMapping("/tictactoe/join/{gameId}") public ResponseEntity<?> joinToGame(@PathVariable Long gameId) { UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = principal.getUsername(); TicTacToeGameDTO gameDto = ticTacToeService.addSecondPlayerToGame(gameId, username); template.convertAndSend("/tictactoe/update", gameDto); return new ResponseEntity<>(gameDto, HttpStatus.OK); } @GetMapping("/tictactoe/start/{gameId}") public ResponseEntity<?> startGame(@PathVariable Long gameId) { UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = principal.getUsername(); TicTacToeGameDTO gameDTO = ticTacToeService.startGame(gameId, username); template.convertAndSend("/tictactoe/update", gameDTO); return new ResponseEntity<>(gameDTO, HttpStatus.OK); } @GetMapping("/tictactoe/state/{gameId}") public TicTacToeGameStateDTO getGameState(@PathVariable Long gameId) { return ticTacToeService.getGameState(gameId); } @DeleteMapping("/tictactoe/abandon") public ResponseEntity<?> abandonGame() { UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = principal.getUsername(); Long gameId = ticTacToeService.abandonGame(username); template.convertAndSend("/tictactoe/delete", gameId); return new ResponseEntity<>(HttpStatus.OK); } /* ***Games history */ @GetMapping("/tictactoe/history") public List<TicTacToeGameDTO> getGamesHistory() { UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return ticTacToeService.getUserGamesHistory(principal.getUsername()); } @GetMapping("/tictactoe/history/moves/{gameId}") public List<TicTacToeMoveDTO> getGameMoves(@PathVariable Long gameId) { return ticTacToeService.getGameMoves(gameId); } }
package com.pduleba.spring.data.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.pduleba.jpa.model.OwnerModel; @Repository @Transactional public interface OwnerDao extends JpaRepository<OwnerModel, Long>{ OwnerModel getById(Long ownerId); void delete(OwnerModel owner); long count(); List<OwnerModel> getByFirstName(String firstName); }
package com.smartwerkz.bytecode.vm; import java.io.IOException; import com.smartwerkz.bytecode.classfile.Classfile; import com.smartwerkz.bytecode.classfile.MethodInfo; import com.smartwerkz.bytecode.primitives.JavaObject; import com.smartwerkz.bytecode.vm.memory.Heap; public class RuntimeDataArea { private final VMLog log = new VMLog(RuntimeDataArea.class.getName(), false); private final MethodArea methodArea; private final Heap heap = new Heap(); private final BootstrapClassloader bcl; private final VirtualMachine vm; private Threads threads; public RuntimeDataArea(VirtualMachine vm) { if (vm == null) throw new IllegalArgumentException("The VirtualMachine must not be null"); this.vm = vm; this.bcl = vm.getBootstrapClassloader(); this.methodArea = new MethodArea(vm); this.threads = new Threads(vm, this, bcl, methodArea, heap); } public Threads getThreads() { return threads; } public VirtualMachine vm() { return vm; } public Heap getHeap() { return heap; } public MethodArea getMethodArea() { return methodArea; } public BootstrapClassloader getBootstrapClassLoader() { return bcl; } public Classfile loadClass(VirtualThread thread, String mainClassName) { try { Classfile loaded = bcl.load(mainClassName); if (methodArea.contains(loaded)) return loaded; log.debug("Loading class '%s': ", mainClassName, loaded); String superClassName = loaded.getSuperClassName(); if (superClassName != null && !methodArea.hasClass(superClassName)) { log.debug("Loading superclass '%s' of class '%s'", superClassName, mainClassName); loadClass(thread, superClassName); } methodArea.add(loaded, bcl); if (loaded.getThisClassName().equals("java/lang/System")) { MethodInfo methodInfo = loaded.getMethods(vm).findMethodInfo(vm, "initializeSystemClass"); thread.execute(loaded, methodInfo, new JavaObject[0]); } link(thread, loaded); initialize(thread, loaded); return loaded; } catch (IOException e) { throw new RuntimeException(e); } } private void link(VirtualThread thread, Classfile cf) throws IOException { log.debug("Linking class: %s", cf.getThisClassName()); verification(); preparation(thread, cf); } private void verification() { } private void preparation(VirtualThread thread, Classfile cf) throws IOException { log.debug("Preparing class: %s", cf.getThisClassName()); createAndInitializeStaticFieldDefaultValues(thread, cf); } private void createAndInitializeStaticFieldDefaultValues(VirtualThread thread, Classfile cf) throws IOException { cf.getFields().initialize(vm, thread, this); cf.getMethods(vm).initialize(vm, thread, this); } private void initialize(VirtualThread thread, Classfile cf) throws IOException { log.debug("TODO Initializing class: %s", cf.getThisClassName()); } }
public abstract class Shape { private String shapeName; public Shape(String name) { shapeName = name; } abstract double area(); @Override public String toString() { return shapeName; } }
/** * */ package ufc.br.so.test; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import ufc.br.so.scheduler.model.processor.Process; import ufc.br.so.scheduler.model.queue.MultiLevelQueue; import ufc.br.so.scheduler.model.queue.Queue; import ufc.br.so.scheduler.model.queue.algorithm.RR; import ufc.br.so.util.XMLHelper; /** * @author franzejr * */ public class TestRR { MultiLevelQueue multiLevelQueue; List<Process> processes = new ArrayList<Process>(); RR rr = new RR(); /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { List<MultiLevelQueue> listMultilevelQueue = XMLHelper.readMultilevelqueueFile("multilevelQueueTest.xml"); multiLevelQueue = listMultilevelQueue.get(0); for(Queue queue : multiLevelQueue.getListAllQueues()){ for(Process process : queue.getListProcesses()){ processes.add(process); } } } /** * Test method for {@link ufc.br.so.scheduler.model.queue.algorithm.RR#execute(java.util.List, ufc.br.so.kernel.spi.Parameters)}. */ @Test public void testExecuteListOfProcessParameters() { rr.setQuantumTime(1); rr.execute(processes, null); String result = ""; for(Process process : rr.getResult()){ result += process.toString() +","; System.out.println("***** "+process.toString()+" *****"); System.out.println("EXECUTION TIME:"+process.getExecutionTime()); System.out.println("Waiting TIME:"+process.getWaitingTime()); System.out.println("TurnAround TIME:"+process.getTurnAroundTime()); } result = result.length() > 0 ? result.substring(0,result.length() - 1) + "." : result; System.out.println("**************"); System.out.println(" RESULT:"+result); //assertEquals("RESULT", "P3,P2,P0,P1.", result); } }
package com.example.lib.core; import androidx.annotation.NonNull; import com.example.lib.net.ReportNetworkType; import org.jetbrains.annotations.NotNull; //测试配置类 public class TestReportConfig extends ReportConfig implements Cloneable { private TestReportConfig() { } public static final class Builder { long mMaxCacheSize = 32 * 1024 * 1024L; int mFlushInterval; String mServerUrl; int mNetworkTypePolicy = ReportNetworkType.TYPE_3G | ReportNetworkType.TYPE_4G | ReportNetworkType.TYPE_WIFI | ReportNetworkType.TYPE_5G; boolean isSubProcessFlushData = false; public Builder setMaxCacheSize(long mMaxCacheSize) { this.mMaxCacheSize = mMaxCacheSize; return this; } public Builder setFlushInterval(int mFlushInterval) { this.mFlushInterval = mFlushInterval; return this; } public Builder setServerUrl(String mServerUrl) { this.mServerUrl = mServerUrl; return this; } public Builder setNetworkTypePolicy(int mNetworkTypePolicy) { this.mNetworkTypePolicy = mNetworkTypePolicy; return this; } public Builder setSubProcessFlushData(boolean subProcessFlushData) { isSubProcessFlushData = subProcessFlushData; return this; } public Builder(String serverUrl) { this.mServerUrl = serverUrl; } public Builder(ReportConfig config) { this.mMaxCacheSize = config.mMaxCacheSize; this.mFlushInterval = config.mFlushInterval; this.mServerUrl = config.mServerUrl; this.mNetworkTypePolicy = config.mNetworkTypePolicy; this.isSubProcessFlushData = config.isSubProcessFlushData; } public TestReportConfig build() { TestReportConfig testReportConfig = new TestReportConfig(); testReportConfig.mMaxCacheSize = mMaxCacheSize; testReportConfig.mFlushInterval = mFlushInterval; testReportConfig.mServerUrl = mServerUrl; testReportConfig.mNetworkTypePolicy = mNetworkTypePolicy; testReportConfig.isSubProcessFlushData = isSubProcessFlushData; return testReportConfig; } } @NonNull @Override protected TestReportConfig clone() { TestReportConfig copyObject = this; try { copyObject = (TestReportConfig) super.clone(); } catch (CloneNotSupportedException e) { } return copyObject; } }
public class TestEdible { public static void main(String[] args) { Object[] objects = { new Tiger(), new Chicken(), new Apple(), new Orange() }; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof Edible) System.out.println(((Edible) objects[i]).howToEat()); if (objects[i] instanceof Animal) { System.out.println(((Animal) objects[i]).sound()); } } } } abstract class Animal { /** Return animal sound */ abstract String sound(); //implicitly public } class Chicken extends Animal implements Edible { @Override public String howToEat() { return "Chicken: Fry it"; } @Override public String sound() { return "Chicken: cock-a-doodle-doo"; } } class Tiger extends Animal { @Override public String sound() { return "Tiger: RROOAARR"; } } interface Edible { //implicitly abstract /** Describe how to eat */ String howToEat(); //always implicitly public and abstract } abstract class Fruit implements Edible { } class Apple extends Fruit { @Override public String howToEat() { return "Apple: Make apple cider"; } } class Orange extends Fruit implements Edible{ @Override public String howToEat() { return "Orange: Make orange juice"; } }
package am.main.exception; import am.main.api.validation.FormValidation; import am.main.session.AppSession; import am.main.spi.AMCode; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; public class BusinessException extends WebApplicationException { private AMCode errorCode; private String formattedError; private String CLASS; private String METHOD; private String fullErrMsg; private FormValidation errorList; public BusinessException(AppSession session, AMCode errorCode, Object ... args) { this(session, Status.BAD_REQUEST, errorCode, args); } public BusinessException(AppSession session, Status status, AMCode errorCode, Object ... args) { super(Response.status(status) .entity(new AMError(errorCode, session.getMessageHandler(), args)) .type(MediaType.APPLICATION_JSON_TYPE) .build()); this.errorCode = errorCode; this.formattedError = errorCode.getFullMsg(session.getMessageHandler(), args); this.fullErrMsg = session.toString() + this.formattedError; this.CLASS = session.getCLASS(); this.METHOD = session.getMETHOD(); } public BusinessException(AppSession session, FormValidation validation) { super(Response.status(Status.BAD_REQUEST) .entity(new AMError(validation)) .type(MediaType.APPLICATION_JSON_TYPE) .build()); this.errorCode = validation.getCode(); this.formattedError = validation.getMainError() + "\n" + validation.getErrorList(); this.fullErrMsg = session.toString() + this.formattedError; this.errorList = validation; this.CLASS = session.getCLASS(); this.METHOD = session.getMETHOD(); } public AMCode getErrorCode() { return errorCode; } public void setErrorCode(AMCode errorCode) { this.errorCode = errorCode; } public String getCLASS() { return CLASS; } public void setCLASS(String CLASS) { this.CLASS = CLASS; } public String getMETHOD() { return METHOD; } public void setMETHOD(String METHOD) { this.METHOD = METHOD; } public String getFullErrMsg() { return fullErrMsg; } public void setFullErrMsg(String fullErrMsg) { this.fullErrMsg = fullErrMsg; } public String getFormattedError() { return formattedError; } public void setFormattedError(String formattedError) { this.formattedError = formattedError; } public FormValidation getErrorList() { return errorList; } public void setErrorList(FormValidation errorList) { this.errorList = errorList; } }
package server.externalapi; import org.json.JSONException; import org.json.JSONObject; import java.io.*; import java.net.URL; import java.nio.charset.Charset; /** * JSONReader class that parses the JSON response from external API */ public class JSONReader { /** * Builds a string for the full JSON response from a reader. * @param r The reader to read the JSON response * @return The full JSON response as a string * @throws IOException if something goes wrong whilst reading the JSON response */ private static String readAll(Reader r) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = r.read()) != -1) { sb.append((char) cp); } return sb.toString(); } /** * * @param url The url to call and get the JSON response from * @return A JSONObject with all * @throws IOException if something goes wrong whilst parsing the response obtained from the url * @throws JSONException if something goes wrong whilst building the JSONObject from the response of the url */ public static JSONObject readJSONFromURL(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } } }
package com.kush.lib.expressions; public class ExpressionException extends Exception { private static final long serialVersionUID = 1L; public static ExpressionException exceptionWithMessage(String messageTemplate, Object... args) { return new ExpressionException(String.format(messageTemplate, args)); } public ExpressionException() { } public ExpressionException(String message) { super(message); } public ExpressionException(String message, Exception e) { super(message, e); } }
package food; /** * User: Alexandr * Date: 19.11.2014 */ public class Desserts extends Drinks { public void choc(Meat meat){ } }
package ru.smartsarov.election.db; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the "uik_html" database table. * */ @Entity @Table(name="\"uik_html\"") @NamedQuery(name="UikHtml.findAll", query="SELECT u FROM UikHtml u") public class UikHtml implements Serializable { private static final long serialVersionUID = 1L; @Column(name="\"cik_uik_html\"", length=2000000000) private String cikUikHtml; @Id @Column(name="\"id\"") private int id; @Column(name="\"uik_number\"", nullable=false) private int uikNumber; @Column(name="\"vybory_izbirkom_uik_html\"", length=2000000000) private String vyboryIzbirkomUikHtml; @Column(name="\"vybory_izbirkom_uik_id\"", length=2000000000) private String vyboryIzbirkomUikId; @Column(name="\"vybory_izbirkom_uik_url\"", length=2000000000) private String vyboryIzbirkomUikUrl; //bi-directional one-to-one association to Uik // @OneToOne(mappedBy="uikHtml") // private Uik uik; public UikHtml() { } public String getCikUikHtml() { return this.cikUikHtml; } public void setCikUikHtml(String cikUikHtml) { this.cikUikHtml = cikUikHtml; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public int getUikNumber() { return this.uikNumber; } public void setUikNumber(int uikNumber) { this.uikNumber = uikNumber; } public String getVyboryIzbirkomUikHtml() { return this.vyboryIzbirkomUikHtml; } public void setVyboryIzbirkomUikHtml(String vyboryIzbirkomUikHtml) { this.vyboryIzbirkomUikHtml = vyboryIzbirkomUikHtml; } public String getVyboryIzbirkomUikId() { return this.vyboryIzbirkomUikId; } public void setVyboryIzbirkomUikId(String vyboryIzbirkomUikId) { this.vyboryIzbirkomUikId = vyboryIzbirkomUikId; } public String getVyboryIzbirkomUikUrl() { return this.vyboryIzbirkomUikUrl; } public void setVyboryIzbirkomUikUrl(String vyboryIzbirkomUikUrl) { this.vyboryIzbirkomUikUrl = vyboryIzbirkomUikUrl; } // public Uik getUik() { // return this.uik; // } // // public void setUik(Uik uik) { // this.uik = uik; // } }
import java.util.*; public class process { int state; int parent; int used; int prio; LinkedList<Integer> children; LinkedList<Integer> resources; process(){ state = 1; parent = 0; used = 0; prio = 0; children = new LinkedList<>(); resources = new LinkedList<>(); } process(int s, int p, int u, int pr, LinkedList<Integer> c, LinkedList<Integer> r){ state = s; parent = p; used = u; prio = pr; children = new LinkedList<>(); resources = new LinkedList<>(); for(Integer i : c){ children.add(i); } for(Integer i: r){ resources.add(i); } } void printAll(){ System.out.println("State: " + this.state); System.out.println("Parent: " + this.parent); System.out.println("Used: " + this.used); System.out.println("Priority: " + this.prio); System.out.println("Children: " + this.children); System.out.println("Resources: " + this.resources); } }
package ru.otus.spring.barsegyan.dto.ws; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class NotificationDto { private final NotificationType type; private final Object payload; }
package test; import static org.junit.Assert.*; import java.util.Hashtable; import java.util.Vector; import java.util.HashMap; import org.junit.Before; import org.junit.Test; import edu.uci.ics.sdcl.firefly.Answer; import edu.uci.ics.sdcl.firefly.CodeElement; import edu.uci.ics.sdcl.firefly.CodeSnippet; import edu.uci.ics.sdcl.firefly.FileDebugSession; import edu.uci.ics.sdcl.firefly.MethodParameter; import edu.uci.ics.sdcl.firefly.MethodSignature; import edu.uci.ics.sdcl.firefly.Microtask; import edu.uci.ics.sdcl.firefly.controller.MicrotaskSelector; import edu.uci.ics.sdcl.firefly.storage.MicrotaskStorage; public class MicrotaskSelectorTest { private String path = "."; private HashMap<String, FileDebugSession> debugSessionMap = new HashMap<String, FileDebugSession>(); private Hashtable<Integer, Microtask> microtaskMap; MicrotaskStorage memento = MicrotaskStorage.initializeSingleton(); MicrotaskSelector selector = new MicrotaskSelector(); String fileName = "SimpleSampleCode.java"; @Before public void setUp() throws Exception { MethodSignature signature = new MethodSignature("factorial", "public"); MethodParameter arg1, arg2; arg1 = new MethodParameter("Integer", "Seed"); arg2 = new MethodParameter("Integer", "Iterations"); signature.addMethodParameters(arg1); signature.addMethodParameters(arg2); StringBuffer buffer = new StringBuffer("public Integer factorial(Integer Seed, Integer Iterations){"); buffer.append("\n"); buffer.append("if(Seed!=null){"); buffer.append("\n"); buffer.append("int aux=1;"); buffer.append("\n"); buffer.append("for (int i=0;i<Iterations.intValue();i++){"); buffer.append("\n"); buffer.append("aux = aux * Seed;"); buffer.append("\n"); buffer.append("}"); buffer.append("\n"); buffer.append("return new Integer(aux);"); buffer.append("\n"); buffer.append("}"); buffer.append("\n"); buffer.append("else return null;"); buffer.append("\n"); buffer.append("}"); String body = buffer.toString().substring(buffer.toString().indexOf('{')); String questionArg1 = "Is there maybe something wrong in the declaration of function 'factorial' " + "at line 20 (e.g., requires a parameter that is not listed, needs different parameters to " + "produce the correct result, specifies the wrong or no return type, etc .)?"; String questionArg2 = "Is it possible that the conditional clause at line 2 has " + "problems (e.g., wrong Boolean operator, wrong comparison, misplaced parentheses, etc.)?"; String questionArg3 = "Is there maybe something wrong with the '<L>-loop' construct at line 4 " + "(e.g., incorrect initialization, wrong counter increment, wrong exit condition, etc.)?"; CodeSnippet codeSnippetFactorial = new CodeSnippet("sample", "SimpleSampleCode", signature, body, true, 7, 0, 7, 27, 7, 27, 10, 0); Microtask mtask1 = new Microtask(CodeElement.METHOD_INVOCATION, codeSnippetFactorial, null, questionArg1, 20, 0, 20, 58, 1,"failure description", null); Microtask mtask2 = new Microtask(CodeElement.IF_CONDITIONAL, codeSnippetFactorial, null, questionArg2, 2, 0, 2, 16, 2,"failure description", null); Microtask mtask3 = new Microtask(CodeElement.FOR_LOOP, codeSnippetFactorial, null, questionArg3, 4, 0, 4, 41, 3,"failure description", null); //Create the data structure this.microtaskMap = new Hashtable<Integer,Microtask>(); microtaskMap.put(new Integer(1),mtask1); microtaskMap.put(new Integer(2),mtask2); microtaskMap.put(new Integer(3),mtask3); FileDebugSession debugSession = new FileDebugSession(fileName,body, microtaskMap); this.debugSessionMap.put(fileName, debugSession); //Persist micro tasks memento.insert(fileName, debugSession); } //Test if it is incrementing @Test public void testIncrement() { FileDebugSession debugSession = memento.read(fileName); if((debugSession!=null) && (debugSession.getMicrotaskMap()!=null)){ Hashtable<Integer, Microtask> mMap = debugSession.getMicrotaskMap(); //Associate an answer Integer key = new Integer (1); Microtask mtask1 = mMap.get(key); Vector<Answer> answerList = mtask1.getAnswerList(); if(answerList==null) answerList= new Vector<Answer>(); answerList.add(new Answer(Answer.YES,"statement should be executed ealier","workerID", "elapsedTime", "timeStamp")); mtask1.setAnswerList(answerList); debugSession.incrementAnswersReceived(answerList.size()); int max = debugSession.getMaximumAnswerCount(); //Check whether it actually incremented assertEquals(1, max); } else fail("Not yet implemented"); } //Check whether the increment is taking effect @Test public void testGetFirst() { //Associate answers to two microtasks FileDebugSession debugSession = memento.read(fileName); if((debugSession!=null) && (debugSession.getMicrotaskMap()!=null)){ Hashtable<Integer, Microtask> mMap = debugSession.getMicrotaskMap(); Integer key = new Integer (1); Microtask mtask1 = mMap.get(key); Vector<Answer> answerList = mtask1.getAnswerList(); if(answerList==null) answerList= new Vector<Answer>(); answerList.add(new Answer(Answer.YES,"statement should be executed ealier","workerID", "elapsedTime", "timeStamp")); mtask1.setAnswerList(answerList); mMap.put(key, mtask1); debugSession.incrementAnswersReceived(answerList.size()); key = new Integer (2); Microtask mtask2 = mMap.get(key); answerList = mtask2.getAnswerList(); if(answerList==null) answerList= new Vector<Answer>(); answerList.add(new Answer(Answer.NO,"","workerID", "elapsedTime", "timeStamp")); mtask2.setAnswerList(answerList); debugSession.incrementAnswersReceived(answerList.size()); //Persist data back mMap.put(new Integer (1), mtask1); mMap.put(new Integer (2), mtask2); debugSession.setMicrotaskMap(mMap); memento.insert(fileName, debugSession); Microtask mtask3 = this.selector.selectMicrotask(fileName); assertEquals(null,mtask3.getAnswerList()); //Cleans up. //memento.insert(fileName, debugSession); } else{ fail("Not yet implemented"); } } @Test public void testGetAllPlusOne(){ //Associate answers to two microtasks FileDebugSession debugSession = memento.read(fileName); if((debugSession!=null) && (debugSession.getMicrotaskMap()!=null)){ Hashtable<Integer, Microtask> mMap = debugSession.getMicrotaskMap(); Integer key = new Integer (1); Microtask mtask1 = mMap.get(key); Vector<Answer> answerList = mtask1.getAnswerList(); if(answerList==null) answerList= new Vector<Answer>(); answerList.add(new Answer(Answer.YES,"statement should be executed ealier","workerID", "elapsedTime", "timeStamp")); mtask1.setAnswerList(answerList); mMap.put(key, mtask1); debugSession.incrementAnswersReceived(answerList.size()); key = new Integer (2); Microtask mtask2 = mMap.get(key); answerList = mtask2.getAnswerList(); if(answerList==null) answerList= new Vector<Answer>(); answerList.add(new Answer(Answer.NO,"","workerID", "elapsedTime", "timeStamp")); mtask2.setAnswerList(answerList); debugSession.incrementAnswersReceived(answerList.size()); key = new Integer (3); Microtask mtask3 = mMap.get(key); answerList = mtask3.getAnswerList(); if(answerList==null) answerList= new Vector<Answer>(); answerList.add(new Answer(Answer.NO,"","workerID", "elapsedTime", "timeStamp")); answerList.add(new Answer(Answer.NO,"","workerID", "elapsedTime", "timeStamp")); mtask3.setAnswerList(answerList); debugSession.incrementAnswersReceived(answerList.size()); //Persist data back mMap.put(new Integer (1), mtask1); mMap.put(new Integer (2), mtask2); mMap.put(new Integer (3), mtask3); debugSession.setMicrotaskMap(mMap); memento.insert(fileName, debugSession); Microtask mtaskActual1 = this.selector.selectMicrotask(fileName); assertEquals(1,mtaskActual1.getAnswerList().size()); //Cleans up. //memento.insert(fileName, null); } else{ fail("Not yet implemented"); } } }
package CSArmyBot.events; import java.awt.*; import java.io.IOException; import java.util.concurrent.ExecutionException; import CSArmyBot.main; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.events.Event; import net.dv8tion.jda.core.events.message.guild.react.GuildMessageReactionAddEvent; import net.dv8tion.jda.core.hooks.EventListener; import net.dv8tion.jda.core.requests.RequestFuture; public class ReactionEvent implements EventListener { private static final String BotGUID = "435616811602673688"; //TODO Make "super star" for staff so a force command is not needed. @Override public void onEvent(Event e) { if (e instanceof GuildMessageReactionAddEvent) { GuildMessageReactionAddEvent event = (GuildMessageReactionAddEvent) e; if (event.getUser().isBot()) return; if (!event.getReactionEmote().getName().equals("⭐")) { return; } if (main.userData.get("starboard").containsValue(event.getMessageId())) return; TextChannel quotechannel = event.getGuild().getTextChannelsByName("starboard", true).get(0); try { int count = event.getReaction().getUsers().submit().get().size(); if (count >= 20) { main.userData.get("starboard").put(String.valueOf(main.userData.get("starboard").size()), event.getMessageId()); main.Save(); RequestFuture<Message> quote = event.getChannel().getMessageById(event.getMessageId()).submit(); EmbedBuilder embed = new EmbedBuilder(); embed.setColor(Color.decode("#000000")) .setTimestamp(quote.get().getCreationTime()) .setFooter(quote.get().getAuthor().getName() + "#" + quote.get().getAuthor().getDiscriminator(), quote.get().getAuthor().getAvatarUrl()); if (!quote.get().getContentRaw().isEmpty()) { embed.setDescription("\"" + quote.get().getContentRaw() + "\""); } if (!quote.get().getAttachments().isEmpty() && quote.get().getAttachments().get(0).isImage()) { embed.setImage(quote.get().getAttachments().get(0).getUrl()); } quotechannel.sendMessage(embed.build()).queue(); } } catch (InterruptedException | ExecutionException | IOException e1) { e1.printStackTrace(); } } } } /* */
package com.paytechnologies.cloudacar; import java.util.ArrayList; import android.util.Log; public class TripDetailsDTO { public String startAddressAlias = ""; public String endAddressAlias = ""; public String prefTime = ""; public String Tripid; public static Integer mid; public String Lti; public static Integer tripId; public static Integer lti; public static String tripRequestCount; public static String alertCount; public static ArrayList<TripDetailsDTO>tripDetails= new ArrayList<TripDetailsDTO>(); public TripDetailsDTO() { } public TripDetailsDTO(String StartAddAlias,String EndAddAlias,String TripId,String LiveTripId,String PrefTime){ this.startAddressAlias =StartAddAlias; this.endAddressAlias =EndAddAlias; this.Tripid = TripId; this.Lti = LiveTripId; this.prefTime = PrefTime; } public void setTripCount(String tripCount){ this.tripRequestCount=tripCount; } public String getTripCount(){ return tripRequestCount; } public void setAlertCount(String alert){ this.alertCount=alert; } public String getAlertCount(){ return alertCount; } public void setTripDetails(TripDetailsDTO tpDto){ tripDetails.add(tpDto); } public static TripDetailsDTO getTripDetails(int index) { Log.d("Index is :", ""+index); if(index < tripDetails.size()) { return tripDetails.get(index); } return null; } public String getstartAddAlias() { return startAddressAlias; } public void setStartAddAlias(String startAddressAlias) { this.startAddressAlias = startAddressAlias; } public String getendAddAlias() { return endAddressAlias; } public void setEndAddAlias(String endAddressAlias) { this.endAddressAlias = endAddressAlias; } public String getPrefTime() { return prefTime; } public void setPrefTime(String PrefTime) { this.prefTime = PrefTime; } public Integer getTripId() { return tripId; } public void setTripId(Integer TripId) { Log.d("Trip id is :", ""+TripId); this.tripId = TripId; } public Integer getMid() { return mid; } public void setmid(Integer mid) { Log.d("Mid id is :", ""+mid); this.mid =mid; } public Integer getlti() { return lti; } public void setlti(Integer lti) { Log.d("Lti id is :", ""+lti); this.lti =lti; } }
public class Origem{ private int codReg; private String regiao; Pais p = new Pais(); public void setPais(Pais p){ this.p = p; } public Pais getPais(){ return p; } //Setters public void setCodReg(int codReg){ this.codReg = codReg; } public void setRegiao(String regiao){ this.regiao = regiao; } //Getters public int getCodReg(){ return codReg; } public String getRegiao(){ return regiao; } }
package com.example.user.myapplication; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; /** * Created by Acrylon3 on 13/12/2016. */ public class ScoreButton extends Button{ public ScoreButton(Context context) { super(context); ctorStuff(); } public ScoreButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); ctorStuff(); } public ScoreButton(Context context, AttributeSet attrs) { super(context, attrs); ctorStuff(); } public ScoreButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); ctorStuff(); } private void ctorStuff(){ turnInvisible(); this.setPadding(0,0,0,0); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(6,6); setLayoutParams(lp); } private void turnInvisible(){ setVisibility(View.INVISIBLE); } public void turnVisible(int num){ setVisibility(View.VISIBLE); this.setText(""+num); } }
package es.maltimor.genericRest; import java.util.HashMap; import java.util.Map; import javax.ws.rs.core.UriInfo; import es.maltimor.genericUser.User; /* * Esta clase es la que centraliza la seguridad de todo el servicio rest, delegara en GenericMapperInfoTable * la implementacion para poder definir la seguridad a nivel individual de tabla */ public class GenericSecurityDaoCache implements GenericSecurityDao { private GenericSecurityDao securityDao; private Map<String,Boolean> map; public GenericSecurityDaoCache(){ map = new HashMap<String,Boolean>(); } private String hash(User user,String table,String filter,Map<String, Object> data,Object id, UriInfo ui){ String res="|"; if (user!=null) res+=user.getLogin()+"|"; else res+="null|"; res+=table+"|"; res+=filter+"|"; res+=data+"|"; res+=id+"|"; res+=ui+"|"; return res; } public boolean canSelect(User user, String table, String filter,UriInfo ui) throws Exception { String h=hash(user,table,filter,null,null,ui); if (map.containsKey(h)) return map.get(h); boolean res = securityDao.canSelect(user, table, filter, ui); map.put(h, res); return res; } public boolean canGetById(User user, String table, Object id,UriInfo ui) throws Exception { String h=hash(user,table,null,null,id,ui); if (map.containsKey(h)) return map.get(h); boolean res = securityDao.canGetById(user, table, id, ui); map.put(h, res); return res; } public boolean canInsert(User user, String table, Map<String, Object> data,UriInfo ui) throws Exception { String h=hash(user,table,null,data,null,ui); if (map.containsKey(h)) return map.get(h); boolean res = securityDao.canInsert(user, table, data, ui); map.put(h, res); return res; } public boolean canUpdate(User user, String table, Object id, Map<String, Object> data,UriInfo ui) throws Exception { String h=hash(user,table,null,data,id,ui); if (map.containsKey(h)) return map.get(h); boolean res = securityDao.canUpdate(user, table, id, data, ui); map.put(h, res); return res; } public boolean canDelete(User user, String table, Object id,UriInfo ui) throws Exception { String h=hash(user,table,null,null,id,ui); if (map.containsKey(h)) return map.get(h); boolean res = securityDao.canDelete(user, table, id, ui); map.put(h, res); return res; } public boolean canExecute(User user, String table, Map<String, Object> data,UriInfo ui) throws Exception { String h=hash(user,table,null,data,null,ui); if (map.containsKey(h)) return map.get(h); boolean res = securityDao.canExecute(user, table, data, ui); map.put(h, res); return res; } public GenericSecurityDao getSecurityDao() { return securityDao; } public void setSecurityDao(GenericSecurityDao securityDao) { this.securityDao = securityDao; } }
package pe.egcc.interesapp.service; import static java.lang.Math.pow; public class InteresService { public double calcularImporte(double capitalIni, double interes, int periodo){ double importe, calc_interes; calc_interes= interes/100; importe=capitalIni * pow((1+calc_interes),periodo); return importe; } }
package com.niit.designerswear; import javax.enterprise.inject.spi.Bean; import javax.transaction.Transactional; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.niit.designerswear.dao.CategoryDAO; import com.niit.designerswear.dao.CategoryDAO; import com.niit.designerswear.model.Category; import com.niit.designerswear.model.Category; @Controller public class CategoryController { @Autowired private CategoryDAO categoryDAO; @Autowired private Category category; @RequestMapping("/Category/Category") public ModelAndView Category() { ModelAndView mv = new ModelAndView("Index"); mv.addObject("ifUserClickedCategory", true); return mv; } }
package com.tencent.mm.plugin.sport.ui; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.R; import com.tencent.mm.bg.d; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.opensdk.modelmsg.WXMediaMessage; import com.tencent.mm.pluginsdk.ui.applet.ContactListExpandPreference; import com.tencent.mm.pluginsdk.ui.applet.ContactListExpandPreference.a; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.ui.base.preference.MMPreference; import com.tencent.mm.ui.base.preference.Preference; import com.tencent.mm.ui.base.preference.f; import com.tencent.mm.ui.contact.s; import java.util.ArrayList; import java.util.List; public class SportBlackListUI extends MMPreference { private ContactListExpandPreference hLp; private List<String> opv; private a opw = new 2(this); static /* synthetic */ void c(SportBlackListUI sportBlackListUI) { String c = bi.c(sportBlackListUI.opv, ","); Intent intent = new Intent(); intent.putExtra("titile", sportBlackListUI.getString(R.l.address_title_select_contact)); intent.putExtra("list_type", 1); intent.putExtra("list_attr", s.s(new int[]{s.ukF, WXMediaMessage.DESCRIPTION_LENGTH_LIMIT})); intent.putExtra("always_select_contact", c); d.b(sportBlackListUI, ".ui.contact.SelectContactUI", intent, 0); } public void onCreate(Bundle bundle) { super.onCreate(bundle); com.tencent.mm.plugin.sport.b.d.kB(39); if (this.opv == null) { this.opv = new ArrayList(); } au.HU(); Cursor d = c.FR().d("@werun.black.android", "", null); while (d.moveToNext()) { this.opv.add(d.getString(0)); } d.close(); this.hLp = (ContactListExpandPreference) this.tCL.ZZ("black_contact_list_pref"); this.hLp.a(this.tCL, this.hLp.mKey); this.hLp.kG(true).kH(true); this.hLp.p(null, this.opv); this.hLp.a(this.opw); this.hLp.setSummary(R.l.exdevice_we_sport_black_list_intro); setMMTitle(getString(R.l.exdevice_profile_add_black_list)); setBackBtn(new OnMenuItemClickListener() { public final boolean onMenuItemClick(MenuItem menuItem) { SportBlackListUI.this.finish(); return false; } }); } public final int Ys() { return R.o.sportblacklist_pref; } public final boolean a(f fVar, Preference preference) { return false; } protected void onActivityResult(int i, int i2, Intent intent) { super.onActivityResult(i, i2, intent); if (i == 0 && intent != null) { String stringExtra = intent.getStringExtra("Select_Contact"); if (!bi.oW(stringExtra)) { Object<String> F = bi.F(stringExtra.split(",")); if (F != null) { this.opv.addAll(F); this.hLp.p(null, this.opv); this.hLp.refresh(); for (String stringExtra2 : F) { au.HU(); com.tencent.mm.model.s.f(c.FR().Yg(stringExtra2)); } } } } } }
package net.raydeejay.gossip.test; import java.io.*; import java.net.*; public class B { public static void main(String[] argv) { try { //////////// // Emitting Socket client = new Socket("localhost", 1978); PrintWriter out = new PrintWriter(client.getOutputStream(), true); out.println("Hello!"); //////////// // Receiving ServerSocket s = new ServerSocket(1979); Socket sock = s.accept(); BufferedReader r = new BufferedReader(new InputStreamReader(sock.getInputStream())); System.out.println("Reply: "+r.readLine()); client.close(); } catch(Exception e){System.out.println(e);} } }
import exceptions.IncorrectFileNameException; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class UserFileReader { final static String DEFAULT_FILE_NAME = "users.txt"; static List<User> users = new ArrayList<>(); static User newUser = new User(); static int lineIdx = 0; public static List<User> readUsersList(String fileName, ReaderType readerType) throws IncorrectFileNameException { switch(readerType) { case BYTE_BUFFER: try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName), StandardCharsets.UTF_8)) { for (String line; (line = br.readLine()) != null; ) { readUserInfoFromLine(line); } } catch (IOException e) { if (!fileName.equals(DEFAULT_FILE_NAME)) { throw new IncorrectFileNameException("Incorrect filename : " + fileName); } } break; case SEEKABLE_BYTE_CHANNEL: break; case SCANNER: break; } return users; } public static void readUserInfoFromLine( String line) { switch (lineIdx) { case 0: newUser.setSurname(line); break; case 1: newUser.setFirstname(line); break; case 2: newUser.setMiddlename(line); break; case 3: newUser.setAge(line); break; case 4: newUser.addPassport(line); break; } lineIdx++; if (lineIdx == User.FIELDS_COUNT) { lineIdx = 0; users.add(newUser); newUser = new User(); } } }
package org.rhokk.hh.sealand.http; import java.io.IOException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpProtocolParams; import org.json.JSONObject; import org.rhokk.hh.sealand.BaseActivity; import org.rhokk.hh.sealand.util.StringUtils; import android.util.Log; public class HttpHelper { public static ServerResponse getServerResponse( final String payload, final String url, String userAgentString ) throws ClientProtocolException, IOException { final HttpPost post = new HttpPost( url ); Log.d( BaseActivity.LOG_ID, "Calling " + url + ":\n" + payload.toString() ); post.addHeader("Content-Type", "application/json"); post.addHeader("Authorization", "api_key=f34df0fc602d1ef9d7a1ba8fa8a051fd17d6d2a1"); post.setEntity( new StringEntity( payload, "UTF-8" ) ); final HttpClient client = new DefaultHttpClient(); if ( StringUtils.isNotBlank( userAgentString ) ) { HttpProtocolParams.setUserAgent( client.getParams(), userAgentString ); } try { final ServerResponse response = client.execute( post, new StringResponseHandler() ); return response; } finally { client.getConnectionManager().shutdown(); } } }
package com.lec.ex5_momchild; // Child child1 = new Child ("첫째 ") // child1.takeMoney(100); public class Child { private String name; static MomPouch momPouch = new MomPouch();; // static public Child(String name) { // 생성자,return type없어야하고,class name똑같에야하고 this.name = name; momPouch = new MomPouch(); } public void takeMoney(int money) { if (momPouch.getMoney() >= money) { // momPouch.money = momPouch.money - money; momPouch.setMoney(momPouch.getMoney() - money); System.out.println(name + "가" + money + "가져가서 엄마지갑엔" + momPouch.getMoney()); } else { System.out.println(name + "가 돈을 못받음. 현재 엄마 돈은" + momPouch.getMoney()); } } }
package fr.lteconsulting.training.moviedb.servlet; import fr.lteconsulting.training.moviedb.ejb.GestionUtilisateur; import fr.lteconsulting.training.moviedb.model.Utilisateur; import fr.lteconsulting.training.moviedb.outil.Session; import fr.lteconsulting.training.moviedb.outil.Vues; import javax.inject.Inject; 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 java.io.IOException; @WebServlet("/inscription") public class InscriptionServlet extends HttpServlet { @Inject private GestionUtilisateur gestionUtilisateur; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Vues.afficherInscription(req, resp, "Bienvenue"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String login = req.getParameter("login"); String password = req.getParameter("password"); String nom = req.getParameter("nom"); String prenom = req.getParameter("prenom"); Utilisateur existant = gestionUtilisateur.findByLogin(login); if (existant != null) { Vues.afficherInscription(req, resp, "Impossible avec ce login, il existe déjà !"); return; } Utilisateur utilisateur = new Utilisateur(); utilisateur.setLogin(login); utilisateur.setPassword(password); utilisateur.setNom(nom); utilisateur.setPrenom(prenom); gestionUtilisateur.add(utilisateur); Session.setUtilisateurConnecte(req.getSession(), utilisateur); resp.sendRedirect("produits"); } }
package com.thoughtworks.domain.product_detail.usecases; import com.thoughtworks.domain.UseCaseDataReceiver; import com.thoughtworks.domain.UseCaseError; import com.thoughtworks.domain.product_detail.Product; import com.thoughtworks.domain.product_list.ProductRepository; /** * Created on 12-06-2018. */ public class GetProductDetailsUseCase implements GetProductDetails { private final ProductRepository mProductRepository; public static GetProductDetails newInstance(ProductRepository productRepository) { return new GetProductDetailsUseCase(productRepository); } private GetProductDetailsUseCase(final ProductRepository productRepository) { mProductRepository = productRepository; } @Override public void execute(final Integer prodId, final UseCaseDataReceiver<Product> useCaseDataReceiver) { final Product repositoryOutput = mProductRepository.getProduct(prodId); if (repositoryOutput == null) { useCaseDataReceiver.onUseCaseDataReceivedFailed(new UseCaseError()); } else { useCaseDataReceiver.onUseCaseDataReceived(repositoryOutput); } } }
import java.util.Scanner; public class Simpleinput { static Scanner scan=new Scanner (System.in); public static void main(String[] args){ int sum=0; while(sum>=0)[] sum+=scan(); } public static int scan(){ return scan.nextInt(); } }
package lib.game; import static org.lwjgl.opengl.GL11.*; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import math.geom.Point2f; import math.geom.Point3f; import math.geom.Point3i; import org.newdawn.slick.opengl.Texture; /** * Representation of a 3D model in OpenGL * @author David Gardner * */ public class Model { public List<Point3f> vertices = new ArrayList<Point3f>(); public List<Point3f> normals = new ArrayList<Point3f>(); public List<Point2f> texCoords = new ArrayList<Point2f>(); public List<Face> faces = new ArrayList<Face>(); boolean textured = false; Texture tex; int texID; /** * Creates a new model * @param vertices list of vertices * @param normals list of normals * @param faces list of faces */ public Model(List<Point3f> vertices, List<Point3f> normals, List<Face> faces) { this.vertices = vertices; this.normals = normals; this.faces = faces; } public Model(List<Point3f> vertices, List<Point3f> normals, List<Face> faces, List<Point2f> texCoords, Texture tex) { this(vertices, normals, faces); this.texCoords = texCoords; this.tex = tex; } /** * Creates an empty model */ public Model() {}; /** * Reads the given .obj file and creates a new model from the data * @param f File object of the .obj file * @return a Model object created from the file * @throws FileNotFoundException * @throws IOException */ public static Model loadModel(File f) throws FileNotFoundException, IOException { BufferedReader reader = new BufferedReader(new FileReader(f)); Model m = new Model(); String line; while((line = reader.readLine()) != null) { if(line.startsWith("v ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); float z = Float.valueOf(line.split(" ")[3]); m.vertices.add(new Point3f(x, y, z)); //System.out.println("Added vertex " + (m.vertices.size()-1) + " (" + x + " ," + y + ", " + z + ")"); } else if(line.startsWith("vn ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); float z = Float.valueOf(line.split(" ")[3]); m.normals.add(new Point3f(x, y, z)); } else if(line.startsWith("vt ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); m.texCoords.add(new Point2f(x, y)); } else if(line.startsWith("f ")) { int vx = Integer.valueOf(line.split(" ")[1].split("/")[0]); int vy = Integer.valueOf(line.split(" ")[2].split("/")[0]); int vz = Integer.valueOf(line.split(" ")[3].split("/")[0]); Point3i v = new Point3i(vx, vy, vz); int nx = Integer.valueOf(line.split(" ")[1].split("/")[2]); int ny = Integer.valueOf(line.split(" ")[2].split("/")[2]); int nz = Integer.valueOf(line.split(" ")[3].split("/")[2]); Point3i n = new Point3i(nx, ny, nz); if (!line.split(" ")[1].split("/")[1].equals("")) { int tx = Integer.valueOf(line.split(" ")[1].split("/")[1]); int ty = Integer.valueOf(line.split(" ")[2].split("/")[1]); int tz = Integer.valueOf(line.split(" ")[3].split("/")[1]); Point3i t = new Point3i(tx, ty, tz); m.faces.add(new Face(v, n, t)); } else m.faces.add(new Face(v, n)); } } reader.close(); return m; } public static Model loadModel(ArrayList<String> modelData) { Model m = new Model(); String line; for(int i=0; i<modelData.size(); i++) { line = modelData.get(i); if(line.startsWith("v ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); float z = Float.valueOf(line.split(" ")[3]); m.vertices.add(new Point3f(x, y, z)); //System.out.println("Added vertex " + (m.vertices.size()-1) + " (" + x + " ," + y + ", " + z + ")"); } else if(line.startsWith("vn ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); float z = Float.valueOf(line.split(" ")[3]); m.normals.add(new Point3f(x, y, z)); } else if(line.startsWith("vt ")) { float x = Float.valueOf(line.split(" ")[1]); float y = Float.valueOf(line.split(" ")[2]); m.texCoords.add(new Point2f(x, y)); } else if(line.startsWith("f ")) { int vx = Integer.valueOf(line.split(" ")[1].split("/")[0]); int vy = Integer.valueOf(line.split(" ")[2].split("/")[0]); int vz = Integer.valueOf(line.split(" ")[3].split("/")[0]); Point3i v = new Point3i(vx, vy, vz); int nx = Integer.valueOf(line.split(" ")[1].split("/")[2]); int ny = Integer.valueOf(line.split(" ")[2].split("/")[2]); int nz = Integer.valueOf(line.split(" ")[3].split("/")[2]); Point3i n = new Point3i(nx, ny, nz); if (!line.split(" ")[1].split("/")[1].equals("")) { int tx = Integer.valueOf(line.split(" ")[1].split("/")[1]); int ty = Integer.valueOf(line.split(" ")[2].split("/")[1]); int tz = Integer.valueOf(line.split(" ")[3].split("/")[1]); Point3i t = new Point3i(tx, ty, tz); m.faces.add(new Face(v, n, t)); } else m.faces.add(new Face(v, n)); } } return m; } /** * Constructs a textured model from the given files * @param modelFile the .obj file with vertex, normal, and face data * @param textureFile the png format texture * @return a Model object constructed from the files * @throws FileNotFoundException * @throws IOException */ public static Model loadModel(File modelFile, File textureFile) throws FileNotFoundException, IOException { return loadModel(modelFile).loadTexture(textureFile.getAbsolutePath()); } /** * Loads the texture from the given png format file. * @param fileName of the png file. * @return the model with the texture added. */ public Model loadTexture(String fileName) { //this.tex = RenderUtils.loadTexture(fileName); //this.textured = (tex != null) && (!texCoords.isEmpty()); this.texID = RenderUtils.loadTexture(fileName, true); this.textured = true; return this; } public Model setTexture(Texture tex) { this.tex = tex; this.textured = (tex != null) && (!texCoords.isEmpty()); return this; } /** * Binds the texture to the OpenGL context */ public void bindTexture() { //if(tex!=null) tex.bind(); if(textured) RenderUtils.bindTexture(texID); } /** * * @return true if the object has a texture (texture coords and a texture file) */ public boolean hasTexture() { return textured; } /** * Creates an OpenGL display list for the model * @return the id of the display list */ public int createDisplayList(int list) { int displayList = glGenLists(list); glNewList(displayList, GL_COMPILE); { glBegin(GL_TRIANGLES); { int i=0; for(Face face : faces) { try { //glColor3f(1.0f, 0.0f, 0.7f); Point3f n1 = normals.get(face.normals.x-1); Point3f v1 = vertices.get(face.vertices.x-1); if(textured) { Point2f t1 = texCoords.get(face.texCoords.x-1); glTexCoord2f(t1.x, t1.y); } glNormal3f(n1.x, n1.y, n1.z); glVertex3f(v1.x, v1.y, v1.z); Point3f n2 = normals.get(face.normals.y-1); Point3f v2 = vertices.get(face.vertices.y-1); if(textured) { Point2f t2 = texCoords.get(face.texCoords.y-1); glTexCoord2f(t2.x, t2.y); } glNormal3f(n2.x, n2.y, n2.z); glVertex3f(v2.x, v2.y, v2.z); Point3f n3 = normals.get(face.normals.z-1); Point3f v3 = vertices.get(face.vertices.z-1); if(textured) { Point2f t3 = texCoords.get(face.texCoords.z-1); glTexCoord2f(t3.x, t3.y); } glNormal3f(n3.x, n3.y, n3.z); glVertex3f(v3.x, v3.y, v3.z); } catch (IndexOutOfBoundsException e) { System.err.println("faces[" + i + "]"); e.printStackTrace(); } i++; } } glEnd(); } glEndList(); return displayList; } public int createDisplayList() { return createDisplayList(RenderUtils.nextDisplayListID()); } }
import com.jfinal.plugin.activerecord.ActiveRecordPlugin; import com.jfinal.plugin.druid.DruidPlugin; import com.link.webMagic.NwnuWebMagic; import us.codecraft.webmagic.model.OOSpider; public class NwnuTest { public static void main(String[] args){ String url = "jdbc:mysql://localhost:3306/linkup?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull"; String username = "root"; String password = "123456"; DruidPlugin druidPlugin = new DruidPlugin(url,username,password); druidPlugin.start(); ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin); arp.addMapping("t_blog",NwnuWebMagic.class); arp.start(); NwnuWebMagic nwnu = new NwnuWebMagic(); nwnu.login("********","*******"); OOSpider.create(nwnu.getSite(),NwnuWebMagic.class).addUrl("http://www.jfinal.com/share/").run(); } }
package A; import B.MovieDBBasic; import B.MovieFachklasse; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import java.io.IOException; import java.net.URL; import java.util.LinkedList; import java.util.ResourceBundle; /** * An implementation of Grid * in movieScratcher * * @author Nicolas * @version 1.0 * @since 2018-Nov-30 */ public class Grid extends BorderPane implements Initializable { public TextField txtSearch; public Button btnSearch; public GridPane layoutCenterGrid; /* ---------------------------------------- Main ---------------------------------------------------------------- */ /* ---------------------------------------- Attributes ---------------------------------------------------------- */ /* ---------------------------------------- Constants ----------------------------------------------------------- */ /* ---------------------------------------- Constructors -------------------------------------------------------- */ /* ---------------------------------------- Methods ------------------------------------------------------------- */ public Grid() { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource( "/fxml/grid.fxml")); fxmlLoader.setRoot(this); fxmlLoader.setController(this); try { fxmlLoader.load(); } catch (IOException exception) { throw new RuntimeException(exception); } } public void initialize(URL location, ResourceBundle resources) { btnSearch.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { layoutCenterGrid.getChildren().clear(); String search = txtSearch.getText(); MovieFachklasse f = new MovieFachklasse(); LinkedList<MovieDBBasic> hp = f.getResults(search); GUITools.listToGrid(hp,Grid.this); } }); } public void addToGrid(Node node, int column, int row){ layoutCenterGrid.add(node, column,row); } public GridPane getGridPane(){ return layoutCenterGrid; } /* ---------------------------------------- S/Getters ----------------------------------------------------------- */ }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.math.BigDecimal; import java.util.Date; /** * PProblemfeedback generated by hbm2java */ public class PProblemfeedback implements java.io.Serializable { private BigDecimal uniqueid; private String pdeptid; private String pemployeeid; private Date ptime; private Date demandfbtime; private String ptopic; private String pcontent; private String dutydeptid; private String dutyemployeeid; private String fbresult; private String fbemployeeid; private Date fbtime; private String attachid; private Long fbstate; private String fbtype; public PProblemfeedback() { } public PProblemfeedback(BigDecimal uniqueid) { this.uniqueid = uniqueid; } public PProblemfeedback(BigDecimal uniqueid, String pdeptid, String pemployeeid, Date ptime, Date demandfbtime, String ptopic, String pcontent, String dutydeptid, String dutyemployeeid, String fbresult, String fbemployeeid, Date fbtime, String attachid, Long fbstate, String fbtype) { this.uniqueid = uniqueid; this.pdeptid = pdeptid; this.pemployeeid = pemployeeid; this.ptime = ptime; this.demandfbtime = demandfbtime; this.ptopic = ptopic; this.pcontent = pcontent; this.dutydeptid = dutydeptid; this.dutyemployeeid = dutyemployeeid; this.fbresult = fbresult; this.fbemployeeid = fbemployeeid; this.fbtime = fbtime; this.attachid = attachid; this.fbstate = fbstate; this.fbtype = fbtype; } public BigDecimal getUniqueid() { return this.uniqueid; } public void setUniqueid(BigDecimal uniqueid) { this.uniqueid = uniqueid; } public String getPdeptid() { return this.pdeptid; } public void setPdeptid(String pdeptid) { this.pdeptid = pdeptid; } public String getPemployeeid() { return this.pemployeeid; } public void setPemployeeid(String pemployeeid) { this.pemployeeid = pemployeeid; } public Date getPtime() { return this.ptime; } public void setPtime(Date ptime) { this.ptime = ptime; } public Date getDemandfbtime() { return this.demandfbtime; } public void setDemandfbtime(Date demandfbtime) { this.demandfbtime = demandfbtime; } public String getPtopic() { return this.ptopic; } public void setPtopic(String ptopic) { this.ptopic = ptopic; } public String getPcontent() { return this.pcontent; } public void setPcontent(String pcontent) { this.pcontent = pcontent; } public String getDutydeptid() { return this.dutydeptid; } public void setDutydeptid(String dutydeptid) { this.dutydeptid = dutydeptid; } public String getDutyemployeeid() { return this.dutyemployeeid; } public void setDutyemployeeid(String dutyemployeeid) { this.dutyemployeeid = dutyemployeeid; } public String getFbresult() { return this.fbresult; } public void setFbresult(String fbresult) { this.fbresult = fbresult; } public String getFbemployeeid() { return this.fbemployeeid; } public void setFbemployeeid(String fbemployeeid) { this.fbemployeeid = fbemployeeid; } public Date getFbtime() { return this.fbtime; } public void setFbtime(Date fbtime) { this.fbtime = fbtime; } public String getAttachid() { return this.attachid; } public void setAttachid(String attachid) { this.attachid = attachid; } public Long getFbstate() { return this.fbstate; } public void setFbstate(Long fbstate) { this.fbstate = fbstate; } public String getFbtype() { return this.fbtype; } public void setFbtype(String fbtype) { this.fbtype = fbtype; } }
// assignment 10 // pair p134 // Singh, Bhavneet // singhb // Wang, Shiyu // shiyu /** <code>Word</code> represents a word and its number of occurrences */ public class Word { /*TEMPLATE * Fields * this.s.... -- String * this.freq.... -- int * * Methods * this.equals(Object)... --boolean * this.hashCode()..... --int * this.toString()..... --String * this.increment().... --void * * Methods for fields * this.s.equals(Object).... -- boolean * this.s.hashCode()..... -- int * * */ String s; int freq; public Word(String s) { this.s = s; this.freq = 1; } /** Is this Word equal to the given Object */ public boolean equals(Object obj) { if (obj == null) return false; else { Word word1 = (Word)obj; return this.s.equals(word1.s); } } /** Produce this Word's hashCode */ public int hashCode() { return this.s.hashCode(); } /** Produce a String representation of this Word */ public String toString() { return this.s + this.freq; } // Increment this word's frequency public void increment() { this.freq = this.freq + 1; } }
package org.rebioma.client; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodeEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DeferredCommand; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.MultiWordSuggestOracle; import com.google.gwt.user.client.ui.SuggestBox; import com.google.gwt.user.client.ui.SuggestOracle.Callback; import com.google.gwt.user.client.ui.SuggestOracle.Request; import com.google.gwt.user.client.ui.SuggestOracle.Response; import com.google.gwt.user.client.ui.SuggestOracle.Suggestion; /** * A {@link SuggestBox} wrapper to limit the user input key to available term * only. * * @author Tri * */ public class SearchFieldSuggestion extends Composite implements SelectionHandler<Suggestion>, KeyDownHandler, ClickHandler, KeyUpHandler { /** * A listener is used to notified a term is selected. * * @author Tri * */ public interface TermSelectionListener { void onTermSelected(String term); } private final SuggestBox suggestionBox; private final MultiWordSuggestOracle suggestOracle; private final List<TermSelectionListener> termSelectionListeners = new ArrayList<TermSelectionListener>(); public SearchFieldSuggestion() { suggestOracle = new MultiWordSuggestOracle(); suggestionBox = new SuggestBox(suggestOracle); suggestionBox.addSelectionHandler(this); suggestionBox.addKeyDownHandler(this); suggestionBox.getTextBox().addClickHandler(this); suggestionBox.addKeyUpHandler(this); suggestionBox.setWidth("200px"); initWidget(suggestionBox); suggestionBox.setStyleName("SearchSuggestion"); suggestionBox.setPopupStyleName("gwt-SuggestBoxPopup SuggestFields"); } public void addSearchTerm(String terms) { suggestOracle.add(terms); } public void addSearchTerms(Collection<String> term) { suggestOracle.addAll(term); } public void addTermSelectionListener(TermSelectionListener e) { termSelectionListeners.add(e); } public void onClick(ClickEvent event) { // suggestionBox.setText(""); } /** * Cancel the current key if it the current words + current key don't get any * suggestion. */ public void onKeyDown(KeyDownEvent event) { int keyCode = event.getNativeKeyCode(); // no need to look ahead one step of suggestion phase if the key is // backspace, arrow, or any modifier key. if (isSpecialKeys(event)) { return; } suggestOracle.requestSuggestions(new Request(suggestionBox.getText() + (char) keyCode), new Callback() { public void onSuggestionsReady(Request request, Response response) { int size = response.getSuggestions().size(); if (size == 0) { suggestionBox.getTextBox().cancelKey(); } } }); } public void onKeyUp(KeyUpEvent event) { int keyCode = event.getNativeKeyCode(); // no need to check for possible suggestion phases if the key is // backspace, arrow, or any modifier key. if (isSpecialKeys(event)) { return; } suggestOracle.requestSuggestions(new Request(suggestionBox.getText()), new Callback() { public void onSuggestionsReady(Request request, Response response) { Collection<Suggestion> suggestions = (Collection<Suggestion>) response .getSuggestions(); int size = suggestions.size(); if (size == 1) { suggestionBox.setText(suggestions.iterator().next() .getReplacementString()); } } }); } public void onSelection(SelectionEvent<Suggestion> event) { for (TermSelectionListener listener : termSelectionListeners) { listener.onTermSelected(event.getSelectedItem().getReplacementString()); } suggestionBox.setText(""); Scheduler.get().scheduleDeferred(new ScheduledCommand(){ public void execute() { suggestionBox.hideSuggestionList(); } }); } public void setDeafaultSuggestions(Collection<String> terms) { suggestOracle.setDefaultSuggestionsFromText(terms); } private boolean isSpecialKeys(KeyCodeEvent event) { int keyCode = event.getNativeKeyCode(); return keyCode == KeyCodes.KEY_BACKSPACE || KeyCodeEvent.isArrow(keyCode) || event.isAnyModifierKeyDown() || keyCode == KeyCodes.KEY_ENTER || keyCode == KeyCodes.KEY_TAB || keyCode == KeyCodes.KEY_ESCAPE; } }
package leecode.dfs; import java.util.*; public class 二叉树的序列化与反序列化_297 { // Encodes a tree to a single string. //一个函数进行序列化 不知道算不算先序 // 选择前序遍历,是因为 根|左|右根∣左∣右 的打印顺序,在反序列化时更容易定位出根节点的值。 //https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/solution/shou-hui-tu-jie-gei-chu-dfshe-bfsliang-chong-jie-f/ public static String serialize(TreeNode root) { if (root == null) { return "null,";//不是 return null } String left = serialize(root.left); String right = serialize(root.right); return root.val + "," + left + right; //不是这样写 root+","+left+","+right; 返回的left right里面已经有 , } public StringBuilder helperSer(TreeNode root, StringBuilder str) { if (root == null) { str.append("null,"); return str; } str.append(root.val); str.append(","); str = helperSer(root.left, str); str = helperSer(root.right, str); return str; } // Decodes your encoded data to tree. public static TreeNode deserialize(String data) { String[] str = data.split(","); Queue<String> list = new ArrayDeque<>(); for (int i = 0; i < str.length; i++) { list.add(str[i]); } return deserHelp(list); } public static TreeNode deserHelp(Queue<String> str) { // String cur = str.get(0);//这个不对 如果List 为空,那么这儿就会报错 String cur = str.poll(); //str应该改成队列的形式 这样即使队列为空 poll也不会报错 if (cur.equals("null")) { // str.remove(0);//改成队列 就不需要 remove return null; } TreeNode node = new TreeNode(Integer.valueOf(cur)); // str.remove(0); node.left = deserHelp(str); node.right = deserHelp(str); return node; } //通过bfs 进行序列化和反序列化 public static String serialize2(TreeNode root) { Queue<TreeNode> queue=new LinkedList<>(); queue.add(root); String res=new String(); while (!queue.isEmpty()){ TreeNode cur=queue.poll(); if(cur!=null){ res=res+cur.val+","; queue.add(cur.left); queue.add(cur.right); }else {//注意这里 res=res+"null,"; } } return res; } //通过bfs 反序列化 public TreeNode deserialize2(String data) { String[]values=data.substring(0,data.length()-1).split(","); Queue<TreeNode>queue=new LinkedList<>(); TreeNode root=new TreeNode(Integer.parseInt(values[0])); //这个cur的作用可以看这个题解画的图 //https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/solution/shou-hui-tu-jie-gei-chu-dfshe-bfsliang-chong-jie-f/ int cur=1; queue.add(root); while (!queue.isEmpty()){ TreeNode curNode=queue.poll(); String left=values[cur]; if(!left.equals("null")){ curNode.left=new TreeNode(Integer.parseInt(left)); queue.offer(curNode.left); } cur++; String right=values[cur]; if(!right.equals("null")){ curNode.right=new TreeNode(Integer.parseInt(right)); queue.offer(curNode.right); } cur++; } return root; } public static void main(String[] args) { // TreeNode root=new TreeNode(1); // root.left=new TreeNode(2); // root.right=new TreeNode(3); // System.out.println(serialize2(root)); // System.out.println(serialize(root)); String str="1,2,3"; deserialize(str); } }
class Solution { public int[] sortArrayByParity(int[] A) { int[] result = new int[A.length]; int resultIndex = 0; for(int i=0;i<A.length;i++){ if(A[i] % 2 == 0) result[resultIndex++] = A[i]; } for(int i=0;i<A.length;i++){ if(A[i] % 2 == 1) result[resultIndex++] = A[i]; } return result; } }
package am.data.hibernate.model.lookup; import am.data.hibernate.model.apps.RegisteredApplication; import javax.persistence.*; /** * Created by ahmed.motair on 1/13/2018. */ @Entity @Table(name="system_address") public class SystemAddress { public static final String TYPE = "type." + NotificationType.TYPE; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "address_id") private Integer addressID; @ManyToOne @JoinColumn(name = "ntf_type", referencedColumnName = "ntf_type") private NotificationType type; @ManyToOne @JoinColumn(name = "app_id", referencedColumnName = "app_id") private RegisteredApplication application; @Basic @Column(name = "address") private String address; @Basic @Column(name = "address_password") private String password; public SystemAddress() { } public SystemAddress(NotificationType type, String address) { this.type = type; this.address = address; } public Integer getAddressID() { return addressID; } public void setAddressID(Integer addressID) { this.addressID = addressID; } public NotificationType getType() { return type; } public void setType(NotificationType type) { this.type = type; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public RegisteredApplication getApplication() { return application; } public void setApplication(RegisteredApplication application) { this.application = application; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof SystemAddress)) return false; SystemAddress that = (SystemAddress) o; return getAddressID() != null ? getAddressID().equals(that.getAddressID()) : that.getAddressID() == null; } @Override public int hashCode() { return getAddressID() != null ? getAddressID().hashCode() : 0; } @Override public String toString() { return "SystemAddress{" + "addressID = " + addressID + ", type = " + type + ", address = " + address + "}\n"; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pasosServer.model; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Juan Antonio */ @Entity @Table(name = "CONTACTO") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Contacto.findAll", query = "SELECT c FROM Contacto c"), @NamedQuery(name = "Contacto.findByTelefonoContacto", query = "SELECT c FROM Contacto c WHERE c.telefonoContacto = :telefonoContacto"), @NamedQuery(name = "Contacto.findByNombre", query = "SELECT c FROM Contacto c WHERE c.nombre = :nombre"), @NamedQuery(name = "Contacto.findByEmail", query = "SELECT c FROM Contacto c WHERE c.email = :email"), @NamedQuery(name = "Contacto.findByIdContacto", query = "SELECT c FROM Contacto c WHERE c.idContacto = :idContacto")}) public class Contacto implements Serializable { private static final long serialVersionUID = 1L; @Column(name = "TELEFONO_CONTACTO") private BigInteger telefonoContacto; @Size(max = 20) @Column(name = "NOMBRE") private String nombre; // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation @Size(max = 30) @Column(name = "EMAIL") private String email; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Id @Basic(optional = false) @NotNull @Column(name = "ID_CONTACTO") private BigDecimal idContacto; @JoinColumn(name = "ID_PROTEGIDO", referencedColumnName = "ID_PROTEGIDO") @ManyToOne private Protegido idProtegido; public Contacto() { } public Contacto(BigDecimal idContacto) { this.idContacto = idContacto; } public BigInteger getTelefonoContacto() { return telefonoContacto; } public void setTelefonoContacto(BigInteger telefonoContacto) { this.telefonoContacto = telefonoContacto; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public BigDecimal getIdContacto() { return idContacto; } public void setIdContacto(BigDecimal idContacto) { this.idContacto = idContacto; } public Protegido getIdProtegido() { return idProtegido; } public void setIdProtegido(Protegido idProtegido) { this.idProtegido = idProtegido; } @Override public int hashCode() { int hash = 0; hash += (idContacto != null ? idContacto.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Contacto)) { return false; } Contacto other = (Contacto) object; if ((this.idContacto == null && other.idContacto != null) || (this.idContacto != null && !this.idContacto.equals(other.idContacto))) { return false; } return true; } @Override public String toString() { return "pasosServer.model.Contacto[ idContacto=" + idContacto + " ]"; } }
package com.jincarry.request; /** * Created by jincarry on 16-9-21. */ public class HttpResult { public int code; public String body; public HttpResult(int code,String body){ this.code = code; this.body = body; } public HttpResult(){} }
package pt.mleiria.mlalgo.functions; import junit.framework.TestCase; public class LogFunctionTest extends TestCase { public void testLogFunction() { Double[] z = new Double[]{1., 3.25, 5.5, 7.75, 10.}; OneVarFunction<Double[], Double[]> log = new LogFunction(); Double[] res = log.value(z); assertEquals(0., res[0]); assertEquals(1.1786549963416462, res[1]); assertEquals(z.length, res.length); } }
public class TictactoeScore extends GameScore { @Override public void score(int tries) { totalScore = totalScore - (tries * 100); } }
package maedit; import java.awt.Dimension; import javax.swing.JEditorPane; import javax.swing.JScrollPane; public class HtmlPane { JEditorPane editorPane; JScrollPane scrollPane; public HtmlPane() { editorPane = new JEditorPane(); editorPane.setEditable(false); editorPane.setContentType("text/html"); scrollPane = new JScrollPane(editorPane); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); scrollPane.setMinimumSize(new Dimension(320, 200)); } public JScrollPane getScrollPane() { return scrollPane; } public JEditorPane getTextTarget() { return editorPane; } public void show() { scrollPane.setVisible(true); } public void hide() { scrollPane.setVisible(false); } }
/* * 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 be.livingsmart.eindwerk; import be.livingsmart.hdr.Shift; import be.livingsmart.hdr.ShiftItem; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigDecimal; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.util.*; import javax.mail.*; import javax.mail.internet.*; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessagePreparator; /** * This class creates excel (.xlsx) files and sends an email to the specified email address * @author Pieter */ public class ExcelWriter { /** * Given a {@link Shift} an excel file gets made. Date, start time, end time and then all the sold products gets listed (amounts + price per product + total prices), followed by a total of all the prices of all the products that got sold. Then it calls a private method that sends this file to a specified (hardcoded) email address. * @param shift This is the {@link Shift} where data gets pulled from. * @throws FileNotFoundException When the file was not found * @throws IOException When a file couldn't be saved */ public void shiftReport(Shift shift) throws FileNotFoundException, IOException, IOException { String fileName = "Verslag: " + shift.getCurrentDate() + ".xlsx" ;//+ " " + shift.getStartTime() + ", " + shift.getEndTime(); System.out.println(fileName); System.out.println(shift.getStartTime()); XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("Shift"); ArrayList<ArrayList<String>> sheetString = new ArrayList<ArrayList<String>>(); for (int i = 0; i <= 7; i++) { sheetString.add(new ArrayList<String>()); } sheetString.get(0).add("Datum: "); sheetString.get(0).add(""); sheetString.get(0).add("" + shift.getCurrentDate()); sheetString.get(1).add("Start shift: "); sheetString.get(1).add(""); sheetString.get(1).add("" + shift.getStartTime()); sheetString.get(2).add("Einde shift: "); sheetString.get(2).add(""); sheetString.get(2).add("" + shift.getEndTime()); sheetString.get(3).add("Supervisor: "); sheetString.get(3).add(""); sheetString.get(3).add("" + shift.getSupervisor().getName()); sheetString.get(4).add(""); sheetString.get(5).add("Product: "); sheetString.get(5).add("Aantal verkocht: "); sheetString.get(5).add("Prijs per product"); sheetString.get(5).add("Totale prijs"); int i = 6; double total = 0; for (Map.Entry<Long, ShiftItem> entry : shift.getShiftItems().entrySet()) { sheetString.add(new ArrayList<String>()); sheetString.get(i).add(entry.getValue().getItem().getName()); sheetString.get(i).add("" + entry.getValue().getAmount()); sheetString.get(i).add("" + entry.getValue().getItem().getPrice()); double productTotal = entry.getValue().getItem().getPrice() * entry.getValue().getAmount(); sheetString.get(i).add("" + productTotal); total += productTotal; i++; } sheetString.get(i+1).add("Totale prijs: "); sheetString.get(i+1).add(""); sheetString.get(i+1).add(""); sheetString.get(i+1).add("" + total); int rowNum = 0; System.out.println("Creating excel"); for (ArrayList list : sheetString) { Row row = sheet.createRow(rowNum++); int colNum = 0; for (Object field : list) { Cell cell = row.createCell(colNum++); if (field instanceof String) { cell.setCellValue((String) field); } else if (field instanceof Integer) { cell.setCellValue((Integer) field); } } } try { File file = new File(fileName); file.createNewFile(); FileOutputStream outputStream = new FileOutputStream(file); workbook.write(outputStream); workbook.close(); sendEmail(file); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Done"); } private void sendEmail(final File file) { String hdr = "HDRPointOfSale@gmail.com"; JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); //Using gmail mailSender.setHost("smtp.gmail.com"); mailSender.setPort(587); mailSender.setUsername(hdr); mailSender.setPassword("PointOfSale2018"); Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.starttls.enable", "true"); javaMailProperties.put("mail.smtp.auth", "true"); javaMailProperties.put("mail.transport.protocol", "smtp"); javaMailProperties.put("mail.debug", "true");//Prints out everything on screen mailSender.setJavaMailProperties(javaMailProperties); MimeMessagePreparator preparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage message) throws Exception { String email = "HDRPointOfSale@gmail.com"; message.setFrom(new InternetAddress("HDRPointOfSale@gmail.com", "Kassa app")); message.setRecipient(Message.RecipientType.TO, new InternetAddress(email)); message.setText("Het shift report zit in de bijlage"); message.setSubject("Shift report"); Multipart multipart = new MimeMultipart(); // creates body part for the message // creates body part for the attachment MimeBodyPart attachPart = new MimeBodyPart(); attachPart.attachFile(file); // code to add attachment...will be revealed later // adds parts to the multiparts multipart.addBodyPart(attachPart); // sets the multipart as message's content message.setContent(multipart); } }; try { mailSender.send(preparator); System.out.println("Message Send...Hurrey"); } catch (MailException ex) { System.err.println(ex.getMessage()); } } }
package de.rwth.i9.palm.persistence; /** * This interface is a Factory-interface for any DAO that is needed in this * application. */ public interface PersistenceStrategy { public AuthorDAO getAuthorDAO(); public AuthorInterestDAO getAuthorInterestDAO(); public AuthorInterestProfileDAO getAuthorInterestProfileDAO(); public AuthorSourceDAO getAuthorSourceDAO(); public AuthorTopicModelingDAO getAuthorTopicModelingDAO(); public AuthorTopicModelingProfileDAO getAuthorTopicModelingProfileDAO(); public CircleDAO getCircleDAO(); public CircleInterestDAO getCircleInterestDAO(); public CircleInterestProfileDAO getCircleInterestProfileDAO(); public CircleTopicModelingDAO getCircleTopicModelingDAO(); public CircleTopicModelingProfileDAO getCircleTopicModelingProfileDAO(); public CircleWidgetDAO getCircleWidgetDAO(); public ConfigDAO getConfigDAO(); public ConfigPropertyDAO getConfigPropertyDAO(); public CountryDAO getCountryDAO(); public EventDAO getEventDAO(); public EventInterestDAO getEventInterestDAO(); public EventInterestProfileDAO getEventInterestProfileDAO(); public EventGroupDAO getEventGroupDAO(); public ExtractionServiceDAO getExtractionServiceDAO(); public ExtractionServicePropertyDAO getExtractionServicePropertyDAO(); public FunctionDAO getFunctionDAO(); public InstitutionDAO getInstitutionDAO(); public InterestDAO getInterestDAO(); public InterestProfileDAO getInterestProfileDAO(); public InterestProfileCircleDAO getInterestProfileCircleDAO(); public InterestProfileEventDAO getInterestProfileEventDAO(); public InterestProfilePropertyDAO getInterestProfilePropertyDAO(); public LocationDAO getLocationDAO(); public PublicationDAO getPublicationDAO(); public PublicationAuthorDAO getPublicationAuthorDAO(); public PublicationFileDAO getPublicationFileDAO(); public PublicationHistoryDAO getPublicationHistoryDAO(); public PublicationSourceDAO getPublicationSourceDAO(); public PublicationTopicDAO getPublicationTopicDAO(); public RoleDAO getRoleDAO(); public SessionDataSetDAO getSessionDataSetDAO(); public SourceDAO getSourceDAO(); public SourcePropertyDAO getSourcePropertyDAO(); public SubjectDAO getSubjectDAO(); public UserAuthorBookmarkDAO getUserAuthorBookmarkDAO(); public UserDAO getUserDAO(); public UserCircleBookmarkDAO getUserCircleBookmarkDAO(); public UserEventGroupBookmarkDAO getUserEventGroupBookmarkDAO(); public UserPublicationBookmarkDAO getUserPublicationBookmarkDAO(); public UserRequestDAO getUserRequestDAO(); public UserWidgetDAO getUserWidgetDAO(); public TopicModelingAlgorithmAuthorDAO getTopicModelingAlgorithmAuthorDAO(); public TopicModelingAlgorithmCircleDAO getTopicModelingAlgorithmCircleDAO(); public WidgetDAO getWidgetDAO(); }
package com.hcp.objective.schedule; import org.quartz.DisallowConcurrentExecution; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.PersistJobDataAfterExecution; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.quartz.QuartzJobBean; @PersistJobDataAfterExecution @DisallowConcurrentExecution public class MyJobTwo extends QuartzJobBean { public static final Logger logger = LoggerFactory.getLogger(MyJobTwo.class); protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException { logger.error("======"+System.currentTimeMillis()); } }
package com.classcheck.panel; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JTabbedPane; public class Class_Sequence_ImageTabbedPanel extends JTabbedPane { private JFrame window; File root; private ArrayList<String> classDiagramNameList; public Class_Sequence_ImageTabbedPanel(JFrame window, String exportPath, ArrayList<String> classDiagramNameList) { root = new File(exportPath); this.window = window; this.classDiagramNameList = classDiagramNameList; initComponent(); } private void initComponent() { List<Class_Sequence_ImageTab> tabPaneList = new ArrayList<Class_Sequence_ImageTab>(); File[] files = root.listFiles(); String fileName,classDiagramName; Pattern pattern = Pattern.compile("(.+)\\.(png)$"); Matcher matcher; ImageIcon classIcon = new ImageIcon(getClass().getResource("/icons/class_image.png")); ImageIcon sequenceIcon = new ImageIcon(getClass().getResource("/icons/sequence_image.png")); for (File file : files) { fileName = file.getName(); matcher = pattern.matcher(fileName); System.out.println("fileName:"+fileName); if (matcher.find()) { classDiagramName = matcher.group(1); tabPaneList.add(new Class_Sequence_ImageTab(classDiagramName,file)); } } int tabCount = 0; final int firstTab = 0; for (Class_Sequence_ImageTab tabPanel : tabPaneList) { //もじクラス図の場合はクラス図のアイコンを使う if (this.classDiagramNameList.contains(tabPanel.getClassDiagramName())) { addTab(tabPanel.getClassDiagramName(), classIcon, tabPanel, null); tabPanel.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent e) { super.componentShown(e); window.setTitle("クラス図"); } }); if (tabCount == firstTab) { window.setTitle("クラス図"); } //それ以外はシーケンス図のアイコンを使う }else{ addTab(tabPanel.getClassDiagramName(), sequenceIcon, tabPanel, null); tabPanel.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent e) { super.componentShown(e); window.setTitle("シーケンス図"); } }); if (tabCount == firstTab) { window.setTitle("シーケンス図"); } } tabCount++; } } }
package org.alienideology.jcord.event.channel.dm; import org.alienideology.jcord.handle.channel.IPrivateChannel; /** * @author AlienIdeology */ public interface IPrivateChannelEvent { IPrivateChannel getPrivateChannel(); }
package com.duofei.controller; import com.duofei.config.ConfigPro; import com.duofei.event.NotifyRemoteApplicationEvent; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.configurationprocessor.json.JSONObject; import org.springframework.cloud.bus.BusProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author duofei * @date 2019/10/18 */ @RefreshScope @RestController public class TestController { @Autowired private AmqpTemplate amqpTemplate; @Autowired private ConfigPro configPro; @Autowired private ApplicationContext applicationContext; @Autowired private BusProperties busProperties; @Value("${from}") private String from; @RequestMapping("/from") public String from() { return this.from; } @GetMapping("/send") public void send(@RequestParam String msg){ amqpTemplate.convertAndSend("exchange", "routingKey", msg); } @GetMapping("/pro") public String pro(){ return configPro.getPro(); } @GetMapping("/notify") public void notifyOthers(@RequestParam String msg) throws Exception{ applicationContext.publishEvent(new NotifyRemoteApplicationEvent(msg, new Object() , busProperties.getId())); } }
package com.paytechnologies.cloudacar; import com.sromku.simple.fb.entities.Feed; import com.viewpagerindicator.CirclePageIndicator; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager.LayoutParams; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import android.widget.ImageView.ScaleType; public class Features extends Activity{ private static final int MAX_PAGES = 10; private int num_pages = 6; CirclePageIndicator mIndicator; String fromIntent; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main_features); Intent i= getIntent(); fromIntent =i.getStringExtra("fromIntent"); final ViewPagerParallax pager = (ViewPagerParallax) findViewById(R.id.pager2); pager.set_max_pages(MAX_PAGES); pager.setBackgroundAsset(R.drawable.bg); pager.setAdapter(new my_adapter()); mIndicator = (CirclePageIndicator)findViewById(R.id.indicator2); mIndicator.setViewPager(pager); if (savedInstanceState!=null) { num_pages = savedInstanceState.getInt("num_pages"); pager.setCurrentItem(savedInstanceState.getInt("current_page"), false); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("num_pages", num_pages); final ViewPagerParallax pager = (ViewPagerParallax) findViewById(R.id.pager); outState.putInt("current_page", pager.getCurrentItem()); } private class my_adapter extends PagerAdapter { @Override public int getCount() { return num_pages; } @Override public boolean isViewFromObject(View view, Object o) { return view == o; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View)object); } @Override public Object instantiateItem(ViewGroup container, int position) { View new_view=null; LayoutInflater inflater = getLayoutInflater(); new_view = inflater.inflate(R.layout.page_features, null); ImageView num = (ImageView) new_view.findViewById(R.id.imageViewParallex2); // Button next = (Button)new_view.findViewById(R.id.buttonNext); // TextView desc = (TextView)new_view.findViewById(R.id.textViewParallex2); // TextView title = (TextView)new_view.findViewById(R.id.textViewParallexTitle2); // Typeface roboto = Typeface.createFromAsset(getApplicationContext().getAssets(), "Roboto-Light.ttf"); // // // title.setTypeface(roboto); // desc.setTypeface(roboto); FrameLayout.LayoutParams Params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); if(position==0){ num.setScaleType(ScaleType.FIT_XY); num.setImageResource(R.drawable.secure_reliable); //desc.setText("Only pre-verified users \n Stringent Verification Process \n Rules for reliable user behavior "); // title.setText("Secure and Reliable"); // next.setVisibility(View.INVISIBLE); } if(position==1){ num.setScaleType(ScaleType.FIT_XY); num.setImageResource(R.drawable.smart_matchin); // desc.setText("Number Of Preferences To Get The Best Match"); // title.setText("Smart Ride Matching Engine"); } if(position==2){ num.setScaleType(ScaleType.FIT_XY); num.setImageResource(R.drawable.integrated); // desc.setText("24 X7 Call Center \n Interactive Mobile App \n Web"); // title.setText("Integrated for convinience"); } if(position==3){ num.setScaleType(ScaleType.FIT_XY); num.setImageResource(R.drawable.easy_payments); // desc.setText("Pay Online To Subscribe Service \n Pay Trip Charges In Car \n No Deposits With CAC"); // title.setText("Easy Payments"); } if(position==4){ num.setScaleType(ScaleType.FIT_XY); num.setImageResource(R.drawable.regulated); // desc.setText("CAC Rules Of Use For Commuter \n Ratings & Penalties For Non Compliance \n Prefixed Trip Costs"); // title.setText("Regualted Platform"); } if(position==5){ num.setScaleType(ScaleType.FIT_XY); num.setImageResource(R.drawable.intelligent_reporting); // desc.setText("Track your savings \n Track your Trips"); // title.setText("Intelligent Reporting"); } // next.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // // TODO Auto-generated method stub // // Intent splash_activity = new Intent(Features.this,Login.class); // startActivity(splash_activity); // } // }); container.addView(new_view); return new_view; } } @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); if(fromIntent!=null){ if(fromIntent.equalsIgnoreCase("login")){ Intent login = new Intent(Features.this,Login.class); startActivity(login); }else if(fromIntent.equalsIgnoreCase("profile")){ Intent login = new Intent(Features.this,Profile.class); startActivity(login); }else if(fromIntent.equalsIgnoreCase("bookTrip")){ Intent login = new Intent(Features.this,BookTrip.class); startActivity(login); }else if(fromIntent.equalsIgnoreCase("tripsDashboard")){ Intent login = new Intent(Features.this,TripsDashboard.class); startActivity(login); }else if(fromIntent.equalsIgnoreCase("dashboard")){ Intent login = new Intent(Features.this,DashBoard.class); startActivity(login); }else if(fromIntent.equalsIgnoreCase("manageTrip")){ Intent login = new Intent(Features.this,ManageTrip.class); startActivity(login); }else if(fromIntent.equalsIgnoreCase("callTobook")){ Intent callToBook = new Intent(Features.this,CallToBook.class); startActivity(callToBook); }else if(fromIntent.equalsIgnoreCase("registration")){ Intent resgistration = new Intent(Features.this,Registration.class); startActivity(resgistration); }else if(fromIntent.equalsIgnoreCase("newProfile")){ Intent newProfile = new Intent(Features.this,NewProfile.class); startActivity(newProfile); }else if(fromIntent.equalsIgnoreCase("prof")){ Intent newProfile = new Intent(Features.this,ProfessionalInformation.class); startActivity(newProfile); }else if(fromIntent.equalsIgnoreCase("travel")){ Intent Prof = new Intent(Features.this,TravelPrefences.class); startActivity(Prof); }else if(fromIntent.equalsIgnoreCase("registration")){ Intent Prof = new Intent(Features.this,Registration.class); startActivity(Prof); }else if(fromIntent.equalsIgnoreCase("docAddress")){ Intent Prof = new Intent(Features.this,Submit_document_address.class); startActivity(Prof); }else if(fromIntent.equalsIgnoreCase("docIndentity")){ Intent Prof = new Intent(Features.this,Submit_document_identity.class); startActivity(Prof); }else if(fromIntent.equalsIgnoreCase("docVehicle")){ Intent Prof = new Intent(Features.this,Submit_document_vehicle.class); startActivity(Prof); }else if(fromIntent.equalsIgnoreCase("cacPlans")){ Intent Prof = new Intent(Features.this,NewModifiedCacPlans.class); startActivity(Prof); } }else{ Intent login = new Intent(Features.this,Login.class); startActivity(login); } } }
package cq.InnerClass; //外部类 public class CreateInnerClass { //内部类 class Contents{ private int i = 11; public int value() { return i; } } class Destination{ //CreateInnerClass createInnerClass = CreateInnerClass.this; private String label; public Destination(String whereTo) { label = whereTo; } String readLable() { return label; } } public void ship(String dest) { Destination destination = new Destination(dest); System.out.println(destination.readLable()); } //外部类方法返回值 指向内部类 public Destination toInner(String s) { return new Destination(s); } public static void main(String[] args) { CreateInnerClass createInnerClass = new CreateInnerClass(); createInnerClass.ship("a"); Destination destination = createInnerClass.toInner("toinner"); System.out.println(destination); //创建内部类对象 Destination destination2 = new CreateInnerClass().new Destination("a"); } }
package com.gmail.khanhit100896.foody.main; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.gmail.khanhit100896.foody.R; public class SplashScreenActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); startAnimation(); } private void startAnimation() { Thread mThread = new Thread() { @Override public void run() { super.run(); int waited = 0; while (waited < 4500) { try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } waited += 100; } SplashScreenActivity.this.finish(); Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent); } }; mThread.start(); } }
package com.fnsvalue.skillshare.mapper; import java.util.ArrayList; import java.util.HashMap; import org.apache.ibatis.annotations.Param; public interface QuestionMapper { int QuestionAdd(@Param("user_tb_user_id_pk")String USER_TB_USER_ID_PK, @Param("ask_tit")String ASK_TIT,@Param("ask_con") String ASK_CON); ArrayList<HashMap> QuestionView(@Param("page_start")int PAGE_START,@Param("perpage_num")int PERPAGE_NUM); ArrayList<HashMap> QuestionDetailView(int ASK_NO_PK); int countPaging(); int QuestionDelete(int ASK_NO_PK); int QuestionChange(@Param("ask_no_pk")int ASK_NO_PK, @Param("ask_tit")String ASK_TIT, @Param("ask_con")String ASK_CON); ArrayList<HashMap> dashboardView(); int viewOk(String USER_TB_USER_ID_PK); }
package com.resolutech.services; //import com.resolutech.api.v1.model.VendorDTO; import com.resolutech.model.VendorDTO; import org.springframework.stereotype.Service; import java.util.List; /** * */ @Service public interface VendorService { List<VendorDTO> getAll(); VendorDTO getVendorById(Long id); VendorDTO createVendor(VendorDTO vendor); VendorDTO saveVendorById(Long id, VendorDTO vendor); VendorDTO patchVendorById(Long id, VendorDTO vendor); void deleteVendorById(Long id); }
package com.stryksta.swtorcentral.ui.views.timeline; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathEffect; import android.util.AttributeSet; import android.view.View; import com.stryksta.swtorcentral.R; public class DashedVLineView extends View { private Paint mPaint; private Path mPath; protected PathEffect mEffects; private int mDashHeight = 26; private float mDashWidth = 20; private float mDashGap = 15; private int mDashColor = Color.rgb(117,117,117); public DashedVLineView(Context context) { super(context, null); init(); } public DashedVLineView(Context context, AttributeSet attrs) { super(context, attrs, 0); if(!isInEditMode()){ setAttributes(context, attrs); } init(); } public DashedVLineView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if(!isInEditMode()){ setAttributes(context, attrs); } init(); } private void setAttributes(Context context, AttributeSet attrs) { TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.dashedLineView); try { mDashWidth = array.getFloat(R.styleable.dashedLineView_dashWidth, mDashWidth); mDashGap = array.getFloat(R.styleable.dashedLineView_dashGap, mDashGap); mDashColor = array.getColor(R.styleable.dashedLineView_dashColor, mDashColor); } finally { array.recycle(); } } private void init() { mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(mDashHeight); mPaint.setColor(mDashColor); mPath = new Path(); mEffects = new DashPathEffect(new float[]{mDashWidth, mDashGap}, 0); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPaint.setPathEffect(mEffects); int top = getPaddingTop(); int bottom = getHeight() - getPaddingBottom(); int contentWidth = getWidth() - getPaddingLeft() - getPaddingRight(); int contentHeight = getHeight() - getPaddingTop() - getPaddingBottom(); //int startX = contentHeight - mDashHeight / 2; //int endX = contentHeight + mDashHeight / 2; mPath.moveTo(contentWidth / 2, top); mPath.lineTo(contentWidth / 2, bottom); canvas.drawPath(mPath, mPaint); //demo /* int height = getMeasuredHeight(); int width = getMeasuredWidth(); if (height <= width) { // horizontal mPath.moveTo(0, (float) (height / 2.0)); mPath.lineTo(width, (float) (height / 2.0)); canvas.drawPath(mPath, mPaint); } else { // vertical mPath.moveTo((float) (width / 2.0), 0); mPath.lineTo((float) (width / 2.0), height); canvas.drawPath(mPath, mPaint); } */ //canvas.drawLine(startX, startY, stopX, stopY, mPaint); //canvas.drawLine(left, contentHeight / 2, right, contentHeight / 2, mPaint); } }
package lab.ss5; import java.util.Scanner; public class Person { public String Ten; public String Gioitinh; public String ngaysinh; public String diachi; // constructor public Person(){ } public Person(String ten, String gioitinh,String ngaysinh, String diachi) { Ten = ten; Gioitinh = gioitinh; this.ngaysinh = ngaysinh; this.diachi = diachi; } //GETTER SETTER public String getTen() { return Ten; } public void setTen(String ten) { Ten = ten; } public String getGioitinh() { return Gioitinh; } public void setGioitinh(String gioitinh) { Gioitinh = gioitinh; } public String getNgaysinh() { return ngaysinh; } public void setNgaysinh(String ngaysinh) { this.ngaysinh = ngaysinh; } public String getDiachi() { return diachi; } public void setDiachi(String diachi) { this.diachi = diachi; } public void inputtt(){ Scanner sc = new Scanner(System.in); System.out.println("ho va ten: "); setTen(sc.nextLine()); System.out.println("gioi tinh: "); setGioitinh(sc.nextLine()); System.out.println("ngay sinh: "); setNgaysinh(sc.nextLine()); System.out.println("dia chi: "); setDiachi(sc.nextLine()); } public void printtt(){ System.out.println("tên: "+getTen()); System.out.println("giới tính: "+getGioitinh()); System.out.println("ngày sinh: "+getNgaysinh()); System.out.println("diachi: "+getDiachi()); } @Override public String toString() { return "Person{" + "Ten='" + Ten + '\'' + ", Gioitinh='" + Gioitinh + '\'' + ", ngaysinh='" + ngaysinh + '\'' + ", diachi='" + diachi + '\'' + '}'; } }
package com.mo.mohttp.executor; import com.mo.mohttp.Request; import com.mo.mohttp.Response; import com.mo.mohttp.anno.ThreadSafe; import java.io.IOException; import java.net.URISyntaxException; @ThreadSafe public interface Executor{ Response execute(Request request) throws IOException, URISyntaxException; }
package com.icleveret.recipes.viewmodel; import com.icleveret.recipes.model.User; public class UserViewInfo { private User user; private String changedEmail; private String changedPassword; public UserViewInfo() { } public UserViewInfo(User user, String changedEmail, String changedPassword) { this.user = user; this.changedEmail = changedEmail; this.changedPassword = changedPassword; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getChangedEmail() { return changedEmail; } public void setChangedEmail(String changedEmail) { this.changedEmail = changedEmail; } public String getChangedPassword() { return changedPassword; } public void setChangedPassword(String changedPassword) { this.changedPassword = changedPassword; } }
package com.example.pam2; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.fragment.app.Fragment; import android.os.Bundle; public class MainActivity extends AppCompatActivity { private FragmentManager fragMan; private Fragment f1, f2, f3, f4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); f1 = new f1(); f2 = new f2(); f3 = new f3(); f4 = new f4(); fragMan = getSupportFragmentManager(); FragmentTransaction trans = fragMan.beginTransaction(); trans.add(R.id.f1, f1); trans.add(R.id.f2, f2); trans.add(R.id.f3, f3); trans.add(R.id.f4, f4); trans.addToBackStack(null); trans.commit(); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.filecache; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; /** * Distribute application-specific large, read-only files efficiently. * * <p><code>DistributedCache</code> is a facility provided by the Map-Reduce * framework to cache files (text, archives, jars etc.) needed by applications. * </p> * * <p>Applications specify the files, via urls (hdfs:// or http://) to be cached * via the {@link org.apache.hadoop.mapred.JobConf}. The * <code>DistributedCache</code> assumes that the files specified via urls are * already present on the {@link FileSystem} at the path specified by the url * and are accessible by every machine in the cluster.</p> * * <p>The framework will copy the necessary files on to the slave node before * any tasks for the job are executed on that node. Its efficiency stems from * the fact that the files are only copied once per job and the ability to * cache archives which are un-archived on the slaves.</p> * * <p><code>DistributedCache</code> can be used to distribute simple, read-only * data/text files and/or more complex types such as archives, jars etc. * Archives (zip, tar and tgz/tar.gz files) are un-archived at the slave nodes. * Jars may be optionally added to the classpath of the tasks, a rudimentary * software distribution mechanism. Files have execution permissions. * Optionally users can also direct it to symlink the distributed cache file(s) * into the working directory of the task.</p> * * <p><code>DistributedCache</code> tracks modification timestamps of the cache * files. Clearly the cache files should not be modified by the application * or externally while the job is executing.</p> * * <p>Here is an illustrative example on how to use the * <code>DistributedCache</code>:</p> * <p><blockquote><pre> * // Setting up the cache for the application * * 1. Copy the requisite files to the <code>FileSystem</code>: * * $ bin/hadoop fs -copyFromLocal lookup.dat /myapp/lookup.dat * $ bin/hadoop fs -copyFromLocal map.zip /myapp/map.zip * $ bin/hadoop fs -copyFromLocal mylib.jar /myapp/mylib.jar * $ bin/hadoop fs -copyFromLocal mytar.tar /myapp/mytar.tar * $ bin/hadoop fs -copyFromLocal mytgz.tgz /myapp/mytgz.tgz * $ bin/hadoop fs -copyFromLocal mytargz.tar.gz /myapp/mytargz.tar.gz * * 2. Setup the application's <code>JobConf</code>: * * JobConf job = new JobConf(); * DistributedCache.addCacheFile(new URI("/myapp/lookup.dat#lookup.dat"), * job); * DistributedCache.addCacheArchive(new URI("/myapp/map.zip", job); * DistributedCache.addFileToClassPath(new Path("/myapp/mylib.jar"), job); * DistributedCache.addCacheArchive(new URI("/myapp/mytar.tar", job); * DistributedCache.addCacheArchive(new URI("/myapp/mytgz.tgz", job); * DistributedCache.addCacheArchive(new URI("/myapp/mytargz.tar.gz", job); * * 3. Use the cached files in the {@link org.apache.hadoop.mapred.Mapper} * or {@link org.apache.hadoop.mapred.Reducer}: * * public static class MapClass extends MapReduceBase * implements Mapper&lt;K, V, K, V&gt; { * * private Path[] localArchives; * private Path[] localFiles; * * public void configure(JobConf job) { * // Get the cached archives/files * localArchives = DistributedCache.getLocalCacheArchives(job); * localFiles = DistributedCache.getLocalCacheFiles(job); * } * * public void map(K key, V value, * OutputCollector&lt;K, V&gt; output, Reporter reporter) * throws IOException { * // Use data from the cached archives/files here * // ... * // ... * output.collect(k, v); * } * } * * </pre></blockquote></p> * * It is also very common to use the DistributedCache by using * {@link org.apache.hadoop.util.GenericOptionsParser}. * * This class includes methods that should be used by users * (specifically those mentioned in the example above, as well * as {@link DistributedCache#addArchiveToClassPath(Path, Configuration)}), * as well as methods intended for use by the MapReduce framework * (e.g., {@link org.apache.hadoop.mapred.JobClient}). * * @see org.apache.hadoop.mapred.JobConf * @see org.apache.hadoop.mapred.JobClient * @see org.apache.hadoop.mapreduce.Job * @deprecated Use methods on {@link Job}. */ @Deprecated @InterfaceAudience.Public @InterfaceStability.Stable public class DistributedCache extends org.apache.hadoop.mapreduce.filecache.DistributedCache { // }
package clientProfileApplication; import javafx.scene.Parent; import javafx.scene.Scene; public class ClientProfileScene extends Scene{ public ClientProfileScene(Parent root) { super(root , 1000.0 , 600.002); } }
package com.tencent.mm.plugin.appbrand.jsapi.op_report; import com.tencent.mm.ab.b; import com.tencent.mm.ab.l; import com.tencent.mm.ab.v.a; import com.tencent.mm.protocal.c.bhc; class AppBrandOpReportLogic$b$1 implements a { final /* synthetic */ String bAj; AppBrandOpReportLogic$b$1(String str) { this.bAj = str; } public final int a(int i, int i2, String str, b bVar, l lVar) { if (i == 0 && i2 == 0) { bhc bhc = (bhc) bVar.dIE.dIL; if (bhc != null) { AppBrandOpReportLogic.b.aE(this.bAj, bhc.shW); } } return 0; } }