text
stringlengths
10
2.72M
package com.ecommerce.sayurku.creative.sayurku; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.ecommerce.sayurku.creative.sayurku.Interface.ItemClickListener; import com.ecommerce.sayurku.creative.sayurku.ViewHolder.FoodViewHolder; import com.ecommerce.sayurku.creative.sayurku.Model.Food; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.mancj.materialsearchbar.MaterialSearchBar; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; public class FoodList extends AppCompatActivity { RecyclerView recyclerView; RecyclerView.LayoutManager layoutManager; FirebaseDatabase database; DatabaseReference foodList; String categoryId=""; FirebaseRecyclerAdapter<Food,FoodViewHolder> adapter; //Fungsi Search FirebaseRecyclerAdapter<Food,FoodViewHolder> searchAdapter; List<String> suggestList = new ArrayList<>(); MaterialSearchBar materialSearchBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_food_list); //Firebase database = FirebaseDatabase.getInstance(); foodList = database.getReference("Foods"); recyclerView = (RecyclerView) findViewById(R.id.recycler_food); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); //Get Intent if (getIntent() != null) categoryId = getIntent().getStringExtra("CategoryId"); //if (!categoryId.isEmpty() && categoryId != null) { loadListFood(categoryId); } } private void loadSuggest() { foodList.orderByChild("MenuId").equalTo(categoryId).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot postSnapshot:dataSnapshot.getChildren()) { Food item = postSnapshot.getValue(Food.class); suggestList.add(item.getName()); //menmbahkan nama makanan untuk ditampilkan ke suggest list } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void loadListFood(String categoryId) { //seperti perintah select * from Food where MenuId = adapter = new FirebaseRecyclerAdapter<Food, FoodViewHolder>(Food.class,R.layout.food_item,FoodViewHolder.class,foodList.orderByChild("MenuId").equalTo(categoryId)) { @Override protected void populateViewHolder(FoodViewHolder viewHolder, Food model, int position) { viewHolder.food_name.setText(model.getName()); viewHolder.food_price.setText(model.getPrice()); Picasso.with(getBaseContext()).load(model.getImage()).into(viewHolder.food_image); final Food local = model; viewHolder.setItemClickListener(new ItemClickListener() { @Override public void onClick(View view, int position, boolean isLongClick) { //Mulai Activity Baru Intent foodDetail = new Intent(FoodList.this,SignIn.class); foodDetail.putExtra("FoodId",adapter.getRef(position).getKey()); // untuk mengirim foodId ke activity baru startActivity(foodDetail); } }); } }; recyclerView.setAdapter(adapter); } }
package com.mx.profuturo.bolsa.model.service.hiringform.dto; import com.mx.profuturo.bolsa.model.service.hiringform.vo.DatosFormularioVO; public class TerminarFormularioDTO { private int idProceso; private DatosFormularioVO datosFormularioVO; public int getIdProceso() { return idProceso; } public void setIdProceso(int idProceso) { this.idProceso = idProceso; } public DatosFormularioVO getDatosFormularioVO() { return datosFormularioVO; } public void setDatosFormularioVO(DatosFormularioVO datosFormularioVO) { this.datosFormularioVO = datosFormularioVO; } }
package chapter12.Exercise12_09; public class BinaryFormatException extends Exception { public BinaryFormatException() { super(); } public BinaryFormatException(String message) { super(message); } }
package com.xwechat.api.wxapp; /** * Created by zqs on 2017/11/16. */ import okhttp3.RequestBody; import com.xwechat.api.Apis; import com.xwechat.api.AuthorizedApi; import com.xwechat.api.Method; import com.xwechat.util.JsonUtil; /** * 删除帐号下的某个模板 * * @Note 小程序api * @url https://api.weixin.qq.com/cgi-bin/wxopen/template/del?access_token=ACCESS_TOKEN * @see https://mp.weixin.qq.com/debug/wxadoc/dev/api/notice.html#模版消息管理 * @author zqs */ public class TemplateDelApi extends AuthorizedApi<WxappApiResp> { public TemplateDelApi() { super(Apis.WXAPP_TEMPLATE_DEL, Method.POST); } public TemplateDelApi setParams(TemplateReq req) { setRequestBody(RequestBody.create(JSON_MEDIA_TYPE, JsonUtil.writeAsString(JsonUtil.DEFAULT_OBJECT_MAPPER, req))); return this; } @Override public Class<WxappApiResp> getResponseClass() { return WxappApiResp.class; } }
package bg.sofia.uni.fmi.mjt.torrent.client; public class NicknameAlreadyExistsException extends Exception { public NicknameAlreadyExistsException(String message) { super(message); } }
package jp.naist.se.codehash; import jp.naist.se.codehash.util.StringMultiset; public class NgramMultiset { private int ngramCount; private StringMultiset regular; private StringMultiset normalized; public NgramMultiset(NgramReader ngramReader) { regular = new StringMultiset(2048); normalized = new StringMultiset(2048); while (ngramReader.next()) { // Calculate a hash for the N-gram StringBuilder builder = new StringBuilder(128); for (int i=0; i<ngramReader.getN(); i++) { if (ngramReader.getToken(i) != null) { builder.append(ngramReader.getToken(i)); } else { builder.append((char)i); } builder.append((char)0); } regular.add(builder.toString()); // Calculate a hash for the N-gram builder = new StringBuilder(128); for (int i=0; i<ngramReader.getN(); i++) { if (ngramReader.getNormalizedToken(i) != null) { builder.append(ngramReader.getNormalizedToken(i)); } else { builder.append((char)i); } builder.append((char)0); } normalized.add(builder.toString()); } ngramCount = ngramReader.getNgramCount(); } public StringMultiset getRegular() { return regular; } public StringMultiset getNormalized() { return normalized; } public int getNgramCount() { return ngramCount; } public int getUniqueNgramCount() { return regular.size(); } }
package com.milano.controller; import java.io.IOException; import java.sql.SQLException; 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 com.milano.bc.CorsoBC; @WebServlet("/rimuoviCorso") public class rimuoviCorso extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int codcorso = Integer.parseInt(request.getParameter("codcorso")); try { CorsoBC corsoBC = new CorsoBC(); if (codcorso != 0) { corsoBC.delete(codcorso); } } catch (SQLException | ClassNotFoundException exc) { exc.printStackTrace(); throw new ServletException(); } response.sendRedirect("eliminaCorsi.jsp"); } }
package br.org.funcate.glue.view; import java.awt.Color; import javax.swing.BoxLayout; import javax.swing.JPanel; /** * \brief Panel that have the application's toolbar. * * @author * @version 1.0.0 */ @SuppressWarnings("serial") public class PanelToolbar extends JPanel { /** The panel's toolbar. */ private Toolbar bar; public PanelToolbar() { setLayout(null); bar = new Toolbar(); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); //setLayout(null); setBackground(Color.white); setVisible(true); add(bar); } /** * \brief Method to get the panel's toolbar. * * @return The panel's toolbar. */ public Toolbar get_bar() { return bar; } }
package com.crivano.swaggerservlet; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONException; import org.json.JSONObject; import junit.framework.TestCase; /** * Unit test for simple App. */ public class SwaggerServletTest extends TestCase { private SwaggerServlet ss = null; private Swagger sv = null; @SuppressWarnings("serial") @Override protected void setUp() throws Exception { super.setUp(); ss = new SwaggerServlet(); ss.setAPI(ISwaggerPetstore.class); ss.setActionPackage("com.crivano.swaggerservlet"); } public void testCamelCase_Simple_Success() throws JSONException { assertEquals("PetPetId", ss.toCamelCase("/pet/{petId}")); } public void testAction_Simple_Success() throws Exception { ISwaggerPetstore.IPetPetIdGet.Request req = new ISwaggerPetstore.IPetPetIdGet.Request(); ISwaggerPetstore.IPetPetIdGet.Response resp = new ISwaggerPetstore.IPetPetIdGet.Response(); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getMethod()).thenReturn("GET"); when(request.getPathInfo()).thenReturn("/v2/pet/123"); ss.prepare(request, null); req = (ISwaggerPetstore.IPetPetIdGet.Request) ss.injectVariables(request, req); ss.run(req, resp); assertEquals("white", resp.color); } public void testAction_SimpleException_FailWithUnknownId() throws Exception { ISwaggerPetstore.IPetPetIdGet.Request req = new ISwaggerPetstore.IPetPetIdGet.Request(); ISwaggerPetstore.IPetPetIdGet.Response resp = new ISwaggerPetstore.IPetPetIdGet.Response(); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getMethod()).thenReturn("GET"); when(request.getPathInfo()).thenReturn("/v2/pet/456"); try { ss.prepare(request, null); ss.run(req, resp); assertTrue(false); } catch (Exception ex) { assertEquals("unknown petId", ex.getMessage()); } } public void testGet_Simple_Success() throws Exception { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getProtocol()).thenReturn("HTTP 1.1"); when(request.getMethod()).thenReturn("GET"); when(request.getPathInfo()).thenReturn("/v2/pet/123"); HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(pw); ss.doGet(request, response); String body = sw.toString(); JSONObject resp = new JSONObject(body); assertEquals("white", resp.get("color")); } public void testGet_SimpleException_FailWithUnknownId() throws Exception { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getMethod()).thenReturn("GET"); when(request.getPathInfo()).thenReturn("/v2/pet/456"); HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(pw); ss.doGet(request, response); JSONObject resp = new JSONObject(sw.toString()); JSONObject errordetails = resp.getJSONArray("errordetails").getJSONObject(0); assertEquals("unknown petId", resp.get("errormsg")); // assertEquals("test", errordetails.get("context")); assertEquals("SwaggerPetstore", errordetails.get("service")); assertNotNull(errordetails.get("stacktrace")); } }
package com.simha.SpringOAuth2Demo2Example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringOAuth2Demo2ExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringOAuth2Demo2ExampleApplication.class, args); } }
package io.github.rhythm2019.mawenCommunity.service.impl; import cn.hutool.core.bean.BeanUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import io.github.rhythm2019.mawenCommunity.dto.NotificationDTO; import io.github.rhythm2019.mawenCommunity.dto.PaginationDTO; import io.github.rhythm2019.mawenCommunity.dto.UserDTO; import io.github.rhythm2019.mawenCommunity.enums.NotificationStatusEnum; import io.github.rhythm2019.mawenCommunity.enums.NotificationTypeEnum; import io.github.rhythm2019.mawenCommunity.exception.CustomizeErrorCode; import io.github.rhythm2019.mawenCommunity.exception.CustomizeException; import io.github.rhythm2019.mawenCommunity.mapper.NotificationMapper; import io.github.rhythm2019.mawenCommunity.model.Notification; import io.github.rhythm2019.mawenCommunity.service.INotificationService; import io.github.rhythm2019.mawenCommunity.service.IQuestionService; import io.github.rhythm2019.mawenCommunity.service.IUserService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; @Service public class NotificationService extends ServiceImpl<NotificationMapper, Notification> implements INotificationService { @Resource private IQuestionService questionService; @Override public PaginationDTO<NotificationDTO> list(Integer userId, Integer page, Integer size) { Page<Notification> notificationPage = this.page(new Page<Notification>(page, size), new LambdaQueryWrapper<Notification>() .eq(Notification::getReceiver, userId) .orderBy(true, false, Notification::getGmtCreate)); return PaginationDTO.of(notificationPage.getRecords() .stream() .map(notification -> { NotificationDTO notificationDTO = BeanUtil.copyProperties(notification, NotificationDTO.class); notificationDTO.setTypeName(NotificationTypeEnum.nameOf(notification.getType())); return notificationDTO; }).collect(Collectors.toList()), notificationPage.getTotal(), notificationPage.getPages(), notificationPage.getSize()); } @Override public long countUnread(Integer id) { return this.count(new LambdaQueryWrapper<Notification>().eq(Notification::getStatus, NotificationStatusEnum.UNREAD.getStatus())); } @Override public void createNotification(UserDTO notifier, Integer receiver, NotificationTypeEnum typeEnum, Integer outerId, String outerName) { Notification notification = new Notification(); notification.setNotifier(notifier.getId()); notification.setReceiver(receiver); notification.setGmtCreate(System.currentTimeMillis()); notification.setType(typeEnum.getType()); notification.setStatus(NotificationStatusEnum.UNREAD.getStatus()); notification.setOuterId(outerId); notification.setNotifierName(notifier.getName()); notification.setOuterName(outerName); this.save(notification); } public NotificationDTO read(Integer id, Integer userId) { Notification notification = getById(id); //判断有没有这个消息 if(notification == null){ throw new CustomizeException(CustomizeErrorCode.NOTIFICATION_NOT_FOUND); } //检查一下是不是你的通知 if(!Objects.equals(notification.getReceiver(), userId)){ throw new CustomizeException(CustomizeErrorCode.NO_ALLOW_READ); } //修改一下未读状态 notification.setStatus(NotificationStatusEnum.READ.getStatus()); this.updateById(notification); return BeanUtil.copyProperties(notification, NotificationDTO.class); } }
package com.appc.report.controller; import basic.common.core.utils.MD5Util; import basic.common.core.utils.SpringUtils; import com.appc.framework.mybatis.executor.criteria.EntityCriteria; import com.appc.report.common.ReportConstants; import com.appc.report.model.AdminUser; import com.appc.report.model.Rule; import com.appc.report.model.RuleCate; import com.appc.report.service.AdminUserService; import com.appc.report.service.RuleCateService; import com.appc.report.service.RuleService; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttribute; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; @Controller public class SystemController { @Autowired private AdminUserService adminUserService; @Autowired private RuleService ruleService; @Autowired private RuleCateService ruleCateService; @Autowired private HttpServletRequest request; @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login() { ModelAndView mv = new ModelAndView("login");//指定视图 //向视图中添加所要展示或使用的内容,将在页面中使用 return mv; } @RequestMapping(value = "/logout", method = RequestMethod.GET) public ModelAndView logout() { request.getSession().invalidate(); ModelAndView mv = new ModelAndView("redirect:login.html");//指定视图 //向视图中添加所要展示或使用的内容,将在页面中使用 return mv; } @ApiOperation(ReportConstants.LOGIN) @RequestMapping(value = "/login", method = RequestMethod.POST) public ModelAndView loginPost(@RequestParam String username, @RequestParam String password, HttpSession session) { ModelAndView mv = new ModelAndView("login");//指定视图 AdminUser user = adminUserService.getEntity(EntityCriteria.build().eq("username", username)); if (user == null) { mv.addObject("error_message", SpringUtils.getLocalMessage("010002")); } else if (!user.getPassword().equals(MD5Util.getMD5String(password))) { mv.addObject("error_message", SpringUtils.getLocalMessage("010003")); } else if ("1".equals(user.getStatus())) { mv.addObject("error_message", SpringUtils.getLocalMessage("010017")); } else { session.setAttribute(ReportConstants.SESSION_KEY, user); List<Rule> menuList = null; if ("admin".equals(username)) { menuList = ruleService.getEntityList(); } else { menuList = ruleService.getMenuList(user.getId()); } List<RuleCate> ruleCates = new ArrayList<>(); for (Rule rule : menuList) { RuleCate parent = null; for (RuleCate ruleCate : ruleCates) { if (rule.getRuleCate().equals(ruleCate.getCateId())) { parent = ruleCate; break; } } if (parent == null) { parent = ruleCateService.getById(rule.getRuleCate()); parent.setRules(new ArrayList<>()); ruleCates.add(parent); } parent.getRules().add(rule); } session.setAttribute(ReportConstants.SESSION_MENU, ruleCates); mv = new ModelAndView("redirect:index.html");//指定视图 } return mv; } @RequestMapping(value = "/password", method = RequestMethod.GET) public ModelAndView password() { ModelAndView mv = new ModelAndView("password");//指定视图 //向视图中添加所要展示或使用的内容,将在页面中使用 return mv; } @ApiOperation("修改密码") @RequestMapping(value = "/password", method = RequestMethod.POST) public ModelAndView passwordPost(@RequestParam String oldpass, @RequestParam String password, @SessionAttribute("user") AdminUser sessionUser) { ModelAndView mv = new ModelAndView("password");//指定视图 AdminUser user = adminUserService.getById(sessionUser.getId()); if (user == null) { mv.addObject("error_message", SpringUtils.getLocalMessage("010002")); } else if (!user.getPassword().equals(MD5Util.getMD5String(oldpass))) { mv.addObject("error_message", SpringUtils.getLocalMessage("010015")); } else { user.setPassword(MD5Util.getMD5String(password)); adminUserService.updateById(user); mv.addObject("success", true); } return mv; } }
package de.bitkings.nitram509; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloWorldHttpController { @RequestMapping(path = "hello") @ResponseBody public String get() { return "Hello World"; } }
package com.devjam.training.cicourse.model; import java.util.ArrayList; import java.util.List; public class Order { private List <Item> myItems = new ArrayList <Item> ();; public void addItem(Item itemToAdd) { myItems.add(itemToAdd); } public void removeItem(Item itemToRemove) throws OrderException { if(myItems.contains(itemToRemove)) myItems.remove(itemToRemove); else throw new OrderException("Item: " + itemToRemove.getSku() + " Does Not Exist In Order"); } public int numberOfItems() { return myItems.size(); } public List <Item> getItemsInOrder() { return myItems; } public Double getOrderSubTotal() { double orderSubTotal = 0.0; for(Item oneItem: myItems) orderSubTotal += oneItem.getPrice(); return Double.valueOf(orderSubTotal); } }
package homework4; import java.sql.ResultSet; import java.sql.SQLException; public class Country { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static Country of(ResultSet resultSet){ Country country = new Country(); try { country.setId(resultSet.getInt("id")); country.setName(resultSet.getString("name")); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException("Can`t create country!"); } return country; } @Override public String toString() { return "Country{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
package com.project.linkedindatabase.service.modelMap.chat; import com.project.linkedindatabase.domain.chat.Message; import com.project.linkedindatabase.jsonToPojo.MessageJson; import com.project.linkedindatabase.repository.model.chat.MessageRepository; import com.project.linkedindatabase.service.model.ProfileService; import com.project.linkedindatabase.service.model.chat.MessageService; import org.springframework.stereotype.Service; import java.sql.SQLException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; @Service public class MessageServiceMap implements MessageService { private final MessageRepository messageRepository; public MessageServiceMap(ProfileService profileService) throws SQLException { this.messageRepository = new MessageRepository(profileService); } @Override public Message findById(Long aLong) throws SQLException { return messageRepository.findById(aLong); } @Override public void save(Message object) throws SQLException { messageRepository.save(object); } @Override public List<Message> findAll() throws SQLException { return messageRepository.findAll(); } @Override public void deleteByObject(Message object) throws SQLException { messageRepository.deleteByObject(object); } @Override public void deleteById(Long aLong) throws SQLException { messageRepository.deleteById(aLong); } @Override public void createTable() throws SQLException { messageRepository.createTable(); } @Override public List<Message> getMessagesByChatId(long chatId) throws SQLException, ParseException { return messageRepository.getMessagesByChatId(chatId); } @Override public List<MessageJson> getAllMessageByChatIdJson(Long chatId) throws SQLException { return messageRepository.getAllMessageByChatIdJson(chatId); } @Override public MessageJson convertToMessageJson(Message message) throws SQLException { return messageRepository.convertToMessageJson(message); } }
package com.example.tetrisapp; /** * 4 points make up a piece */ public class Piece implements Cloneable { // Coordinates of each square in piece public int x1, y1; public int x2, y2; public int x3, y3; public int x4, y4; public int colorCode; public Piece piece; // Copy constructor public Piece(Piece piece){ this.piece = piece; this.x1 = piece.x1; this.x2 = piece.x2; this.x3 = piece.x3; this.x4 = piece.x4; this.y1 = piece.y1; this.y2 = piece.y2; this.y3 = piece.y3; this.y4 = piece.y4; } // Constructor creates colored squares (distinct shape) per piece public Piece(int colorCode){ switch(colorCode){ case 1: // square x1 = 0; y1 = 7; x2 = 0; y2 = 8; x3 = 1; y3 = 7; x4 = 1; y4 = 8; this.colorCode = colorCode; break; case 2: // Z-piece x1 = 0; y1 = 7; x2 = 0; y2 = 8; x3 = 1; y3 = 8; x4 = 1; y4 = 9; this.colorCode = colorCode; break; case 3: // I-piece x1 = 0; y1 = 6; x2 = 0; y2 = 7; x3 = 0; y3 = 8; x4 = 0; y4 = 9; this.colorCode = colorCode; break; case 4: // T-piece x1 = 0; y1 = 8; x2 = 1; y2 = 7; x3 = 1; y3 = 8; x4 = 2; y4 = 8; this.colorCode = colorCode; break; case 5: // S-piece x1 = 0; y1 = 7; x2 = 0; y2 = 8; x3 = 1; y3 = 6; x4 = 1; y4 = 7; this.colorCode = colorCode; break; case 6: // J-piece x1 = 2; y1 = 7; x2 = 2; y2 = 8; x3 = 1; y3 = 8; x4 = 0; y4 = 8; this.colorCode = colorCode; break; case 7: // L-piece x1 = 0; y1 = 7; x2 = 0; y2 = 8; x3 = 1; y3 = 8; x4 = 2; y4 = 8; this.colorCode = colorCode; break; } } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } // Move square by x amount and y amount public void move(int x, int y){ // Square 1 x1 = x1 + x; y1 = y1 + y; // Square 2 x2 = x2 + x; y2 = y2 + y; // Square 3 x3 = x3 + x; y3 = y3 + y; // Square 4 x4 = x4 + x; y4 = y4 + y; } // Gets new coordinate of x after rotation public int turnAroundX1(int y){ return x1 + y - y1; } // Gets new coordinate of y after rotation public int turnAroundY1(int x){ return y1 + x - x1; } // Rotate piece public void turnPiece(){ int tempX1, tempY1; int tempX2, tempY2; int tempX3, tempY3; tempX1 = turnAroundX1(y2); tempY1 = turnAroundY1(x2); x2 = tempX1; y2 = tempY1; tempX2 = turnAroundX1(y3); tempY2 = turnAroundY1(x3); x3 = tempX2; y3 = tempY2; tempX3 = turnAroundX1(y4); tempY3 = turnAroundY1(x4); x4 = tempX3; y4 = tempY3; } // Get smallest x-coord of four square points public int getMinXCoord(int x1, int x2, int x3, int x4){ return Math.min(Math.min(x1,x2), Math.min(x3, x4)); } }
package api.arq.validator.dto; import java.util.List; public class ApiErrosView{ List<ApiFieldErro> fieldErros; List<ApiErroGeral> errosGerais; public ApiErrosView(List<ApiFieldErro> fieldErros, List<ApiErroGeral> erroGerais){ super(); this.fieldErros = fieldErros; this.errosGerais = erroGerais; } public List<ApiFieldErro> getFieldErros() { return fieldErros; } public void setFieldErros(List<ApiFieldErro> fieldErros) { this.fieldErros = fieldErros; } public List<ApiErroGeral> getErrosGerais() { return errosGerais; } public void setErrosGerais(List<ApiErroGeral> errosGerais) { this.errosGerais = errosGerais; } }
/** * */ package com.goodhealth.web.service.impl; import com.goodhealth.web.dao.PrizeRepository; import com.goodhealth.web.entity.Prize; import com.goodhealth.web.service.PrizeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.List; /** * @author 24663 * @date 2019年1月8日 * @Description */ @Service public class PrizeServiceImp implements PrizeService { @Autowired private PrizeRepository prizeRepository; @Override public List<Prize> findAll() { return prizeRepository.findAll(); } /* *//* (non-Javadoc) * @see PrizeService#findListByLikeName(java.lang.String, int) *//* @Override public Page<Prize> findListByLikeName(final String name, int index){ Pageable pageable= new PageRequest(index, 10); Specification<Prize> spec=new Specification<Prize>() { @Override public Predicate toPredicate(Root<Prize> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Predicate pre=cb.like(root.get("prizeName").as(String.class), "%"+name+"%"); return pre; } }; Page<Prize> list=this.prizeRepository.findAll(spec,pageable); return list; }*/ @Override @Cacheable public Page<Prize> findByPage(int index) { Sort sort = new Sort(Sort.Direction.DESC,"prizeId"); Pageable pageable = new PageRequest(index,5,sort); return prizeRepository.findAll(pageable); } /* (non-Javadoc) * @see PrizeService#addPrize(Prize) */ @Override @CacheEvict public void addPrize(Prize prize){ this.prizeRepository.save(prize); } /* (non-Javadoc) * @see PrizeService#deletePrizeById(int) */ @Override @CacheEvict public void deletePrizeById(int id){ this.prizeRepository.deleteById(id); } /* (non-Javadoc) * @see PrizeService#findPrizeByName(java.lang.String) */ @Override public List<Prize> findPrizeByNameLike(String name){ Specification<Prize> spec=new Specification<Prize>() { @Override public Predicate toPredicate(Root<Prize> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Predicate pre=cb.like(root.get("prizeName").as(String.class), "%"+name+"%"); return pre; } }; return prizeRepository.findAll(spec); } /* (non-Javadoc) * @see PrizeService#findById(int) */ @Override public Prize findById(int id){ // TODO Auto-generated method stub return this.prizeRepository.getOne(id); } }
/* Author: Solehjon Ruziboev Date: 21.03.2016 Version: 1.0 */ import java.util.*; import java.lang.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import myWorld.*; import shapes.*; public class Lab04b{ public static void main(String args[]){ JFrame main = new JFrame("Ballons"); BalloonsGamePanel panel1 = new BalloonsGamePanel(); main.add(panel1); main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); main.setVisible(true); main.pack(); } }
package com.cjava.spring.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjava.spring.util.Properties; @Service public class ServiceFactory { @Autowired private Properties properties; @Autowired private EmpleadoService empleadoService; @Autowired private ArticuloService articuloService; @Autowired private ClienteService clienteService; @Autowired private VentaService ventaService; public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public EmpleadoService getEmpleadoService() { return empleadoService; } public void setEmpleadoService(EmpleadoService empleadoService) { this.empleadoService = empleadoService; } public ArticuloService getArticuloService() { return articuloService; } public void setArticuloService(ArticuloService articuloService) { this.articuloService = articuloService; } public ClienteService getClienteService() { return clienteService; } public void setClienteService(ClienteService clienteService) { this.clienteService = clienteService; } public VentaService getVentaService() { return ventaService; } public void setVentaService(VentaService ventaService) { this.ventaService = ventaService; } }
package pl.ark.chr.buginator.app.application; import java.util.Objects; public abstract class BaseApplicationDTO { private Long id; private String name; BaseApplicationDTO(Builder builder) { id = builder.id; name = builder.name; } public Long getId() { return id; } public String getName() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BaseApplicationDTO that = (BaseApplicationDTO) o; return id.equals(that.id); } @Override public int hashCode() { return Objects.hash(id); } static abstract class Builder<T extends Builder<T>> { protected Long id; protected String name; protected abstract T self(); Builder() { } public T id(Long val) { Objects.requireNonNull(val); id = val; return self(); } public T name(String val) { Objects.requireNonNull(val); name = val; return self(); } public abstract BaseApplicationDTO build(); } }
package com.coinhunter.web.ticker.websocket; import com.coinhunter.core.domain.bithumb.BithumbApiPayload; import com.coinhunter.core.domain.bithumb.ticker.BithumbTicker; import com.coinhunter.core.service.bithumb.BithumbApiService; import com.coinhunter.core.service.user.UserDetailsServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; @Slf4j @Controller public class TickerController { private UserDetailsServiceImpl userDetailsService; private BithumbApiService bithumbApiService; private SimpMessagingTemplate template; @Value("${websocket.ticker.send.delay}") private long tickerSendDelay; @Autowired public TickerController( UserDetailsServiceImpl userDetailsService, BithumbApiService bithumbApiService, SimpMessagingTemplate template) { this.userDetailsService = userDetailsService; this.bithumbApiService = bithumbApiService; this.template = template; } @MessageMapping("/ticker/bithumb") @SendTo("/topic/ticker/bithumb") public BithumbTicker sendTicker(@Payload BithumbApiPayload bithumbApiPayload) throws Exception { Thread.sleep(tickerSendDelay); return bithumbApiService.getTickerByCryptoCurrency(bithumbApiPayload.getCryptoCurrency()); } }
/** * Copyright (c) 2013-2020 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.adapter.vector.plugin; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Timestamp; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TimeZone; import org.geotools.feature.visitor.MaxVisitor; import org.geotools.feature.visitor.MinVisitor; import org.locationtech.geowave.core.geotime.store.statistics.FieldNameStatistic; import org.locationtech.geowave.core.geotime.store.statistics.TimeRangeDataStatistics; import org.locationtech.geowave.core.geotime.util.ExtractAttributesFilter; import org.locationtech.geowave.core.store.adapter.statistics.InternalDataStatistics; import org.locationtech.geowave.core.store.adapter.statistics.NumericRangeDataStatistics; import org.locationtech.geowave.core.store.adapter.statistics.StatisticsId; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.AttributeDescriptor; class GeoWaveGTPluginUtils { protected static List<InternalDataStatistics<SimpleFeature, ?, ?>> getStatsFor( final String name, final Map<StatisticsId, InternalDataStatistics<SimpleFeature, ?, ?>> statsMap) { final List<InternalDataStatistics<SimpleFeature, ?, ?>> stats = new LinkedList<>(); for (final Map.Entry<StatisticsId, InternalDataStatistics<SimpleFeature, ?, ?>> stat : statsMap.entrySet()) { if ((stat.getValue() instanceof FieldNameStatistic) && ((FieldNameStatistic) stat.getValue()).getFieldName().endsWith(name)) { stats.add(stat.getValue()); } } return stats; } protected static boolean accepts( final org.opengis.feature.FeatureVisitor visitor, final org.opengis.util.ProgressListener progress, final SimpleFeatureType featureType, final Map<StatisticsId, InternalDataStatistics<SimpleFeature, ?, ?>> statsMap) throws IOException { if ((visitor instanceof MinVisitor)) { final ExtractAttributesFilter filter = new ExtractAttributesFilter(); final MinVisitor minVisitor = (MinVisitor) visitor; final Collection<String> attrs = (Collection<String>) minVisitor.getExpression().accept(filter, null); int acceptedCount = 0; for (final String attr : attrs) { for (final InternalDataStatistics<SimpleFeature, ?, ?> stat : getStatsFor(attr, statsMap)) { if (stat instanceof TimeRangeDataStatistics) { minVisitor.setValue( convertToType( attr, new Date(((TimeRangeDataStatistics) stat).getMin()), featureType)); acceptedCount++; } else if (stat instanceof NumericRangeDataStatistics) { minVisitor.setValue( convertToType(attr, ((NumericRangeDataStatistics) stat).getMin(), featureType)); acceptedCount++; } } } if (acceptedCount > 0) { if (progress != null) { progress.complete(); } return true; } } else if ((visitor instanceof MaxVisitor)) { final ExtractAttributesFilter filter = new ExtractAttributesFilter(); final MaxVisitor maxVisitor = (MaxVisitor) visitor; final Collection<String> attrs = (Collection<String>) maxVisitor.getExpression().accept(filter, null); int acceptedCount = 0; for (final String attr : attrs) { for (final InternalDataStatistics<SimpleFeature, ?, ?> stat : getStatsFor(attr, statsMap)) { if (stat instanceof TimeRangeDataStatistics) { maxVisitor.setValue( convertToType( attr, new Date(((TimeRangeDataStatistics) stat).getMax()), featureType)); acceptedCount++; } else if (stat instanceof NumericRangeDataStatistics) { maxVisitor.setValue( convertToType(attr, ((NumericRangeDataStatistics) stat).getMax(), featureType)); acceptedCount++; } } } if (acceptedCount > 0) { if (progress != null) { progress.complete(); } return true; } } return false; } protected static Object convertToType( final String attrName, final Object value, final SimpleFeatureType featureType) { final AttributeDescriptor descriptor = featureType.getDescriptor(attrName); if (descriptor == null) { return value; } final Class<?> attrClass = descriptor.getType().getBinding(); if (attrClass.isInstance(value)) { return value; } if (Number.class.isAssignableFrom(attrClass) && Number.class.isInstance(value)) { if (Double.class.isAssignableFrom(attrClass)) { return ((Number) value).doubleValue(); } if (Float.class.isAssignableFrom(attrClass)) { return ((Number) value).floatValue(); } if (Long.class.isAssignableFrom(attrClass)) { return ((Number) value).longValue(); } if (Integer.class.isAssignableFrom(attrClass)) { return ((Number) value).intValue(); } if (Short.class.isAssignableFrom(attrClass)) { return ((Number) value).shortValue(); } if (Byte.class.isAssignableFrom(attrClass)) { return ((Number) value).byteValue(); } if (BigInteger.class.isAssignableFrom(attrClass)) { return BigInteger.valueOf(((Number) value).longValue()); } if (BigDecimal.class.isAssignableFrom(attrClass)) { return BigDecimal.valueOf(((Number) value).doubleValue()); } } if (Calendar.class.isAssignableFrom(attrClass)) { if (Date.class.isInstance(value)) { final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.setTime((Date) value); return c; } } if (Timestamp.class.isAssignableFrom(attrClass)) { if (Date.class.isInstance(value)) { final Timestamp ts = new Timestamp(((Date) value).getTime()); return ts; } } return value; } }
package ch03.ex03_09; public class Vehicle implements Cloneable { private double velocity; // 現在のスピード private double direction; // 現在の方向 private String owner; // 所有者 private long idNum; private static long nextID = 0; public Vehicle() { idNum = nextID++; } public Vehicle(String firstOwner) { this(); owner = firstOwner; } public void setVelocity(double value) { velocity = value; } public double getVelocity() { return velocity; } public void setAngle(double value) { direction = value; } public double getAngle() { return direction; } @Override public String toString() { return "ID = " + idNum + "\n" + "スピード = " + velocity + "\n" +"方向 = "+ direction + "\n" +"所有者 = "+ owner; } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } } }
package sarong.discouraged; import sarong.LightRNG; import sarong.StatefulRandomness; import sarong.util.StringKit; import java.io.Serializable; /** * Based on the same SplitMix algorithm {@link LightRNG} uses, but a 32-bit variant, this RandomnessSource has 63 bits * of state and should have a period of 2 to the 63. It has 2 ints for state, one of which changes with every number * generated (state A), and the other of which changes rarely and is always odd (state B). State A goes through every * number in a simple sequence that would normally repeat after 2 to the 32 generations, and always will be 0 once every * 2 to the 32 generations; the sequence is formed by just adding state B to state A. When state A changes to 0, state B * changes by adding a large even constant and that is used for the rest of the next 2 to the 32 generations. Although * this uses a ternary conditional to determine when to change state B, the branch on which state B changes happens so * rarely that processor branch prediction can almost optimize it out, and this is just slightly slower than LightRNG on * 32-bit int generation. Quality is not great with such a small state; this shouldn't be expected to pass many tests on * 2GB or more of tested data. * Created by Tommy Ettinger on 7/15/2017. */ public final class Light32RNG implements StatefulRandomness, Serializable { private int state, inc; private static final long serialVersionUID = -374415589203474497L; /** * Constructs a Light32RNG with a random state, using two calls to Math.random(). */ public Light32RNG() { this((int)((Math.random() * 2.0 - 1.0) * 0x80000000), (int)((Math.random() * 2.0 - 1.0) * 0x80000000)); } /** * Constructs a Light32RNG with the exact state A given and a similar state B (the least significant bit of state B * will always be 1 internally, so even values for state B will be incremented and odd values will be kept as-is). * @param stateA any int * @param stateB any int, but the last bit will not be used (e.g. 20 and 21 will be treated the same) */ public Light32RNG(int stateA, int stateB) { state = stateA; inc = stateB | 1; } /** * Takes 32 bits of state and uses it to randomly fill the 63 bits of state this uses. * @param statePart any int */ public Light32RNG(int statePart) { state = determine(statePart + 19) + statePart; inc = determine(state + statePart) | 1; } /** * Constructs a Light32RNG using a long that combines the two parts of state, as from {@link #getState()}. * @param stateCombined a long that combines state A and state B, with state A in the less significant 32 bits */ public Light32RNG(long stateCombined) { state = (int)stateCombined; inc = (int)(stateCombined >>> 32 | 1); } public final int nextInt() { int z = (state += (state == 0) ? (inc += 0x632BE5A6) : inc); z = (z ^ (z >>> 16)) * 0x85EBCA6B; z = (z ^ (z >>> 13)) * 0xC2B2AE35; return z ^ (z >>> 16); } /** * Using this method, any algorithm that might use the built-in Java Random * can interface with this randomness source. * * @param bits the number of bits to be returned * @return the integer containing the appropriate number of bits */ @Override public final int next(int bits) { int z = (state += (state == 0) ? (inc += 0x632BE5A6) : inc); z = (z ^ (z >>> 16)) * 0x85EBCA6B; z = (z ^ (z >>> 13)) * 0xC2B2AE35; return (z ^ (z >>> 16)) >>> (32 - bits); } /** * Using this method, any algorithm that needs to efficiently generate more * than 32 bits of random data can interface with this randomness source. * <p> * Get a random long between Long.MIN_VALUE and Long.MAX_VALUE (both inclusive). * * @return a random long between Long.MIN_VALUE and Long.MAX_VALUE (both inclusive) */ @Override public final long nextLong() { int y = (state += (state == 0) ? (inc += 0x632BE5A6) : inc), z = (state += (state == 0) ? (inc += 0x632BE5A6) : inc); y = (y ^ (y >>> 16)) * 0x85EBCA6B; z = (z ^ (z >>> 16)) * 0x85EBCA6B; y = (y ^ (y >>> 13)) * 0xC2B2AE35; z = (z ^ (z >>> 13)) * 0xC2B2AE35; return (long)(y ^ (y >>> 16)) << 32 ^ (z ^ (z >>> 16)); } /** * Produces a copy of this RandomnessSource that, if next() and/or nextLong() are called on this object and the * copy, both will generate the same sequence of random numbers from the point copy() was called. This just need to * copy the state so it isn't shared, usually, and produce a new value with the same exact state. * * @return a copy of this RandomnessSource */ @Override public Light32RNG copy() { return new Light32RNG(state, inc); } public int getStateA() { return state; } public void setStateA(int stateA) { state = stateA; } public int getStateB() { return inc; } public void setStateB(int stateB) { inc = stateB | 1; } /** * Get the current internal state of the StatefulRandomness as a long. * * @return the current internal state of this object. */ @Override public long getState() { return (long)inc << 32 | (state & 0xFFFFFFFFL); } /** * Set the current internal state of this StatefulRandomness with a long. * This implementation may not use the state verbatim, since only 63 bits are actually used as state here. * Specifically, the bit in state that would be masked by 0x0000000100000000L is unused; it is always 1 internally. * @param state a 64-bit long. You should avoid passing 0, even though some implementations can handle that. */ @Override public void setState(long state) { this.state = (int)(state & 0xFFFFFFFFL); inc = (int) (state >>> 32) | 1; } /** * Sets the current internal state of this Light32RNG with two ints. * The least significant bit of stateB is unused; it is always 1 internally. * @param stateA any int * @param stateB any int, but the last bit will not be used (e.g. 20 and 21 will be treated the same) */ public void setState(int stateA, int stateB) { state = stateA; inc = stateB | 1; } @Override public String toString() { return "Light32RNG with stateA 0x" + StringKit.hex(state) + " and stateB 0x" + StringKit.hex(inc); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Light32RNG that = (Light32RNG) o; return state == that.state && inc == that.inc; } @Override public int hashCode() { int result = state; result = 31 * result + inc; return result; } /** * Gets a pseudo-random int from the given state as an int; the state should change with each call. * This can be done easily with {@code determine(++state)} or {@code determine(state += 12345)}, where 12345 * can be any odd number (it should stay the same across calls that should have random-seeming results). Uses the * same algorithm as Light32RNG, but does not change the increment on its own (it leaves that to the user). * @param state should be changed with each call; {@code determine(++state)} will work fine * @return a pseudo-random int */ public static int determine(int state) { state = ((state *= 0x9E3779B9) ^ (state >>> 16)) * 0x85EBCA6B; state = (state ^ (state >>> 13)) * 0xC2B2AE35; return state ^ (state >>> 16); } /** * Gets a pseudo-random int between 0 and the given bound, using the given state as a basis, as an int; the state * should change with each call. This can be done easily with {@code determineBounded(++state, bound)} or * {@code determineBounded(state += 12345, bound)}, where 12345 can be any odd number (it should stay the same * across calls that should have random-seeming results). The bound should be between -32768 and 32767 (both * inclusive); more significant bounds won't usually work well. Uses the same algorithm as Light32RNG, but does not * change the increment on its own (it leaves that to the user). * @param state should be changed with each call; {@code determineBounded(++state, bound)} will work fine * @param bound the outer exclusive limit on the random number; should be between -32768 and 32767 (both inclusive) * @return a pseudo-random int, between 0 (inclusive) and bound (exclusive) */ public static int determineBounded(int state, int bound) { state = ((state *= 0x9E3779B9) ^ (state >>> 16)) * 0x85EBCA6B; state = (state ^ (state >>> 13)) * 0xC2B2AE35; return ((bound * ((state ^ (state >>> 16)) & 0x7FFF)) >> 15); } }
package com.boot.spring.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.boot.spring.model.Project; @Repository public interface ProjectsRepository extends CrudRepository<Project, String> { List<Project> findAll(); }
package com.bridgeit.ADDRESSBook; public class Person { String fierstName; String lastName; Address address; String mobileNumber; public String getFierstName() { return fierstName; } public void setFierstName(String fierstName) { this.fierstName = fierstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String getMobileNumber() { return mobileNumber; } public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } public String toString() { return "\n\t First Name: " + fierstName + "\n\t Last Name: " + lastName + "\n\t Address: " + address + "\n\t Mobile Num: " + mobileNumber; } }
package cqu.shy.arithmetic; /** * Created by SHY on 2014/12/16/0016. */ public class Element { public Double value; public ElementType type; public char ope; public int length; }
package com.tt.miniapp.msg; import android.text.TextUtils; import com.a; import com.tt.frontendapiinterface.b; import com.tt.miniapp.debug.DebugManager; import com.tt.miniapp.storage.Storage; import com.tt.miniapphost.AppBrandLogger; import com.tt.option.e.e; import java.io.IOException; import org.json.JSONException; import org.json.JSONObject; public class ApiSetStorageCtrl extends b { public ApiSetStorageCtrl(String paramString, int paramInt, e parame) { super(paramString, paramInt, parame); } public void act() { try { boolean bool; JSONObject jSONObject = new JSONObject(this.mArgs); String str1 = jSONObject.optString("key"); if (TextUtils.isEmpty(str1)) { callbackIllegalParam("key"); return; } String str2 = jSONObject.optString("data"); String str3 = jSONObject.optString("dataType"); AppBrandLogger.d("tma_ApiSetStorageCtrl", new Object[] { "key ", str1, " \n value", str2, " \n dataType", str3 }); if ((DebugManager.getInst()).mRemoteDebugEnable) { String str = Storage.getValue(str1); bool = Storage.setValue(str1, str2, str3); DebugManager.getInst().getRemoteDebugManager().setDOMStorageItem(0, bool, str1, str, str2); } else { bool = Storage.setValue(str1, str2, str3); } if (bool) { callbackOk(); return; } callbackFail(a.a("set storage fail", new Object[0])); return; } catch (JSONException jSONException) { AppBrandLogger.stacktrace(6, "tma_ApiSetStorageCtrl", jSONException.getStackTrace()); callbackFail((Throwable)jSONException); return; } catch (IOException iOException) { AppBrandLogger.stacktrace(6, "tma_ApiSetStorageCtrl", iOException.getStackTrace()); callbackFail(iOException.getMessage()); return; } catch (Exception exception) { AppBrandLogger.stacktrace(6, "tma_ApiSetStorageCtrl", exception.getStackTrace()); callbackFail(exception); return; } } public String getActionName() { return "setStorage"; } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\ApiSetStorageCtrl.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.ifre.controller.brms; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.core.util.ResourceUtil; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.tag.core.easyui.TagUtil; import org.jeecgframework.web.system.pojo.base.TSTypegroup; import org.jeecgframework.web.system.pojo.base.TSUser; import org.jeecgframework.web.system.service.SystemService; import org.kie.api.runtime.StatelessKieSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.ifre.common.Constants; import com.ifre.entity.brms.RulePckgEntity; import com.ifre.entity.brms.RuleProdEntity; import com.ifre.entity.ruleengin.BrmsRuleTableEntity; import com.ifre.invoker.DecitabInvokerI; import com.ifre.invoker.DecitableInvokerFactroy; import com.ifre.ruleengin.RuleFactory; import com.ifre.ruleengin.hotcompiler.DynamicEngine; import com.ifre.service.brms.HotComplierServiceI; import com.ifre.service.brms.ProcessExcelServicel; import com.ifre.service.brms.RuleProdServiceI; import com.ifre.util.ChineseToEnglish; import com.ifre.util.PathUtils; import net.sf.json.JSONArray; import net.sf.json.JSONObject; @Scope("prototype") @Controller @RequestMapping("/ruleTesterController") public class RuleTesterController extends BaseController{ Logger log = Logger.getLogger(RuleTesterController.class); @Autowired private RuleProdServiceI ruleProdService; @Autowired private SystemService systemService; @Autowired private ProcessExcelServicel processExcelService; @Autowired private HotComplierServiceI hotComplierService; @RequestMapping(params = "datagrid") public void datagrid(RuleProdEntity ruleProd,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { String prodType = request.getParameter("prodType"); String sql = " "; if (StringUtil.isNotEmpty(ruleProd.getOrgId())) { sql += "and pr.orgId='" + ruleProd.getOrgId() + "'"; } if (StringUtil.isNotEmpty(ruleProd.getKknwldgId())) { sql += "and pr.kknwldgId='" + ruleProd.getKknwldgId() + "'"; } if (StringUtil.isNotEmpty(ruleProd.getName())) { sql += "and pr.name like '%" + ruleProd.getName() + "%'"; } if (StringUtil.isNotEmpty(prodType)) { sql += "and pr.type =" + Integer.parseInt(prodType); } sql += " and pr.status >= '"+Constants.START+"'" + " and pr.rightStatus = 1" ; CriteriaQuery cq = new CriteriaQuery(RuleProdEntity.class, dataGrid); //机构过滤-后台实现 TSUser tSUser = ResourceUtil.getSessionUserName(); if(!"A01".equals(tSUser.getCurrentDepart().getOrgCode())){ //cq无效果,原因:马江修改了jeecg源码,使用的是sql的形式获取数据 //cq.eq("orgCode", tSUser.getSysCompanyCode()); sql += " and pr.orgCode = '" + tSUser.getCurrentDepart().getOrgCode() + "'"; } cq.add(); // cq.eq("kknwldgId", ruleProd.getKknwldgId()); // cq.like("name", ruleProd.getName()); // cq.eq("type", prodType); // cq.ge("status", Constants.START); // cq.eq("rightStatus", "1"); // cq.add(); // 查询条件组装器 org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, ruleProd, request.getParameterMap()); this.ruleProdService.getDataGridAReturn(cq, true, sql); // this.ruleProdService.getDataGridReturn(cq, true); TagUtil.datagrid(response, dataGrid); // createMavenFile(); } @RequestMapping(params = "datagridJarList") public void datagridJarList(RuleProdEntity ruleProd,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { String prodType = request.getParameter("prodType"); String sql = " "; if (StringUtil.isNotEmpty(ruleProd.getOrgId())) { sql += "and pr.orgId='" + ruleProd.getOrgId() + "'"; } if (StringUtil.isNotEmpty(ruleProd.getKknwldgId())) { sql += "and pr.kknwldgId='" + ruleProd.getKknwldgId() + "'"; } if (StringUtil.isNotEmpty(ruleProd.getName())) { sql += "and pr.name like '%" + ruleProd.getName() + "%'"; } if (StringUtil.isNotEmpty(prodType)) { sql += "and pr.type =" + Integer.parseInt(prodType); } sql += "and pr.status >= '"+Constants.PASS_TEST+"'" + " and pr.rightStatus = 1" ; CriteriaQuery cq = new CriteriaQuery(RuleProdEntity.class, dataGrid); //机构过滤-后台实现 TSUser tSUser = ResourceUtil.getSessionUserName(); if(!"A01".equals(tSUser.getCurrentDepart().getOrgCode())){ //cq无效果,原因:马江修改了jeecg源码,使用的是sql的形式获取数据 //cq.eq("orgCode", tSUser.getSysCompanyCode()); sql += " and pr.orgCode = '" + tSUser.getCurrentDepart().getOrgCode() + "'"; } cq.add(); // 查询条件组装器 org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, ruleProd, request.getParameterMap()); this.ruleProdService.getDataGridAReturn(cq, true, sql); // this.ruleProdService.getDataGridReturn(cq, true); TagUtil.datagrid(response, dataGrid); // createMavenFile(); } @RequestMapping(params = "showTester") public ModelAndView showTester(HttpServletRequest request){ String prodType = request.getParameter("prodType"); request.setAttribute("prodType", prodType); if (prodType != null && prodType.equals("1")) { return new ModelAndView("com/ifre/brms/modelTestList"); } else { return new ModelAndView("com/ifre/brms/ruleTestList"); } } @RequestMapping(params = "ruleTesterProd") public ModelAndView ruleTesterProd(String id,String prodName,HttpServletRequest request) throws UnsupportedEncodingException{ request.setAttribute("id", id); request.setAttribute("prodName", prodName); return new ModelAndView("com/ifre/brms/ruleTesterProd"); } @RequestMapping(params = "callJar") public ModelAndView callJar(HttpServletRequest request) throws UnsupportedEncodingException{ return new ModelAndView("com/ifre/show/callJar"); } @RequestMapping(params = "outerCallJar") public ModelAndView outerCallJar(String id,HttpServletRequest request) throws UnsupportedEncodingException{ List<RulePckgEntity> packList = systemService.findHql("from RulePckgEntity where prodId = ?", id); String packc = null; if(!packList.isEmpty()){ packc = packList.get(0).getAllName(); } request.setAttribute("packc", packc); return new ModelAndView("com/ifre/show/callJarOuter"); } @RequestMapping(params = "getTesterSelectData") @ResponseBody public List<Map<String,String>> getTesterSelectData(String id,HttpServletRequest request){ List<Map<String,String>> list = new ArrayList<Map<String,String>>(); String hqlForFirst = "from BrmsRuleTableEntity where prodId = ? order by salience desc"; List<BrmsRuleTableEntity> ruleList = systemService.findHql(hqlForFirst, new Object[]{id}); String ruleId = null; if(!ruleList.isEmpty()){ ruleId = ruleList.get(0).getId(); } Map<String,String[][]> hm = processExcelService.grubDeciTableData(ruleId); String[][] head = hm.get("head"); String[][] body = hm.get("body"); int flag = 0; for (int i = 0; i < head[0].length; i++) { if(StringUtils.isNotEmpty(head[0][i])){ flag = i; break; } } int headRows = head.length; int varDescP = 0; int varValueP = 0; for(int i = 0; i < head[headRows-1].length;i++ ){ if("变量描述".equals(head[headRows-1][i])){ varDescP =i; break; } } for(int i = 0; i < head[headRows-1].length;i++ ){ if("变量名称".equals(head[headRows-1][i])){ varValueP = i; break; } } String typeStr = null; for(int i = 0; i < head[headRows-1].length;i++ ){ if("模型类型".equals(head[headRows-1][i])||"贷款类型".equals(head[headRows-1][i])){ typeStr = body[0][i]; break; } } log.info("模型类型:"+typeStr); int type = Integer.valueOf(typeStr); List<Map<String,String>> descList = new ArrayList<Map<String,String>>(); int row = body[0].length; for (int i = 0; i < body.length; i++) { Map<String,String> temp = new HashMap<String,String>(); StringBuilder sb = new StringBuilder(); if(StringUtils.isEmpty(body[i][0])){ continue; } for (int j = 1; j < row; j++) { sb.append(body[i][j]); } temp.put("text", sb.toString()); temp.put("value", body[i][varValueP]); descList.add(temp); } if(type != 71){ Map<String,Integer> setDesc = new HashMap<String,Integer>(); Map<String,Integer> setValue = new HashMap<String,Integer>(); for (int i = 0; i < body.length; i++) { // setDesc.put(body[i][varDescP],i); setValue.put(body[i][varValueP],i); } /* Set<String> setValueP = new HashSet<String>(); for (int i = 0; i < body.length; i++) { setValueP.add(body[i][varDescP]); }*/ // for (Map.Entry<String, Integer> desc : setDesc.entrySet()) { // for (Map.Entry<String, Integer> value : setValue.entrySet()) { // if(desc.getValue() == value.getValue()){ // Map<String,String> temp = new HashMap<String,String>(); // temp.put("text",desc.getKey()); // temp.put("value",StringUtils.trim(value.getKey())); // list.add(temp); // } // } // } //变量描述可能随意变化,以变量名称为主键 for (Map.Entry<String, Integer> value : setValue.entrySet()) { Map<String,String> temp = new HashMap<String,String>(); temp.put("text",body[value.getValue()][varDescP]); temp.put("value",body[value.getValue()][varValueP]); list.add(temp); } }else{ for (int i = 0; i < body.length; i++) { Map<String,String> temp = new HashMap<String,String>(); StringBuilder sb = new StringBuilder(); if(StringUtils.isEmpty(body[i][0])){ continue; } for (int j = 1; j < flag; j++) { sb.append(body[i][j]); } temp.put("text", sb.toString()); temp.put("value", body[i][flag]); list.add(temp); } } return list; } /** * 获取预测填写数据 * @param id * @param request * @param response * @return */ @RequestMapping(params = "getPredData") @ResponseBody public Map<String,Object> getPredData(String id,HttpServletRequest request, HttpServletResponse response){ Map<String, Object> hm = new HashMap<String, Object>(); String hqlForPreTest = "select prop.PROP_CODE code, prop.name, prop.descp from brms_obj_prop prop " + "left join brms_biz_obj bizobj on prop.BIZ_OBJ_ID = bizobj.id " + "where bizobj.name = 'LoanApplication' and bizobj.PROD_ID = ? "; List<Map<String, Object>> preList = systemService.findForJdbc(hqlForPreTest, new Object[] { id }); hm.put("total", preList.size()); hm.put("rows", preList); return hm; } @RequestMapping(params = "mainTest") @ResponseBody public AjaxJson mainTest(String id,String data,HttpServletRequest request){ AjaxJson aj = new AjaxJson(); JSONObject dataObj = JSONObject.fromObject(data); JSONArray array = dataObj.getJSONArray("rows"); String returnStr = ""; List<File> files = null; try { Map<String, String> applicantMap = new HashMap<String, String>(); applicantMap = new HashMap<String, String>(); for (int i = 0; i < array.size(); i++) { JSONObject jb = array.getJSONObject(i); applicantMap.put(jb.getString("testKey"), jb.getString("value")); } List<Map<String, Object>> list = hotComplierService.hotcompiler(id); RuleFactory factory = new RuleFactory(); String hqlForFirst = "from BrmsRuleTableEntity where prodId = ? order by salience desc"; List<BrmsRuleTableEntity> ruleList = systemService.findHql(hqlForFirst, new Object[]{id}); String ruleId = null; if(!ruleList.isEmpty()){ ruleId = ruleList.get(0).getId(); } Map<String,String[][]> hm = processExcelService.grubDeciTableData(ruleId); String[][] heads = hm.get("head"); String[][] bodys = hm.get("body"); String typeStr = ""; int headRows = heads.length; for(int i = 0; i < heads[headRows-1].length;i++ ){ if("模型类型".equals(heads[headRows-1][i])||"贷款类型".equals(heads[headRows-1][i])){ typeStr = bodys[0][i]; break; } } log.info("模型类型:"+typeStr); int type = Integer.valueOf(typeStr); DecitabInvokerI antiFraudModelClient = DecitableInvokerFactroy.create(type); antiFraudModelClient.makeData(list, applicantMap,type); files = processExcelService.makeExcelForCompile(id); StatelessKieSession ks = factory.createKsession(files); returnStr = antiFraudModelClient.getPricingObj(ks, " "); RuleProdEntity prod = ruleProdService.getEntity(RuleProdEntity.class, id); prod.setStatus(Constants.PASS_TEST); ruleProdService.updateEntitie(prod); aj.setSuccess(true); aj.setObj(JSONObject.fromObject(returnStr)); for (File file : files) { if (file.exists()) file.delete(); } } catch (Exception e) { e.printStackTrace(); aj.setSuccess(false); aj.setMsg(e.getMessage()); }finally{ } return aj; } @RequestMapping(params = "prodPublish") @ResponseBody public AjaxJson prodPublish(String id,String pathstr,HttpServletRequest request){ AjaxJson aj = new AjaxJson(); try { RuleProdEntity prod = hotComplierService.getEntity(RuleProdEntity.class, id); if(Integer.valueOf(prod.getStatus())<Integer.valueOf(Constants.PASS_TEST)){ //e.printStackTrace(); aj.setSuccess(false); aj.setMsg("没有测试成功"); return aj; } List<Map<String,Object>> list = hotComplierService.hotcompiler(id); DynamicEngine de = DynamicEngine.getInstance(); StringBuilder sb = new StringBuilder(200); String mainPath = PathUtils.getClassesPath(); log.info("mainPath path:"+ mainPath); sb.append(mainPath.substring(0, mainPath.lastIndexOf("brms"))).append("deis") .append(File.separator).append("WEB-INF").append(File.separator).append("classes").append(File.separator); log.info("publish path:"+ sb.toString()); String tempPath = sb.toString(); //tempPath. if(StringUtils.isEmpty(pathstr)){ String[] paths = {sb.toString()}; makePublis(id, paths, list, de,mainPath,prod); }else{ String[] paths = pathstr.split("#"); makePublis(id, paths, list, de,mainPath,prod); } //ruleProdService.updateProductStatus(id, Constants.PUBLISH); prod.setStatus(Constants.PUBLISH); prod.setPublishStatus("1"); hotComplierService.updateEntitie(prod); aj.setSuccess(true); aj.setMsg("发布成功"); } catch (Exception e) { e.printStackTrace(); aj.setSuccess(false); aj.setMsg("发布错误"); } return aj; } private String makeBackupPath(RuleProdEntity prod){ List<TSTypegroup> groupList = ruleProdService.findHql("from TSTypegroup where typegroupcode = ?", "backupPath"); String path = Constants.BACKUP_PATH; StringBuilder sb = new StringBuilder(); if(groupList ==null || groupList.isEmpty()){ }else{ path = groupList.get(0).getTSTypes().get(0).getTypecode(); } sb.append(path).append(File.separator).append(ChineseToEnglish.getPingYin(prod.getName())).append(File.separator) .append(new SimpleDateFormat("yyyyMMdd_hhMMss").format(new Date())); return sb.toString(); } private void makePublis(String id, String[] paths, List<Map<String, Object>> list, DynamicEngine de,String mainPath,RuleProdEntity prod) throws Exception, IOException { //de.javaCodeCompile(list,mainPath); de.javaCodeToMap(list); String math = processExcelService.makeExcel(id,mainPath); String targetMath = math.replace("brms", "deis"); File file = new File(targetMath); if(!file.exists()){ file.mkdirs(); }else{ File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if(files[i].exists()) files[i].delete(); } } FileUtils.copyDirectory(new File(math), new File(targetMath)); String backupPath = makeBackupPath(prod); log.info("backup path:" +backupPath); File backup = new File(backupPath); if(!backup.exists()){ backup.mkdirs(); }else{ File[] files = backup.listFiles(); for (int i = 0; i < files.length; i++) { if(files[i].exists()) files[i].delete(); } } FileUtils.copyDirectory(new File(math), new File(backupPath)); } @RequestMapping(params = "showPublishPage") public ModelAndView showPublishPage(String id,String prodName,HttpServletRequest request) throws UnsupportedEncodingException{ request.setAttribute("id", id); request.setAttribute("prodName", prodName); return new ModelAndView("com/ifre/brms/showPublishPage"); } }
/* */ package datechooser.beans.editor.border.types; /* */ /* */ import datechooser.beans.locale.LocaleUtils; /* */ import java.awt.FlowLayout; /* */ import javax.swing.JLabel; /* */ import javax.swing.border.Border; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class NoBorderEditor /* */ extends AbstractBorderEditor /* */ { /* */ public NoBorderEditor() /* */ { /* 24 */ setCaption(LocaleUtils.getEditorLocaleString("No_borded")); /* 25 */ setLayout(new FlowLayout(1)); /* 26 */ add(new JLabel("x")); /* */ } /* */ /* */ protected Border getDefaultValue() { /* 30 */ return null; /* */ } /* */ /* */ protected void prepareSelection() { /* 34 */ this.value = null; /* */ } /* */ /* */ protected void refreshInterface() {} /* */ /* */ public void setCurrentBorder(Border border) /* */ { /* 41 */ this.value = null; /* */ } /* */ } /* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/beans/editor/border/types/NoBorderEditor.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
package com.danielgomez.archiver; /** * Fluent interface for building {@link CompressionOptions} */ public class CompressionOptionsBuilder extends IOOptionsBuilder<CompressionOptionsBuilder> { private int bufferSize = 1024 * 1024; private long maxFileSize = -1; private CompressionOptionsBuilder() { super();} public static CompressionOptionsBuilder create() { return new CompressionOptionsBuilder(); } public CompressionOptionsBuilder bufferSize( int bufferSize ) { this.bufferSize = bufferSize; return this; } public CompressionOptionsBuilder maxFileSize( long maxFileSize ) { this.maxFileSize = maxFileSize; return this; } @Override public CompressionOptions build() { return new CompressionOptions( input, output, bufferSize, maxFileSize ); } }
import edu.csc413.calculator.operators.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; public class OperatorTest { @Test public void createTest1(){ Operator su = Operator.create("+"); assertTrue(su instanceof AddOperator); } @Test public void createTest2(){ Operator su = Operator.create("-"); assertTrue(su instanceof SubtractOperator); } @Test public void createTest3(){ Operator su = Operator.create("*"); assertTrue(su instanceof MultiplyOperator); } @Test public void createTest4(){ Operator su = Operator.create("/"); assertTrue(su instanceof DivideOperator); } @Test public void createTest5(){ Operator su = Operator.create("^"); assertTrue(su instanceof PowerOperator); } @Test public void createTest6(){ Operator su = Operator.create("c"); assertTrue(su == null); } }
package testproj; import java.util.Date; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Sample { public WebDriver driver; @BeforeClass private void launchBrowser() { System.setProperty("webdriver.chrome.driver", "C:\\Users\\HOME\\eclipse-workspace\\ProjectClass\\Browser\\chromedriver.exe"); driver= new ChromeDriver(); driver.get("http://www.amazon.in"); driver.manage().window().maximize(); } @AfterClass private void quitebrowser() { driver.close(); } // @BeforeMethod // private void starttime() { // Date d=new Date(); // System.out.println(d); // } // // @AfterMethod // private void endtime() { // Date d= new Date(); // System.out.println(d); // } // @Test private void product() { driver.findElement(By.id("twotabsearchtextbox")).sendKeys("iphone"); driver.findElement(By.xpath("(//input[@type= \"submit\"])[1]")).click(); } @Test private void totalno() throws InterruptedException { List<WebElement> totalphone = driver.findElements(By.xpath("//span[contains(text(),'Apple iPhone')]")); System.out.println("Total number of phones " + totalphone.size()); Thread.sleep(3000); } @Test private void pricesort() throws InterruptedException { driver.findElement(By.xpath("//input[@id=\"low-price\"]")).sendKeys("50000"); Thread.sleep(3000); driver.findElement(By.xpath("(//span[@class=\"a-button-inner\"])[2]")).click(); } @Test private void topmobprice() { WebElement detailprice = driver.findElement(By.xpath("//span[contains(text(),\"Apple iPhone\")]")); detailprice.getAttribute("value"); } }
package com.tencent.mm.plugin.backup.bakoldlogic.bakoldpcui; import android.os.Bundle; import android.view.KeyEvent; import com.tencent.mm.R; import com.tencent.mm.plugin.backup.bakoldlogic.bakoldpcmodel.a; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMWizardActivity; public class BakConnErrorUI extends MMWizardActivity { private int haC; protected final int getLayoutId() { return R.i.bak_topc_error; } public void onCreate(Bundle bundle) { super.onCreate(bundle); if (!getIntent().getExtras().getBoolean("WizardRootKillSelf", false)) { this.haC = getIntent().getIntExtra("cmd", -1); x.i("MicroMsg.BakFinishUI", "BakConnErrorUI onCreate nowCmd:%d", new Object[]{Integer.valueOf(this.haC)}); initView(); a.asN().asO().gZU = -1; } } protected final void initView() { setMMTitle(R.l.bak_chat_to_pc_title); setBackBtn(new 1(this)); } public void onDestroy() { super.onDestroy(); a.asN().asO().gZM = null; x.i("MicroMsg.BakFinishUI", "BakConnErrorUI onDestroy nowCmd:%d", new Object[]{Integer.valueOf(this.haC)}); } public boolean onKeyDown(int i, KeyEvent keyEvent) { if (i != 4) { return super.onKeyDown(i, keyEvent); } DT(1); return true; } }
package fr.lteconsulting.formations; public enum Coup { Pierre { @Override public int battle( Coup other ) { switch( other ) { case Pierre: return 0; case Feuille: return -1; case Ciseau: return 1; } return 0; } }, Feuille { @Override public int battle( Coup other ) { switch( other ) { case Pierre: return 1; case Feuille: return 0; case Ciseau: return -1; } return 0; } }, Ciseau { @Override public int battle( Coup other ) { switch( other ) { case Pierre: return -1; case Feuille: return 1; case Ciseau: return 0; } return 0; } }; public abstract int battle( Coup other ); }
package com.ssm.wechatpro.service; import com.ssm.wechatpro.object.InputObject; import com.ssm.wechatpro.object.OutputObject; public interface WechatAdminUserMenuService { public void addUserMenu(InputObject inputObject,OutputObject outputObject) throws Exception; public void selectMenuByUserId(InputObject inputObject,OutputObject outputObject) throws Exception; public void deleteMenuByUserId(InputObject inputObject,OutputObject outputObject) throws Exception; }
package tech.sanan.fixtures; import tech.sanan.entity.User; import tech.sanan.enums.UserRoles; import tech.sanan.enums.UserTypes; import java.util.ArrayList; import java.util.List; public class UserFixtures { public static List<User> push() { String[] roles = { UserRoles.CREATOR, UserRoles.USER }; User user = new User(); user.setFirstname("Sanan"); user.setLastname("Ismailov"); user.setSex(1); user.setAge(27); user.setAddress("115404, Moscow, RU"); user.setRoles(roles); user.setEmail("mail@sanan.tech"); user.setType(UserTypes.EMPLOYEE); String[] roles2 = { UserRoles.CAT, UserRoles.USER }; User user1 = new User(); user1.setFirstname("Matilda"); user1.setLastname("Kotikova"); user1.setSex(2); user1.setAge(3); user1.setAddress("115404, Moscow, RU"); user1.setRoles(roles2); user1.setEmail("mur@sanan.tech"); user1.setType(UserTypes.EMPLOYEE); String[] roles3 = { UserRoles.TEST, UserRoles.USER }; User user2 = new User(); user2.setFirstname("User"); user2.setLastname("Test"); user2.setSex(1); user2.setAge(30); user2.setAddress("115404, Moscow, RU"); user2.setRoles(roles3); user2.setEmail("test@sanan.tech"); user2.setType(UserTypes.CLIENT); List<User> list = new ArrayList<>(); list.add(user); list.add(user1); list.add(user2); return list; } }
public class Resultado { public boolean resultado; public long idTrabajo; public Resultado (long id, boolean estado) { } }
package test.nz.org.take.compiler.scenario6.generated; /** * Class generated by the take compiler. * This class represents the predicate is_grandfather_of * @version Fri Feb 01 11:31:56 NZDT 2008 */ public class IsGrandfatherOf { public test.nz.org.take.compiler.scenario6.Person grandson; public test.nz.org.take.compiler.scenario6.Person grandfather; public IsGrandfatherOf( test.nz.org.take.compiler.scenario6.Person grandson, test.nz.org.take.compiler.scenario6.Person grandfather) { super(); this.grandson = grandson; this.grandfather = grandfather; } public IsGrandfatherOf() { super(); } }
package com.tt.miniapp.video.plugin.feature.loading; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.tt.miniapp.video.view.widget.RotateImageView; import com.tt.miniapphost.AppBrandLogger; import com.tt.miniapphost.util.UIUtils; public class VideoLoadingLayout { private boolean mIsFullscreen; private RotateImageView mLoadingLayout; private TextView mRetryBtn; private TextView mRetryTips; private View mRetryView; private View mRootView; public LoadingUIListener mUIListener; private void updateLoadingLayout(int paramInt1, int paramInt2) { RotateImageView rotateImageView = this.mLoadingLayout; if (rotateImageView == null) return; Context context = rotateImageView.getContext(); ViewGroup.LayoutParams layoutParams = this.mLoadingLayout.getLayoutParams(); if (layoutParams != null) { float f = paramInt1; layoutParams.width = (int)UIUtils.dip2Px(context, f); layoutParams.height = (int)UIUtils.dip2Px(context, f); this.mLoadingLayout.setLayoutParams(layoutParams); } this.mLoadingLayout.setImageResource(paramInt2); } private void updateRetryButton(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { TextView textView = this.mRetryBtn; if (textView == null) return; Context context = textView.getContext(); ViewGroup.LayoutParams layoutParams = this.mRetryBtn.getLayoutParams(); if (layoutParams != null) { layoutParams.width = (int)UIUtils.dip2Px(context, paramInt1); layoutParams.height = (int)UIUtils.dip2Px(context, paramInt2); this.mRetryBtn.setLayoutParams(layoutParams); } this.mRetryBtn.setTextSize(2, paramInt3); this.mRetryBtn.setBackgroundResource(paramInt4); } private void updateRetryTips(int paramInt1, int paramInt2) { TextView textView = this.mRetryTips; if (textView == null) return; Context context = textView.getContext(); this.mRetryTips.setTextSize(2, paramInt1); ViewGroup.LayoutParams layoutParams = this.mRetryTips.getLayoutParams(); if (layoutParams instanceof ViewGroup.MarginLayoutParams) { ((ViewGroup.MarginLayoutParams)layoutParams).bottomMargin = (int)UIUtils.dip2Px(context, paramInt2); this.mRetryTips.setLayoutParams(layoutParams); } } public void initView(Context paramContext, ViewGroup paramViewGroup) { if (paramContext != null) { if (paramViewGroup == null) return; LayoutInflater.from(paramContext).inflate(2097676336, paramViewGroup, true); this.mRootView = paramViewGroup.findViewById(2097545439); this.mLoadingLayout = (RotateImageView)this.mRootView.findViewById(2097545440); this.mRetryView = this.mRootView.findViewById(2097545441); this.mRetryView.setOnClickListener(new View.OnClickListener() { public void onClick(View param1View) { if (VideoLoadingLayout.this.mUIListener != null) VideoLoadingLayout.this.mUIListener.onRetryClick(); } }); this.mRetryTips = (TextView)this.mRootView.findViewById(2097545449); this.mRetryBtn = (TextView)this.mRootView.findViewById(2097545448); updateUi(); } } public void setFullscreen(boolean paramBoolean) { this.mIsFullscreen = paramBoolean; updateUi(); } public void setUIListener(LoadingUIListener paramLoadingUIListener) { this.mUIListener = paramLoadingUIListener; } public void showLoading(boolean paramBoolean) { byte b = 0; AppBrandLogger.d("tma_VideoLoadingLayout", new Object[] { "showLoading ", Boolean.valueOf(paramBoolean) }); UIUtils.setViewVisibility(this.mRetryView, 4); if (paramBoolean) { UIUtils.setViewVisibility((View)this.mLoadingLayout, 0); RotateImageView rotateImageView = this.mLoadingLayout; if (rotateImageView != null) rotateImageView.startAnimation(); } else { UIUtils.setViewVisibility((View)this.mLoadingLayout, 4); RotateImageView rotateImageView = this.mLoadingLayout; if (rotateImageView != null) rotateImageView.stopAnimation(); } View view = this.mRootView; if (!paramBoolean) b = 4; UIUtils.setViewVisibility(view, b); } public void showRetry(boolean paramBoolean) { byte b = 0; AppBrandLogger.d("tma_VideoLoadingLayout", new Object[] { "showRetry ", Boolean.valueOf(paramBoolean) }); UIUtils.setViewVisibility((View)this.mLoadingLayout, 4); if (paramBoolean) { UIUtils.setViewVisibility(this.mRetryView, 0); } else { UIUtils.setViewVisibility(this.mRetryView, 4); } View view = this.mRootView; if (!paramBoolean) b = 4; UIUtils.setViewVisibility(view, b); } public void updateUi() { if (this.mIsFullscreen) { updateLoadingLayout(60, 2097479810); updateRetryTips(18, 18); updateRetryButton(108, 42, 18, 2097479774); return; } updateLoadingLayout(44, 2097479809); updateRetryTips(14, 14); updateRetryButton(84, 32, 14, 2097479773); } static interface LoadingUIListener { void onRetryClick(); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\video\plugin\feature\loading\VideoLoadingLayout.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.cm4j.hotswap; import java.io.IOException; import java.lang.instrument.UnmodifiableClassException; import org.junit.Test; import com.cm4j.demo.util.DemoUtil; import com.cm4j.hotswap.agent.JavaAgent; import com.sun.tools.attach.AgentInitializationException; import com.sun.tools.attach.AgentLoadException; import com.sun.tools.attach.AttachNotSupportedException; /** * @author yeas.fun * @since 2021/11/4 */ public class JavaAgentTest { @Test public void javaAgentTest() throws UnmodifiableClassException, AgentLoadException, IOException, AttachNotSupportedException, ClassNotFoundException, AgentInitializationException { JavaAgent.javaAgent(new String[]{DemoUtil.class.getName()}); } }
package com.projects.houronearth.activities.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SectionIndexer; import android.widget.TextView; import com.projects.houronearth.R; import java.util.ArrayList; import java.util.List; /** * Created by krishna on 9/1/16. */ public class RemedyListAdapter extends RecyclerView.Adapter<RemedyListAdapter.ViewHolder> implements SectionIndexer { private static final String TAG = RemedyListAdapter.class.getSimpleName(); private final Context context; private LayoutInflater inflater; private ArrayList<String> remedyNames; private ArrayList<Integer> mSectionPositions; class ViewHolder extends RecyclerView.ViewHolder { private TextView textView; public ViewHolder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(R.id.textView); itemView.findViewById(R.id.lineDevider).setVisibility(View.VISIBLE); } } public RemedyListAdapter(Context context, ArrayList<String> remedyNames) { this.inflater = LayoutInflater.from(context); this.remedyNames = remedyNames; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.textview_layout, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.textView.setText(remedyNames.get(position)); } @Override public int getItemCount() { return remedyNames.size(); } @Override public int getSectionForPosition(int position) { return 0; } @Override public Object[] getSections() { List<String> sections = new ArrayList<>(26); mSectionPositions = new ArrayList<>(26); for (int i = 0, size = remedyNames.size(); i < size; i++) { String section = String.valueOf(remedyNames.get(i).charAt(0)).toUpperCase(); if (!sections.contains(section)) { sections.add(section); mSectionPositions.add(i); } } return sections.toArray(new String[0]); } @Override public int getPositionForSection(int sectionIndex) { return mSectionPositions.get(sectionIndex); } }
package com.zhouyi.business.core.model; import java.io.Serializable; import java.util.Date; public class NameInfo implements Serializable { private static final long serialVersionUID = 1L; private Long id; private SurnameInfo surnameInfo; // 姓氏详情 private CombineInfo combineInfo; // 用字组合详情 private String fullName; // 名字全称 private String surname; // 姓氏 private String combine; // 用字组合 private Long createBy; //创建者 private Date createTime; //创建日期 public NameInfo(String fullName) { this.fullName = fullName; } public NameInfo(String surname, String combine) { this.surname = surname; this.combine = combine; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public SurnameInfo getSurnameInfo() { return surnameInfo; } public void setSurnameInfo(SurnameInfo surnameInfo) { this.surnameInfo = surnameInfo; } public CombineInfo getCombineInfo() { return combineInfo; } public void setCombineInfo(CombineInfo combineInfo) { this.combineInfo = combineInfo; } public String getFullName() { if (fullName == null && surname != null && combine != null) { return surname + combine; } return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getCombine() { return combine; } public void setCombine(String combine) { this.combine = combine; } public Long getCreateBy() { return createBy; } public void setCreateBy(Long createBy) { this.createBy = createBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
package commandlineparser; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class StorageManager { private String file; private final List<Product> products = new ArrayList<>(); public String getFile() { return file; } public List<Product> getProducts() { return products; } public StorageManager(String file) throws NullPointerException { if (file == null) throw new NullPointerException("file"); this.file = file; ReadJsonStorage(file); } private void ReadJsonStorage(String url) { JSONParser parser = new JSONParser(); try (FileReader reader = new FileReader(url)) { JSONArray rawProducts = (JSONArray) parser.parse(reader); for (Object product : rawProducts) { JSONObject raw = (JSONObject) product; String name = raw.get("name").toString(); double price = Double.parseDouble(raw.get("price").toString()); int amount = Integer.parseInt(raw.get("amount").toString()); Product p = new Product(name, price, amount); products.add(p); } } catch (Exception e) { System.out.printf("Storage manager failed with exception: %s\n" + e.getMessage()); } } public Product CreateNewProduct(String name) { if (name == null) return null; Product product = new Product(name, 0, 0); getProducts().add(product); return product; } public Product FindProduct(String name) { if (name == null) return null; return getProducts().stream().filter(product -> product.getName().equals(name)).findFirst().orElse(null); } public boolean RemoveProduct(Product product) { if (product == null || !products.contains(product)) return false; products.remove(product); return true; } @SuppressWarnings("unchecked") public void SaveStorage() throws IOException { JSONArray raw = new JSONArray(); for (Product product: products) { JSONObject prodRaw = new JSONObject(); prodRaw.put("name", product.getName()); prodRaw.put("price", product.getPrice()); prodRaw.put("amount", product.getAmount()); raw.add(prodRaw); } try (FileWriter fileWriter = new FileWriter(getFile())) { fileWriter.write(raw.toJSONString()); } } }
package me.hch; import java.io.*; /** * Created by Administrator on 14-4-12. */ public class FileUtils { public static String getFileContent(String fileName) throws IOException { InputStream is = FileUtils.class.getResourceAsStream("/" + fileName); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = bis.read()) != -1) { baos.write(b); } return baos.toString(); } public static void dump(String fileName, String content) { try { BufferedWriter bw = new BufferedWriter( new FileWriter(fileName) ); bw.write(content); bw.flush(); bw.close(); } catch (IOException e) { throw new WsClientException(e); } } }
/* Object:是所有对象的直接或者间接父类,传说中的上帝 该类中定义的肯定是所有对象都具备的功能。 Object类中已经提供了对 对象是否相同的比较方法 如果自定义类中也有比较相同的功能,没有必要重新定义。 只要沿袭父类中的功能,建立自己特有的比较内容即可;即覆盖Object的equals方法 */ class Demo{ // extends Object private int num; Demo(int num){ this.num = num; } // 覆盖Object的equals方法,个性化 public boolean equals(Object obj){ // 所有类向上转型为Object(Obejct obj = new Demo();), // 而Object中没有num if (!(obj instanceof Demo)){ return false; } Demo d = (Demo)obj; return this.num == d.num; } // 覆盖Object的toString方法,个性化 // public String toString(){ // return "demo:" + this.num; // } } class ObjectDemo{ public static void main(String[] args){ Demo a = new Demo(3); System.out.println(a.toString()); Demo b = new Demo(4); System.out.println(b.toString()); System.out.println(a.equals(b)); System.out.println(a.getClass()); Class c = a.getClass(); System.out.println(c.getName()); System.out.println(c.getMethods()); System.out.println(Integer.toHexString(a.hashCode())); // 获得对象的哈希值(内存地址)并转为16进制 System.out.println(a.toString()); // 默认的 // Object 默认的 toString 的实现 System.out.println(c.getName() + "@@" + Integer.toHexString(a.hashCode())); } }
package ro.redeul.google.go.lang.psi; import ro.redeul.google.go.lang.psi.toplevel.GoFunctionDeclaration; public class GoPsiFunctionTestCase extends AbstractGoPsiTestCase { public void testNoParams() { GoFile file = get(parse("package main; func a() { }")); GoFunctionDeclaration func = get(file.getFunctions(), 0); assertEquals(func.getParameters().length, 0); } public void testOneParam() { GoFile file = get(parse("package main; func a(a int) { }")); GoFunctionDeclaration func = get(file.getFunctions(), 0); assertEquals(func.getParameters().length, 1); } public void testOneParamVariadic() { GoFile file = get(parse("package main; func a(a ...int) { }")); GoFunctionDeclaration func = get(file.getFunctions(), 0); assertEquals(func.getParameters().length, 1); } }
package com.cnk.travelogix.custom.ziffm.vendor.createchange; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; import com.cnk.travelogix.sapintegrations.dto.factory.DTOObjectFactory; /** * This object contains factory methods for each Java content interface and Java element interface generated in the * com.cnk.travelogix.custom.order.createupdate package. * <p> * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content. * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in * this class. * */ @XmlRegistry public class ObjectFactory implements DTOObjectFactory { private final static QName _ZiffmVendorCreateChange_QNAME = new QName("urn:sap-com:document:sap:soap:functions:mc-style", "ZVendorCreateChangeService"); private final static QName _ZiffmVendorCreateChangeResponse_QNAME = new QName( "urn:sap-com:document:sap:soap:functions:mc-style", "ZVendorCreateChangeServiceResponse"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: * com.cnk.travelogix.custom.order.createupdate * */ public ObjectFactory() { } /** * Create an instance of {@link ZVendorCreateChangeServiceResponse } * */ public ZVendorCreateChangeServiceResponse createZVendorCreateChangeServiceResponse() { return new ZVendorCreateChangeServiceResponse(); } @XmlElementDecl(namespace = "urn:sap-com:document:sap:soap:functions:mc-style", name = "ZVendorCreateChangeServiceResponse") public JAXBElement<ZVendorCreateChangeServiceResponse> createZVendorCreateChangeServiceResponse( final ZVendorCreateChangeServiceResponse value) { return new JAXBElement<ZVendorCreateChangeServiceResponse>(_ZiffmVendorCreateChangeResponse_QNAME, ZVendorCreateChangeServiceResponse.class, null, value); } /** * Create an instance of {@link ZifttStatusDoc } * */ public ZifttStatusDoc createZifttStatusDoc() { return new ZifttStatusDoc(); } /** * Create an instance of {@link ZVendorCreateChangeService } * */ public ZVendorCreateChangeService createZVendorCreateChangeService() { return new ZVendorCreateChangeService(); } @XmlElementDecl(namespace = "urn:sap-com:document:sap:soap:functions:mc-style", name = "ZVendorCreateChangeService") public JAXBElement<ZVendorCreateChangeService> createZVendorCreateChangeService(final ZVendorCreateChangeService value) { return new JAXBElement<ZVendorCreateChangeService>(_ZiffmVendorCreateChange_QNAME, ZVendorCreateChangeService.class, null, value); } /** * Create an instance of {@link ZvendorInput } * */ public ZvendorInput createZvendorInput() { return new ZvendorInput(); } /** * Create an instance of {@link ZifstStatusDoc } * */ public ZifstStatusDoc createZifstStatusDoc() { return new ZifstStatusDoc(); } /** * Create an instance of {@link ZbankDetailTt } * */ public ZbankDetailTt createZbankDetailTt() { return new ZbankDetailTt(); } /** * Create an instance of {@link ZbankDetail } * */ public ZbankDetail createZbankDetail() { return new ZbankDetail(); } }
package com.cts.projectManagement.model; public class AddTaskRequest { private Long taskId; private Long parentId; private Long userId; private String task; private Long projectId; private int priority; private String status; private String startDate; private String endDate; public Long getTaskId() { return taskId; } public void setTaskId(Long taskId) { this.taskId = taskId; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getTask() { return task; } public void setTask(String task) { this.task = task; } public Long getProjectId() { return projectId; } public void setProjectId(Long projectId) { this.projectId = projectId; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public AddTaskRequest(Long taskId, Long parentId, Long userId, String task, Long projectId, int priority, String status, String startDate, String endDate) { super(); this.taskId = taskId; this.parentId = parentId; this.userId = userId; this.task = task; this.projectId = projectId; this.priority = priority; this.status = status; this.startDate = startDate; this.endDate = endDate; } }
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; 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 com.bookshelf.implementations.BooksDAOImpl; import com.bookshelf.model.Books; @WebServlet("/TodaysSpecial") public class TodaysSpecial extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BooksDAOImpl bl=new BooksDAOImpl(); List<Books> l=new ArrayList<Books>(); PrintWriter out=response.getWriter(); try { l=bl.extractTodaysSpecial(); } catch (Exception e) { e.printStackTrace(); } } }
package form; import java.util.Map; import model.Approver; import model.TrainingActivity; import model.User; 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.SuspendNotAllowedException; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Button; import org.zkoss.zul.Combobox; import org.zkoss.zul.Datebox; import org.zkoss.zul.Hbox; import org.zkoss.zul.Include; import org.zkoss.zul.Label; import org.zkoss.zul.Listbox; import org.zkoss.zul.Textbox; import org.zkoss.zul.Vbox; import org.zkoss.zul.Window; import constant.DocTypeConstant; import constant.ErrorTypeConstant; import constant.ReqStatusConstant; import db.HibernateUtil; import services.GeneralService; import services.LeaveService; import services.TrainingActivityService; import util.MessageUtil; import util.SessionUtil; import util.ZKUtil; public class TrainingActivityForm extends GenericForwardComposer{ Window winLookupEvent; Button btnLookupEvent; Textbox txEventDesc,txEventId,txDesc; Label lbTrainingDesc,lbTrainingLocation,lbTrainer; Datebox dActivityDate; //general component yang kebanyakan dipakai di hampir semua form Include content = (Include) Path.getComponent("//main/content"); Button btnSave,btnCancel,btnBack,btnApprove,btnReject; Combobox cbApprover; Vbox vRemark; Textbox txApproverRemark; Listbox infoBox; //untuk cc Hbox hCC; Textbox txCC; Button btnCC; Window winLookupCCEmail; //------------------------------------------------------------- TrainingActivity ta; User u; String reqId,userType,reqStatus; Boolean isApproverManual; public void doAfterCompose(Component win) throws Exception{ super.doAfterCompose(win); getDataFromSession(); getParameters(); if(reqId.isEmpty()){ initScreen(); ZKUtil.renderInfoBox(infoBox, DocTypeConstant.TRAINING_ACTIVITY, u.getEmpNo()); } else{ getDataForView(); initScreenForView(); } } private void initScreenForView() { // TODO Auto-generated method stub //men disabled form dActivityDate.setDisabled(true); txDesc.setReadonly(true); btnLookupEvent.setVisible(false); //mengisi form Map<String,String> eventDetail = TrainingActivityService.getEventDetail(ta.getTrainingId()); lbTrainingDesc.setValue(eventDetail.get("TrainingDesc")); lbTrainingLocation.setValue(eventDetail.get("LocationDesc")); lbTrainer.setValue(eventDetail.get("HeldBy")); txEventDesc.setValue(eventDetail.get("TrainingDesc")); dActivityDate.setValue(ta.getDate()); txDesc.setValue(ta.getDesc()); //men setting component2 untuk view btnSave.setVisible(false); btnBack.setVisible(true); hCC.setVisible(false); if(reqStatus.equals("active")){ if(userType.equals("requester")){ btnCancel.setVisible(true); } else if(userType.equals("approver")){ btnApprove.setVisible(true); btnReject.setVisible(true); vRemark.setVisible(true); } } } private void getDataForView() { // TODO Auto-generated method stub ta = TrainingActivityService.getTrainingActivityByRequestId(reqId); } private void initScreen() { // TODO Auto-generated method stub isApproverManual = GeneralService.getApproverValidation(DocTypeConstant.TRAINING_ACTIVITY); if(isApproverManual){ cbApprover.setVisible(true); ZKUtil.createComboApproverManual(cbApprover, u.getEmpNo(), DocTypeConstant.TRAINING_ACTIVITY); } } private void getParameters() { reqId = ""; userType = ""; reqStatus = ""; String[] tmpReqId = (String[]) param.get("reqId"); String[] tmpUserType = (String[]) param.get("userType"); String[] tmpReqStatus = (String[]) param.get("reqStatus"); if(tmpReqId != null) reqId = tmpReqId[0]; if(tmpUserType != null) userType = tmpUserType[0]; if(tmpReqStatus != null) reqStatus = tmpReqStatus[0]; } private void getDataFromSession() { u = SessionUtil.getUser(); } public void onClick$btnLookupEvent(){ if(winLookupEvent == null){ winLookupEvent = (Window) Executions.createComponents("WEB-INF/content/lookup/lookup-active-training.zul", null, null); } try { winLookupEvent.doModal(); } catch (SuspendNotAllowedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } String eventId = (String) winLookupEvent.getAttribute("resultId"); String eventDesc = (String) winLookupEvent.getAttribute("resultDesc"); if(eventId == null || eventId.isEmpty()) return; txEventDesc.setValue(eventDesc); txEventId.setValue(eventId); Map<String,String> eventDetail = TrainingActivityService.getEventDetail(eventId); lbTrainingDesc.setValue(eventDetail.get("TrainingDesc")); lbTrainingLocation.setValue(eventDetail.get("LocationDesc")); lbTrainer.setValue(eventDetail.get("HeldBy")); } public void onClick$btnSave(){ //validasi screen by program if (!validateScreen()) return; Approver approver = null; //mengambil data dari form ta = new TrainingActivity(); ta.setTrainingId(txEventId.getValue()); ta.setDate(dActivityDate.getValue()); ta.setDesc(txDesc.getValue()); //validasi by sp String errMesage = TrainingActivityService.validateRequest(ta,u.getEmpNo()); if(!errMesage.isEmpty()){ MessageUtil.errorDialog(errMesage); return; } //validasi kepastian dari user Boolean sure = MessageUtil.confirmation(MessageUtil.getConfirmationRequestMessage()); if(!sure) return; //save String reqId = GeneralService.getRequestId(u.getEmpNo(), DocTypeConstant.TRAINING_ACTIVITY); Session s = HibernateUtil.getSessionFactory().openSession(); try{ if(isApproverManual){ if(cbApprover.getSelectedIndex() == 0){ MessageUtil.errorDialog("Select Your Approver"); return; } String approverId = cbApprover.getSelectedItem().getValue(); GeneralService.saveApproverManual(u.getEmpNo(),approverId,DocTypeConstant.TRAINING_ACTIVITY,s); } approver = GeneralService.getApprover(u.getEmpNo(), DocTypeConstant.TRAINING_ACTIVITY, reqId, s); s.beginTransaction(); TrainingActivityService.sentRequest(ta, u.getEmpNo(), reqId, s); GeneralService.saveRequestHistory(reqId, u.getEmpNo(), approver.getId(), DocTypeConstant.TRAINING_ACTIVITY, s); s.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); s.getTransaction().rollback(); MessageUtil.errorDialog("Sent failed"); } finally{ s.close(); } Boolean isEmailsuccess = GeneralService.saveEmailFromRequester(reqId,u.getEmpNo(),approver.getId(),txCC.getValue(),DocTypeConstant.TRAINING_ACTIVITY); String message = "Success sent request to\n"+approver.getFullName(); if(!isEmailsuccess){ message += "\nbut sent email failed"; } MessageUtil.information(message); Executions.sendRedirect("Main.zul"); } private boolean validateScreen() { if(txEventId.getValue().isEmpty()){ MessageUtil.errorDialog("Select Active Training"); return false; } if(dActivityDate.getValue() == null){ MessageUtil.errorDialog("Select Activity Date"); return false; } if(txDesc.getValue().isEmpty()){ MessageUtil.errorDialog("Fill Activity Description"); return false; } return true; } public void onClick$btnApprove(){ Boolean sure = MessageUtil.confirmation(MessageUtil.getConfirmationApproveMessage()); if(!sure) return; String remark = txApproverRemark.getValue(); String requester = GeneralService.getRequesterByReqId(reqId); //jika requester tidak ada maka prosses approve tidak akan dijalankan if(requester.isEmpty()){ MessageUtil.errorDialog("Approved failed, requester not found"); return; } try{ int errorStatus = GeneralService.updateRequestStatus(reqId, ReqStatusConstant.APPROVED, u.getEmpNo(), remark, u.getEmpNo()); if (errorStatus != ErrorTypeConstant.NO_ERROR){ MessageUtil.errorDialog(ErrorTypeConstant.getMessage(errorStatus)); content.setSrc("WEB-INF/content/approval.zul"); } Boolean isReadyProcess = GeneralService.getReadyProcessStatus(reqId); if(isReadyProcess){ //save request String errMessage = TrainingActivityService.approveSingleRequest(reqId); if(errMessage!= null && !errMessage.isEmpty()){ MessageUtil.errorDialog("Error at approving"); // system.out.println(errMessage); return; } } } catch (Exception e) { e.printStackTrace(); MessageUtil.errorDialog("Approve request failed"); return; } MessageUtil.information("Approving success"); content.setSrc("WEB-INF/content/approval.zul"); } public void onClick$btnReject(){ Boolean sure = MessageUtil.confirmation(MessageUtil.getConfirmationRejectRequest()); if(!sure) return; String remark = txApproverRemark.getValue(); try{ //save request int errorStatus = GeneralService.updateRequestStatus(reqId, ReqStatusConstant.REJECTED, u.getEmpNo(), remark, u.getEmpNo()); if (errorStatus != ErrorTypeConstant.NO_ERROR){ MessageUtil.errorDialog(ErrorTypeConstant.getMessage(errorStatus)); content.setSrc("WEB-INF/content/approval.zul"); } MessageUtil.information("Request has been rejected"); } catch (Exception e) { e.printStackTrace(); MessageUtil.errorDialog("Reject request failed"); return; } content.setSrc("WEB-INF/content/approval.zul"); } public void onClick$btnCancel(){ Boolean sure = MessageUtil.confirmation(MessageUtil.getConfirmationCancelRequest()); if(!sure) return; try{ //save request GeneralService.updateRequestStatus(reqId, ReqStatusConstant.CANCELED, "", "", u.getEmpNo()); MessageUtil.information("Request has been canceled"); } catch (Exception e) { e.printStackTrace(); MessageUtil.errorDialog("Cancel request failed"); return; } content.setSrc("WEB-INF/content/request-history.zul"); } public void onClick$btnBack(){ if(userType.equals("approver")){ content.setSrc("WEB-INF/content/approval.zul"); } else if(userType.equals("requester")){ content.setSrc("WEB-INF/content/request-history.zul"); } } public void onClick$btnCC(){ if(winLookupCCEmail == null){ winLookupCCEmail = (Window) Executions.createComponents("WEB-INF/content/lookup/lookupCC.zul", null, null); winLookupCCEmail.setClosable(false); } try { winLookupCCEmail.doModal(); } catch (SuspendNotAllowedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } String cc = (String) winLookupCCEmail.getAttribute("CC"); txCC.setValue(cc); } }
package com.stem.wechat.bean; import java.io.Serializable; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="xml") public class OutMessage implements Serializable{ private String ToUserName; private String FromUserName; private Long CreateTime; public OutMessage(){ } public String getToUserName(){ return ToUserName; } public void setToUserName(String toUserName){ ToUserName = toUserName; } public String getFromUserName(){ return FromUserName; } public void setFromUserName(String fromUserName){ FromUserName = fromUserName; } public Long getCreateTime(){ return CreateTime; } public void setCreateTime(Long createTime){ CreateTime = createTime; } }
package com.imwj.tmall.pojo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import javax.persistence.*; /** * @author langao_q * @create 2019-12-02 16:12 */ @Data @Entity @Table(name = "user") @JsonIgnoreProperties({ "handler","hibernateLazyInitializer" }) public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int id; @Column(name = "name") private String name; @Column(name = "password") private String password; @Column(name = "salt") private String salt; @Transient private String anonymousName; public String getAnonymousName(){ if(null != anonymousName){ return anonymousName; } if(null == name){ anonymousName = null; }else if(name.length() <= 1){ anonymousName = "*"; }else if(name.length() == 2){ anonymousName = name.substring(0,1) + "*"; }else{ char[] chars = name.toCharArray(); for(int i=1; i < chars.length-1; i++){ chars[i] = '*'; anonymousName = new String(chars); } } return anonymousName; } }
package com.udacity.gradle.builditbigger.api; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.view.View; import android.widget.ProgressBar; import com.example.joketelling.backend.myApi.MyApi; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.joketelling.JokeActivity; import com.udacity.gradle.builditbigger.R; import java.io.IOException; /** * Created by gishiru on 2016/01/01. */ public class EndpointsAsyncTask extends AsyncTask<Context, Void, String> { private static final String URL_ROOT = "http://10.0.2.4:8080/_ah/api/"; // Localhost's IP address. private EndpointsAsyncTaskListener mListener = null; private MyApi mMyApi = null; private Context mContext = null; private ProgressBar mSpinner = null; public EndpointsAsyncTask(Activity activity) { super(); if (activity != null) { mSpinner = (ProgressBar)activity.findViewById(R.id.progress); } } @Override protected void onPreExecute() { super.onPreExecute(); if (mSpinner != null) { mSpinner.setVisibility(View.VISIBLE); } } @Override protected String doInBackground(Context... contexts) { if (mMyApi == null) { MyApi.Builder myApiBuilder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null) .setRootUrl(URL_ROOT) .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() { @Override public void initialize(AbstractGoogleClientRequest<?> request) throws IOException { request.setDisableGZipContent(true); // Turn off compression when running against // local devappserver. } }); mMyApi = myApiBuilder.build(); } mContext = contexts[0]; try { return mMyApi.sayJoke().execute().getData(); } catch (IOException e) { return e.getMessage(); } } @Override protected void onPostExecute(String s) { super.onPostExecute(s); if (mSpinner != null) { mSpinner.setVisibility(View.GONE); } if (mListener != null) { mListener.onCompleted(s); } else { // Start activity and pass a joke. Intent intent = new Intent(mContext, JokeActivity.class); intent.putExtra(JokeActivity.EXTRA_KEY_JOKE, s); mContext.startActivity(intent); // Calling this in android test causes runtime exception. } } public EndpointsAsyncTask setListener(EndpointsAsyncTaskListener listener) { mListener = listener; return this; } public interface EndpointsAsyncTaskListener { void onCompleted(String joke); } }
package com.huawei.cloudstorage.dal.modelDo; import java.util.Date; public class UserInfo { private Integer id; private String userId; private String loginNameEmail; private String loginNameMobile; private String loginPassword; private String paymentPassword; private String nickName; private String realName; private String certType; private String certNo; private String state; private String address; private String nativePlace; private String phone; private String mobileNo; private String email; private Date birthdate; private String constellation; private Short age; private Integer income; private Short height; private Short weight; private String job; private String interest; private String introduce; private String note; private Date gmtFirst; private Date gmtCreate; private Date gmtModify; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId == null ? null : userId.trim(); } public String getLoginNameEmail() { return loginNameEmail; } public void setLoginNameEmail(String loginNameEmail) { this.loginNameEmail = loginNameEmail == null ? null : loginNameEmail.trim(); } public String getLoginNameMobile() { return loginNameMobile; } public void setLoginNameMobile(String loginNameMobile) { this.loginNameMobile = loginNameMobile == null ? null : loginNameMobile.trim(); } public String getLoginPassword() { return loginPassword; } public void setLoginPassword(String loginPassword) { this.loginPassword = loginPassword == null ? null : loginPassword.trim(); } public String getPaymentPassword() { return paymentPassword; } public void setPaymentPassword(String paymentPassword) { this.paymentPassword = paymentPassword == null ? null : paymentPassword.trim(); } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName == null ? null : nickName.trim(); } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName == null ? null : realName.trim(); } public String getCertType() { return certType; } public void setCertType(String certType) { this.certType = certType == null ? null : certType.trim(); } public String getCertNo() { return certNo; } public void setCertNo(String certNo) { this.certNo = certNo == null ? null : certNo.trim(); } public String getState() { return state; } public void setState(String state) { this.state = state == null ? null : state.trim(); } public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } public String getNativePlace() { return nativePlace; } public void setNativePlace(String nativePlace) { this.nativePlace = nativePlace == null ? null : nativePlace.trim(); } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } public String getMobileNo() { return mobileNo; } public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo == null ? null : mobileNo.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public Date getBirthdate() { return birthdate; } public void setBirthdate(Date birthdate) { this.birthdate = birthdate; } public String getConstellation() { return constellation; } public void setConstellation(String constellation) { this.constellation = constellation == null ? null : constellation.trim(); } public Short getAge() { return age; } public void setAge(Short age) { this.age = age; } public Integer getIncome() { return income; } public void setIncome(Integer income) { this.income = income; } public Short getHeight() { return height; } public void setHeight(Short height) { this.height = height; } public Short getWeight() { return weight; } public void setWeight(Short weight) { this.weight = weight; } public String getJob() { return job; } public void setJob(String job) { this.job = job == null ? null : job.trim(); } public String getInterest() { return interest; } public void setInterest(String interest) { this.interest = interest == null ? null : interest.trim(); } public String getIntroduce() { return introduce; } public void setIntroduce(String introduce) { this.introduce = introduce == null ? null : introduce.trim(); } public String getNote() { return note; } public void setNote(String note) { this.note = note == null ? null : note.trim(); } public Date getGmtFirst() { return gmtFirst; } public void setGmtFirst(Date gmtFirst) { this.gmtFirst = gmtFirst; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModify() { return gmtModify; } public void setGmtModify(Date gmtModify) { this.gmtModify = gmtModify; } }
package WinGame; import java.util.ArrayList; public class Player { private String name; private Piece piece; private int material; private ArrayList<Biome> Biomes; Player(String nameSet){ setName(nameSet); } private void setName(String nameSet) { this.name = nameSet; } public void setPiece(Piece piece) { this.piece = piece; } public String getName() { return name; } public Piece getPiece() { return this.piece; } public void setMaterial(int materials) {this.material = materials;} public int getMaterial() {return this.material;} public void setBiomes(ArrayList<Biome> biome) {this.Biomes = biome;} public ArrayList<Biome> getBiomes() {return this.Biomes;} }
package com.geektech.beerapp.presentation.beers; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.geektech.beerapp.R; import com.geektech.beerapp.model.BeerEntity; import java.util.List; public class BeersFragment extends Fragment implements IBeersContract.View { private IBeersContract.Presenter mPresenter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate ( R.layout.fragment_beers, container, false ); return view; } @Override public void showBeers(List<BeerEntity> beers) { } @Override public void openBeerDetails(int id) { } @Override public void attachPresenter(IBeersContract.Presenter presenter) { mPresenter = presenter; } @Override public void finishView() { } }
package it.unica.pr2.risorseWeb; import java.util.*; import java.io.*; import java.lang.*; public class RisorsaWeb extends File { String contenuto; String nome; public RisorsaWeb(String nome, String contenuto){ super(nome, contenuto); this.nome = nome; this.contenuto = contenuto; } public RisorsaWeb(String a){ super(a); this.nome=a; } public String getNome(){ return this.nome; } public String getContenuto(){ return this.contenuto; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package logica; /** * * @author root */ public class TPersonalizada { int tarjeta_id; int saldo; int avances_disponibles; public void TPersonalizada(int tarjeta_id, int saldo, int avances_disponibles){ this.tarjeta_id = tarjeta_id; this.saldo = saldo; this.avances_disponibles = avances_disponibles; } public int getTarjeta_id(){ return tarjeta_id; } public int getSaldo(){ return saldo; } public int avancesDisponibles(){ return avances_disponibles; } public void setTarjeta_id(int tarjeta_id){ this.tarjeta_id = tarjeta_id; } public void setSaldo(int saldo){ this.saldo = saldo; } public void setAvances_disponibles(int avances){ this.avancesDisponibles = avances; } }
package io.meksula.persister.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.Set; public interface TransformationRepository extends JpaRepository<TransformationEntity, Long> { @Query("select distinct t.hostname from TransformationEntity t") Set<String> findAllHostnames(); }
package com.udacity.popularmovies.database; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "movie") public class MovieEntry { @PrimaryKey private final int id; private final String title; @ColumnInfo(name = "movie_poster") private final String moviePoster; @ColumnInfo(name = "plot_synopsis") private final String plotSynopsis; @ColumnInfo(name = "user_rating") private final String userRating; @ColumnInfo(name = "release_date") private final String releaseDate; public MovieEntry(int id, String title, String moviePoster, String plotSynopsis, String userRating, String releaseDate) { this.id = id; this.title = title; this.moviePoster = moviePoster; this.plotSynopsis = plotSynopsis; this.userRating = userRating; this.releaseDate = releaseDate; } public int getId() { return id; } public String getTitle() { return title; } public String getMoviePoster() { return moviePoster; } public String getPlotSynopsis() { return plotSynopsis; } public String getUserRating() { return userRating; } public String getReleaseDate() { return releaseDate; } }
package com.accp.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.accp.entity.SysUsers; import com.alibaba.fastjson.JSON; @Controller @RequestMapping("/authc") public class AuthcController { @RequestMapping("/loginAjax") @ResponseBody public Object loginAjax(@RequestBody SysUsers sysUsers, HttpSession session) { SysUsers sysUser; try { System.out.println("sysUsers: " + JSON.toJSONString(sysUsers)); UsernamePasswordToken token = new UsernamePasswordToken(sysUsers.getUsername(), sysUsers.getPassword()); Subject subject = SecurityUtils.getSubject(); subject.login(token); sysUser = (SysUsers) SecurityUtils.getSubject().getPrincipal(); Map<String, Object> map = new HashMap<String, Object>(); map.put("user", sysUser); map.put("token", session.getId()); return map; } catch (AuthenticationException e) { // TODO Auto-generated catch block e.printStackTrace(); return "0000"; } } }
/* * Copyright (C) 2015 Miquel Sas * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.qtplaf.library.ai.function; /** * Interface used to calculate the error value for an error vector and accumulate it to register the total error in an * iteration learning method. * * @author Miquel Sas */ public interface IterationError { /** * Returns the total network error. * * @return The total network error. */ double getTotalError(); /** * Returns the error value given a list of output errors, an error vector. * * @param errorVector The error values. * @return The error value. */ double getError(double[] errorVector); /** * Adds the error to the total network error. * * @param error The error to accumulate. */ void addError(double error); /** * Reset the total error setting it to zero. */ void reset(); }
package problema; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.Scanner; import modelo.Cliente; import modelo.Deposito; import modelo.Problema; import modelo.Solucao; import modelo.Veiculo; public class Main { public static Scanner in = new Scanner(System.in); public static int qtdIndividuo; public static Problema problema; public static void main(String[] args){ LeInstancias leitor = new LeInstancias(); CalculaDistancia calcDistancia = new CalculaDistancia(); Clustering clustering = new Clustering(); try { problema = leitor.leDat("instancias/p01"); double[][] matrizDC = calcDistancia.calculaDistanciaClienteDeposito(problema); double[][] matrizCC = calcDistancia.calculaDistanciaClienteCliente(problema); calcDistancia.imprimeDistancias(matrizDC, matrizCC); clustering.clustering(matrizDC, problema); clustering.imprimeClusters(problema); System.out.println("Informe o número de indivíduos da população:"); qtdIndividuo = in.nextInt(); ArrayList<Solucao> solucoes = new ArrayList(); for(Solucao s: solucoes) { LinkedList<Cliente> clientes = new LinkedList<Cliente>(); s.setDepositos(problema.getDepositos()); for(Deposito d: s.getDepositos()) { Collections.shuffle(d.getClientes()); d.setClientes(new LinkedList<Cliente>()); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public LinkedList<Cliente> geraRotas(ArrayList<Deposito> depositos){ LinkedList<Cliente> clientes = new LinkedList<Cliente>(); ArrayList<Veiculo> veiculos = problema.getVeiculos(); Collections.sort(veiculos); Collections.sort(depositos); //atribui veículo for (Deposito d: depositos) { clientes = d.getClientes();//deposito de menor demanda d.setVeiculoEscolhido(veiculos.get(0));// veiculo de menor capacidade veiculos.remove(0); } //cria rota for (Deposito d: depositos) { double capacidadeAtingida = 0; clientes = d.getClientes();//deposito de menor demanda Collections.shuffle(clientes); for (Cliente c: clientes) { capacidadeAtingida += c.getDemanda(); if(capacidadeAtingida <= d.getVeiculoEscolhido().getCarga_maxima()) { //adiciona o cliente na rota }else { //adiciona o deposito na rota e zera a capacidade } } } return clientes; } }
package com.tencent.mm.plugin.qqmail.ui; import com.tencent.mm.R; import com.tencent.mm.pluginsdk.model.app.g; class ReadMailUI$6 implements Runnable { final /* synthetic */ ReadMailUI miD; ReadMailUI$6(ReadMailUI readMailUI) { this.miD = readMailUI; } public final void run() { g.a(this.miD, this.miD.getPackageManager().getLaunchIntentForPackage("com.tencent.androidqqmail"), this.miD.getString(R.l.chatfooter_mail_without_unread_count), null); } }
package thsst.calvis.configuration.model.errorlogging; /** * Created by Ivan on 1/29/2016. */ public enum RegisterMissing{ missingSourceRegister, missingNewRegister, missingRegisterSize, missingRegisterType, missingRegisterStartIndex, missingRegisterEndIndex }
package br.com.divulgatudo.sistemadecadastrodeanuncios.teste; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import br.com.divulgatudo.sistemadecadastrodeanuncios.modelo.Anuncio; import br.com.divulgatudo.sistemadecadastrodeanuncios.modelo.BancoDeAnuncios; /** * Classe que testa o cadastramento e a busca de anuncios * * @author Samuel Cardoso de Oliveira * */ public class TesteAnuncio { public static void main(String[] args) { Date dataDeInicio = null; Date dataDeTermino = null; Date dataDeInicio2 = null; Date dataDeTermino2 = null; Date dataDeInicio3 = null; Date dataDeTermino3 = null; Date dataDeInicio4 = null; Date dataDeTermino4 = null; /** * Cadastro das datas de inicio e de termino do primeiro anuncio * */ String dataInicial = "05/05/2021"; try { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); dataDeInicio = sdf.parse(dataInicial); } catch (ParseException e) { e.printStackTrace(); } String dataFinal = "06/05/2021"; try { SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy"); dataDeTermino = sdf1.parse(dataFinal); } catch (ParseException e) { e.printStackTrace(); } /** * Cadastro das datas de inicio e de termino do segundo anuncio * */ String dataInicial2 = "08/06/2021"; try { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); dataDeInicio2 = sdf.parse(dataInicial2); } catch (ParseException e) { e.printStackTrace(); } String dataFinal2 = "10/07/2021"; try { SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy"); dataDeTermino2 = sdf1.parse(dataFinal2); } catch (ParseException e) { e.printStackTrace(); } /** * Cadastro das datas de inicio e de termino do terceiro anuncio * */ String dataInicial3 = "20/07/2021"; try { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); dataDeInicio3 = sdf.parse(dataInicial3); } catch (ParseException e) { e.printStackTrace(); } String dataFinal3 = "30/08/2021"; try { SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy"); dataDeTermino3 = sdf1.parse(dataFinal3); } catch (ParseException e) { e.printStackTrace(); } /** * Cadastro das datas de inicio e de termino do quarto anuncio * */ String dataInicial4 = "02/08/2021"; try { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); dataDeInicio4 = sdf.parse(dataInicial4); } catch (ParseException e) { e.printStackTrace(); } String dataFinal4 = "02/10/2021"; try { SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy"); dataDeTermino4 = sdf1.parse(dataFinal4); } catch (ParseException e) { e.printStackTrace(); } /** * Cadastro do primeiro anuncio (nome do anuncio, cliente, data de inicio, data de termino, * investimento por dia) * */ Anuncio anuncio = new Anuncio("Aula de Matemática", "José", dataDeInicio, dataDeTermino, 1500); BancoDeAnuncios banco = new BancoDeAnuncios(); banco.adiciona(anuncio); /** * Filtrando o primeiro anuncio pelo cliente */ System.out.println(banco.buscaAnuncioPeloCliente("José") + "\n"); /** * Filtrando o primeiro anuncio pelo intervalo de tempo */ System.out.println(banco.buscaAnuncioPeloIntervaloDeTempo(dataDeInicio, dataDeTermino) + "\n\n"); /** * Cadastro do segundo anuncio (nome do anuncio, cliente, data de inicio, data de termino, * investimento por dia) * */ Anuncio anuncio2 = new Anuncio("Venda de um Xbox", "João", dataDeInicio2, dataDeTermino2, 2000); BancoDeAnuncios banco2 = new BancoDeAnuncios(); banco.adiciona(anuncio2); /** * Filtrando o segundo anuncio pelo cliente */ System.out.println(banco2.buscaAnuncioPeloCliente("João") + "\n"); /** * Filtrando o segundo anuncio pelo intervalo de tempo */ System.out.println(banco2.buscaAnuncioPeloIntervaloDeTempo(dataDeInicio2, dataDeTermino2) + "\n\n"); /** * Cadastro do terceiro anuncio (nome do anuncio, cliente, data de inicio, data de termino, * investimento por dia) * */ Anuncio anuncio3 = new Anuncio("Venda de um carro Gol", "Maria", dataDeInicio3, dataDeTermino3, 5000); BancoDeAnuncios banco3 = new BancoDeAnuncios(); banco.adiciona(anuncio3); /** * Filtrando o terceiro anuncio pelo cliente */ System.out.println(banco3.buscaAnuncioPeloCliente("Maria") + "\n"); /** * Filtrando o terceiro anuncio pelo intervalo de tempo */ System.out.println(banco3.buscaAnuncioPeloIntervaloDeTempo(dataDeInicio3, dataDeTermino3) + "\n\n"); /** * Cadastro do quarto anuncio (nome do anuncio, cliente, data de inicio, data de termino, * investimento por dia) * */ Anuncio anuncio4 = new Anuncio("Venda de uma casa de praia", "Laura", dataDeInicio4, dataDeTermino4, 1000); BancoDeAnuncios banco4 = new BancoDeAnuncios(); banco.adiciona(anuncio4); /** * Filtrando o quarto anuncio pelo cliente */ System.out.println(banco4.buscaAnuncioPeloCliente("Laura") + "\n"); /** * Filtrando o quarto anuncio pelo intervalo de tempo */ System.out.println(banco4.buscaAnuncioPeloIntervaloDeTempo(dataDeInicio4, dataDeTermino4) + "\n\n"); } }
package com.bingo.code.example.design.state.rewrite; public class RepeatVoteState implements VoteState{ public void vote(String user, String voteItem, VoteManager voteManager) { //�ظ�ͶƱ //��ʱ�������� System.out.println("�벻Ҫ�ظ�ͶƱ"); } }
@javax.xml.bind.annotation.XmlSchema(namespace = "http://validation.erpel.at", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package at.ebinterface.validation.validator.jaxb;
package com.mineskies.common; import lombok.Getter; import org.bukkit.plugin.Plugin; public class Common { @Getter private static Common instance = new Common(); @Getter private static Plugin plugin; public void onEnable(Plugin plugin) { Common.plugin = plugin; } public void onDisable() { } }
//@@author A0126240W package guitests; import guitests.guihandles.TaskCardHandle; import org.junit.Test; import seedu.whatnow.commons.core.Messages; import seedu.whatnow.logic.commands.AddCommand; import seedu.whatnow.testutil.TestTask; import seedu.whatnow.testutil.TestUtil; import static org.junit.Assert.assertTrue; import static seedu.whatnow.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import java.util.Arrays; public class AddCommandTest extends WhatNowGuiTest { @Test public void add() { TestTask[] currentList = td.getTypicalTasks(); //add one task TestTask taskToAdd = td.h; assertAddSuccess(taskToAdd, currentList); currentList = TestUtil.addTasksToList(currentList, taskToAdd); //add another task taskToAdd = td.i; assertAddSuccess(taskToAdd, currentList); currentList = TestUtil.addTasksToList(currentList, taskToAdd); //add another task: add task with 1 date taskToAdd = td.s; assertAddSuccess(taskToAdd, currentList); currentList = TestUtil.addTasksToList(currentList, taskToAdd); //add another task: add task with 2 dates taskToAdd = td.t; assertAddSuccess(taskToAdd, currentList); currentList = TestUtil.addTasksToList(currentList, taskToAdd); //add another task: add task with 2 dates & 2 time taskToAdd = td.u; assertAddSuccess(taskToAdd, currentList); currentList = TestUtil.addTasksToList(currentList, taskToAdd); //add another task: add task with 1 date & 2 time taskToAdd = td.v; assertAddSuccess(taskToAdd, currentList); currentList = TestUtil.addTasksToList(currentList, taskToAdd); //add duplicate task commandBox.runCommand(td.h.getAddCommand()); assertResultMessage(AddCommand.MESSAGE_DUPLICATE_TASK); assertTrue(taskListPanel.isListMatching(currentList)); //add duplicate task commandBox.runCommand(td.t.getAddCommand()); assertResultMessage(AddCommand.MESSAGE_DUPLICATE_TASK); assertTrue(taskListPanel.isListMatching(currentList)); //add duplicate task commandBox.runCommand(td.v.getAddCommand()); assertResultMessage(AddCommand.MESSAGE_DUPLICATE_TASK); assertTrue(taskListPanel.isListMatching(currentList)); //add to empty list commandBox.runCommand("clear"); assertAddSuccess(td.a); //unknown command commandBox.runCommand("adds Johnny"); assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND); //invalid command commandBox.runCommand("add 'workwork'"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); //invalid number of arguments for add command commandBox.runCommand("add \"\""); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); //invalid arguments for add command commandBox.runCommand("add \"Buy milk\" hahaha"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); //add another task: add task without date & time commandBox.runCommand("clear"); commandBox.runCommand("add \"Buy milk\""); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk")); //add another task: add task with 1 date commandBox.runCommand("clear"); commandBox.runCommand("add \"Buy milk\" on 23/2/2017"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk on 23/02/2017")); commandBox.runCommand("add \"Buy milk\" by 27/2/2017"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk on 27/02/2017")); //add another task: add task with 2 date commandBox.runCommand("clear"); commandBox.runCommand("add \"Buy milk\" from 12/2/2017 to 25/2/2017"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk from 12/02/2017 to 25/02/2017")); commandBox.runCommand("add \"Buy milk\" 22/2/2017 to 26/2/2017"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk from 22/02/2017 to 26/02/2017")); //add another task: add task with 1 date 1 time commandBox.runCommand("clear"); commandBox.runCommand("add \"Buy milk\" 1/2/2018 4pm"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk on 01/02/2018 04:00pm")); commandBox.runCommand("add \"Buy milk\" at 3pm on 3rd oct 2017"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk on 03/10/2017 03:00pm")); //add another task: add task with 1 date 2 time commandBox.runCommand("clear"); commandBox.runCommand("add \"Buy milk\" on 4th dec 2017 from 1.30pm to 4:00pm"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk on 04/12/2017 from 01:30pm to 04:00pm")); commandBox.runCommand("add \"Buy milk\" on 03/12/2017 2.30am to 4.30am"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk on 03/12/2017 from 02:30am to 04:30am")); //add another task: add task with 2 date 1 time commandBox.runCommand("clear"); commandBox.runCommand("add \"Buy milk\" from 12/2/2017 4pm to 25/2/2017"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk from 12/02/2017 04:00pm to 25/02/2017 11:59pm")); commandBox.runCommand("add \"Buy milk\" 22/2/2017 to 26/2/2017 3pm"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk from 22/02/2017 12:00am to 26/02/2017 03:00pm")); //add another task: add task with 2 date 2 time commandBox.runCommand("clear"); commandBox.runCommand("add \"Buy milk\" from 12/2/2017 to 25/2/2017 3pm to 4pm"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk from 12/02/2017 03:00pm to 25/02/2017 04:00pm")); commandBox.runCommand("add \"Buy milk\" 22/2/2017 2pm to 26/2/2017 4pm"); assertResultMessage(String.format(AddCommand.MESSAGE_SUCCESS, "Buy milk from 22/02/2017 02:00pm to 26/02/2017 04:00pm")); } private void assertAddSuccess(TestTask taskToAdd, TestTask... currentList) { commandBox.runCommand(taskToAdd.getAddCommand()); Arrays.sort(currentList); //confirm the new card contains the right data TaskCardHandle addedCard = scheduleListPanel.navigateToTask(taskToAdd.getName().fullName); assertMatching(taskToAdd, addedCard); //confirm the list now contains all previous tasks plus the new task TestTask[] expectedList = TestUtil.addTasksToList(currentList, taskToAdd); assertTrue(scheduleListPanel.isListMatching(expectedList)); } }
package nl.rug.oop.flaps.simulation.model.airport; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Getter; import lombok.Setter; import nl.rug.oop.flaps.simulation.model.aircraft.Aircraft; import nl.rug.oop.flaps.simulation.model.aircraft.FuelType; import nl.rug.oop.flaps.simulation.model.cargo.CargoType; import nl.rug.oop.flaps.simulation.model.map.coordinates.GeographicCoordinates; import java.awt.*; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Represents an airport in the world, with some metadata, aircraft * * @author T.O.W.E.R. */ @Getter public class Airport implements Comparable<Airport> { /** * The name of the airport */ private String name; /** * The description of the airport */ private String description; /** * The maximum number of aircraft this airport can have */ private int aircraftCapacity; /** * The geographic coordinates of this airport on the world map */ private GeographicCoordinates geographicCoordinates; /** * The aircraft that are currently on this airport */ @JsonIgnore private final Set<Aircraft> aircraft; /** * A map that contains, for each fuel type, its price in euros at this airport */ @JsonIgnore private final Map<FuelType, Double> fuelPrices; /** * A map that contains, for each cargo type, its price in euros at this airport */ @JsonIgnore private final Map<CargoType, Double> cargoImportDemands; /** * The banner image of this airport */ @Setter private Image bannerImage; /** * Creates a new airport */ public Airport() { aircraft = new HashSet<>(); fuelPrices = new HashMap<>(); cargoImportDemands = new HashMap<>(); } /** * Indicates whether this airport has enough capacity to accept an incoming aircraft * * @return True if there is space left for an aircraft to arrive here; false otherwise */ public boolean canAcceptIncomingAircraft() { return aircraftCapacity > aircraft.size(); } /** * Adds an aircraft to this airport * * @param incomingAircraft The aircraft that is arriving at this airport */ public void addAircraft(Aircraft incomingAircraft) { aircraft.add(incomingAircraft); } /** * Removes an aircraft from this airport * * @param departingAircraft The aircraft that is leaving the airport */ public void removeAircraft(Aircraft departingAircraft) { aircraft.remove(departingAircraft); } /** * Retrieves the location of the airport * * @return The geographic location of this airport */ public GeographicCoordinates getLocation() { return this.geographicCoordinates; } /** * Retrieve the price of the specified cargo type at this airport * * @param cargoType The cargo type of which the price should be retrieved * @return The price of the cargo type in euros per kg */ public double getCargoPriceByType(CargoType cargoType) { return cargoImportDemands.getOrDefault(cargoType, 0d); } /** * Retrieve the price of the specified fuel type at this airport * * @param fuelType The fuel type of which the price should be retrieved * @return The price of the fuel type in euros per kg */ public double getFuelPriceByType(FuelType fuelType) { return fuelPrices.getOrDefault(fuelType, 0d); } @Override public boolean equals(Object o) { if (!(o instanceof Airport)) return false; Airport a = (Airport) o; return this.getName().equals(a.getName()); } @Override public int compareTo(Airport o) { return this.getName().compareTo(o.getName()); } @Override public String toString() { return "Airport{name=\"" + name + "\"}"; } }
package switch2019.project.domain.domainEntities.ledger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import switch2019.project.domain.domainEntities.frameworks.OwnerID; import switch2019.project.domain.domainEntities.person.Address; import switch2019.project.domain.domainEntities.person.Email; import switch2019.project.domain.domainEntities.person.Person; import switch2019.project.domain.domainEntities.shared.*; import java.time.LocalDateTime; import java.util.*; import static org.junit.jupiter.api.Assertions.*; class LedgerTest { /** * Validate if a transaction was added to ledger list */ @Test @DisplayName("Test for validating add a new transaction") void addTransactionToLedgerOneTransaction() { //Arrange AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt"))); AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt"))); CategoryID category = new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); Transaction expected = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account2, new Type(true)); //Act Transaction result = ledger.addTransactionToLedger(monetaryValue, new Description("payment"), null, category, account1, account2, new Type(true)); //Assert assertEquals(expected,result); } /** * Validate if two transactions were added to ledger list */ @Test @DisplayName("Test for validating for several new transactions") void addTransactionToLedgerTwoTransaction() { //Arrange AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt"))); AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt"))); CategoryID category1 = new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))); CategoryID category2 = new CategoryID(new Denomination("transport"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); Transaction expectedTransaction1 = new Transaction(monetaryValue, new Description("payment"), null, category1, account1, account2, new Type(true)); Transaction expectedTransaction2 = new Transaction( monetaryValue, new Description("payment"), null, category2, account1, account2, new Type(true)); //Act Transaction addedTransaction1 = ledger.addTransactionToLedger(monetaryValue, new Description("payment"), null, category1, account1, account2, new Type(true)); Transaction addedTransaction2 = ledger.addTransactionToLedger(monetaryValue, new Description("payment"), null, category2, account1, account2, new Type(true)); //Assert Assertions.assertAll( () -> assertEquals(expectedTransaction1,addedTransaction1), () -> assertEquals(expectedTransaction2,addedTransaction2) ); } /** * Validate if a transaction was added to ledger list * null monetary value */ @Test @DisplayName("Test for validating ledger not adding invalid transactions - null monetaryValue") void addTransactionToLedgerTransactionNullMonetaryValue() { //Arrange AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt"))); AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt"))); CategoryID category = new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Act try { ledger.addTransactionToLedger(null, new Description("payment"), null, category, account1, account2, new Type(true)); } //Assert catch (IllegalArgumentException description) { assertEquals("The monetary value cannot be null.", description.getMessage()); } } /** * Validate if a transaction was added to ledger list * null description */ @Test @DisplayName("Test for validating ledger not adding invalid transactions - null description") void addTransactionToLedgerTransactionNullDescription() { //Arrange AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt"))); AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt"))); CategoryID category = new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Act try { ledger.addTransactionToLedger(monetaryValue, null, null, category, account1, account2, new Type(true)); } //Assert catch (IllegalArgumentException description) { assertEquals("The description can´t be null. Please try again.", description.getMessage()); } } /** * Validate if a transaction was added to ledger list * null category */ @Test @DisplayName("Test for validating ledger not adding invalid transactions - null category") void addTransactionToLedgerTransactionNullCategory() { //Arrange AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt"))); AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt"))); MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Act try { ledger.addTransactionToLedger(monetaryValue, new Description("payment"), null, null, account1, account2, new Type(true)); } //Assert catch (IllegalArgumentException description) { assertEquals("The category cannot be null.", description.getMessage()); } } /** * Validate if a transaction was added to ledger list * null account */ @Test @DisplayName("Test for validate if ledger is not adding invalid transactions - null account") void addTransactionToLedgerTransactionNullAccount() { //Arrange AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt"))); CategoryID category = new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Act try { ledger.addTransactionToLedger(monetaryValue, new Description("payment"), null, category, account1, null, new Type(true)); } //Assert catch (IllegalArgumentException description) { assertEquals("The accounts cannot be null.", description.getMessage()); } } /** * US012 - Como utilizador membro de grupo, quero obter os movimentos do grupo num dado período. */ @Test @DisplayName("Get Ledger Transactions in a given period - Success Case") void getLedgerTransactionsInPeriod() { //Arrange AccountID oneAccount = new AccountID(new Denomination("myxpto"), new PersonID(new Email("personEmail@email.pt"))); AccountID otherAccount = new AccountID(new Denomination("xyz"), new PersonID(new Email("personEmail@email.pt"))); AccountID anotherAccount = new AccountID(new Denomination("abc"), new PersonID(new Email("personEmail@email.pt"))); CategoryID oneCategory = new CategoryID(new Denomination("ASD"), new PersonID(new Email("personEmail@email.com"))); CategoryID otherCategory = new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue oneMonetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); MonetaryValue otherMonetaryValue = new MonetaryValue(10, Currency.getInstance("EUR")); DateAndTime oneLocalDate = new DateAndTime(2018, 10, 2, 9, 10); DateAndTime otherLocalDate = new DateAndTime(2019, 1, 2, 10, 40); DateAndTime anotherLocalDate = new DateAndTime(2015, 10, 2, 10, 40); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Add Transactions to Ledger ledger.addTransactionToLedger(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); ledger.addTransactionToLedger(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); ledger.addTransactionToLedger(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); //Expected Transactions Transaction expectedTransaction1 = new Transaction(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); Transaction expectedTransaction2 = new Transaction(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); List<Transaction> expected = new ArrayList<>(Arrays.asList(expectedTransaction2, expectedTransaction1)); //Act List<Transaction> real = ledger.getTransactionsInDateRange(LocalDateTime.of(2017, 10, 2, 9, 20), LocalDateTime.of(2019, 2, 3, 10, 40)); //Assert assertEquals(expected, real); } @Test @DisplayName("Get Ledger Transactions in a given period - EmptyLedger") void getLedgerTransactionsInPeriodEmptyLedger() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); List<Transaction> expected = new ArrayList<>(); //Act List<Transaction> real = ledger.getTransactionsInDateRange(LocalDateTime.of(2017, 10, 2, 9, 20), LocalDateTime.of(2017, 12, 3, 10, 40)); //Assert assertEquals(expected, real); } @Test @DisplayName("Get Ledger Transactions in a given period - Same date") void getLedgerTransactionsInPeriodSameDay() { //Arrange AccountID oneAccount = new AccountID(new Denomination("myxpto"), new PersonID(new Email("personEmail@email.pt"))); AccountID otherAccount = new AccountID(new Denomination("xyz"), new PersonID(new Email("personEmail@email.pt"))); AccountID anotherAccount = new AccountID(new Denomination("abc"), new PersonID(new Email("personEmail@email.pt"))); CategoryID oneCategory = new CategoryID(new Denomination("ASD"), new PersonID(new Email("personEmail@email.com"))); CategoryID otherCategory = new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue oneMonetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); MonetaryValue otherMonetaryValue = new MonetaryValue(10, Currency.getInstance("EUR")); DateAndTime oneLocalDate = new DateAndTime(2018, 10, 2, 9, 10); DateAndTime otherLocalDate = new DateAndTime(2019, 1, 2, 10, 40); DateAndTime anotherLocalDate = new DateAndTime(2015, 10, 2, 10, 40); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Add Transactions to Ledger ledger.addTransactionToLedger(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); ledger.addTransactionToLedger(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); ledger.addTransactionToLedger(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); //Expected Transactions Transaction expectedTransaction1 = new Transaction(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); List<Transaction> expected = new ArrayList<>(Collections.singletonList(expectedTransaction1)); //Act List<Transaction> real = ledger.getTransactionsInDateRange(LocalDateTime.of(2018, 10, 2, 9, 10), LocalDateTime.of(2018, 10, 2, 9, 10)); //Assert assertEquals(expected, real); } @Test @DisplayName("Get Ledger Transactions in a given period - No transactions on the given date") void getLedgerTransactionsInPeriodNoTransactions() { //Arrange AccountID oneAccount = new AccountID(new Denomination("myxpto"), new PersonID(new Email("personEmail@email.pt"))); AccountID otherAccount = new AccountID(new Denomination("xyz"), new PersonID(new Email("personEmail@email.pt"))); AccountID anotherAccount = new AccountID(new Denomination("abc"), new PersonID(new Email("personEmail@email.pt"))); CategoryID oneCategory = new CategoryID(new Denomination("ASD"), new PersonID(new Email("personEmail@email.com"))); CategoryID otherCategory = new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue oneMonetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); MonetaryValue otherMonetaryValue = new MonetaryValue(10, Currency.getInstance("EUR")); DateAndTime oneLocalDate = new DateAndTime(2018, 10, 2, 9, 10); DateAndTime otherLocalDate = new DateAndTime(2019, 1, 2, 10, 40); DateAndTime anotherLocalDate = new DateAndTime(2015, 10, 2, 10, 40); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Add Transactions to Ledger ledger.addTransactionToLedger(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); ledger.addTransactionToLedger(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); ledger.addTransactionToLedger(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); //Expected Transactions List<Transaction> expected = new ArrayList<>(); //Act List<Transaction> real = ledger.getTransactionsInDateRange(LocalDateTime.of(2012, 10, 2, 9, 10), LocalDateTime.of(2013, 10, 2, 9, 10)); //Assert assertEquals(expected, real); } @Test @DisplayName("Get Ledger Transactions in a given period - Initital Date > Final Date") void getLedgerTransactionsInPeriodFalse() { //Arrange AccountID oneAccount = new AccountID(new Denomination("myxpto"), new PersonID(new Email("personEmail@email.pt"))); AccountID otherAccount = new AccountID(new Denomination("xyz"), new PersonID(new Email("personEmail@email.pt"))); AccountID anotherAccount = new AccountID(new Denomination("abc"), new PersonID(new Email("personEmail@email.pt"))); CategoryID oneCategory = new CategoryID(new Denomination("ASD"), new PersonID(new Email("personEmail@email.com"))); CategoryID otherCategory = new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue oneMonetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); MonetaryValue otherMonetaryValue = new MonetaryValue(10, Currency.getInstance("EUR")); DateAndTime oneLocalDate = new DateAndTime(2018, 10, 2, 9, 10); DateAndTime otherLocalDate = new DateAndTime(2019, 1, 2, 10, 40); DateAndTime anotherLocalDate = new DateAndTime(2015, 10, 2, 10, 40); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Add Transactions to Ledger ledger.addTransactionToLedger(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); ledger.addTransactionToLedger(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); ledger.addTransactionToLedger(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); //Expected Transactions Transaction expectedTransaction1 = new Transaction(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); Transaction expectedTransaction2 = new Transaction(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); //Act try { ledger.getTransactionsInDateRange(LocalDateTime.of(2019, 2, 3, 10, 40), LocalDateTime.of(2017, 10, 2, 9, 20)); } //Assert catch (IllegalArgumentException getTransactionsInDateRange) { assertEquals("One of the specified dates is not valid.", getTransactionsInDateRange.getMessage()); } } @Test @DisplayName("Get Ledger Transactions in a given period - Initial Date > Actual Date") void getLedgerTransactionsInPeriodInitialDateSuperiorActualDate() { //Arrange AccountID oneAccount = new AccountID(new Denomination("myxpto"), new PersonID(new Email("personEmail@email.pt"))); AccountID otherAccount = new AccountID(new Denomination("xyz"), new PersonID(new Email("personEmail@email.pt"))); AccountID anotherAccount = new AccountID(new Denomination("abc"), new PersonID(new Email("personEmail@email.pt"))); CategoryID oneCategory = new CategoryID(new Denomination("ASD"), new PersonID(new Email("personEmail@email.com"))); CategoryID otherCategory = new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue oneMonetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); MonetaryValue otherMonetaryValue = new MonetaryValue(10, Currency.getInstance("EUR")); DateAndTime oneLocalDate = new DateAndTime(2018, 10, 2, 9, 10); DateAndTime otherLocalDate = new DateAndTime(2019, 1, 2, 10, 40); DateAndTime anotherLocalDate = new DateAndTime(2015, 10, 2, 10, 40); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Add Transactions to Ledger ledger.addTransactionToLedger(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); ledger.addTransactionToLedger(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); ledger.addTransactionToLedger(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); //Act try { ledger.getTransactionsInDateRange(LocalDateTime.of(2025, 2, 3, 10, 40), LocalDateTime.of(2017, 10, 2, 9, 20)); } //Assert catch (IllegalArgumentException getTransactionsInDateRange) { assertEquals("One of the specified dates is not valid.", getTransactionsInDateRange.getMessage()); } } @Test @DisplayName("Get Ledger Transactions in a given period - Final Date > Actual Date") void getLedgerTransactionsInPeriodFinalDateSuperiorActualDate() { //Arrange AccountID oneAccount = new AccountID(new Denomination("myxpto"), new PersonID(new Email("personEmail@email.pt"))); AccountID otherAccount = new AccountID(new Denomination("xyz"), new PersonID(new Email("personEmail@email.pt"))); AccountID anotherAccount = new AccountID(new Denomination("abc"), new PersonID(new Email("personEmail@email.pt"))); CategoryID oneCategory = new CategoryID(new Denomination("ASD"), new PersonID(new Email("personEmail@email.com"))); CategoryID otherCategory = new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue oneMonetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); MonetaryValue otherMonetaryValue = new MonetaryValue(10, Currency.getInstance("EUR")); DateAndTime oneLocalDate = new DateAndTime(2018, 10, 2, 9, 10); DateAndTime otherLocalDate = new DateAndTime(2019, 1, 2, 10, 40); DateAndTime anotherLocalDate = new DateAndTime(2015, 10, 2, 10, 40); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Add Transactions to Ledger ledger.addTransactionToLedger(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); ledger.addTransactionToLedger(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); ledger.addTransactionToLedger(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); //Act try { ledger.getTransactionsInDateRange(LocalDateTime.of(2019, 2, 3, 10, 40), LocalDateTime.of(2030, 10, 2, 9, 20)); } //Assert catch (IllegalArgumentException getTransactionsInDateRange) { assertEquals("One of the specified dates is not valid.", getTransactionsInDateRange.getMessage()); } } @Test @DisplayName("Get Ledger Transactions in a given period - Initial Date null") void getLedgerTransactionsInPeriodInitialDateNull() { //Arrange AccountID oneAccount = new AccountID(new Denomination("myxpto"), new PersonID(new Email("personEmail@email.pt"))); AccountID otherAccount = new AccountID(new Denomination("xyz"), new PersonID(new Email("personEmail@email.pt"))); AccountID anotherAccount = new AccountID(new Denomination("abc"), new PersonID(new Email("personEmail@email.pt"))); CategoryID oneCategory = new CategoryID(new Denomination("ASD"), new PersonID(new Email("personEmail@email.com"))); CategoryID otherCategory = new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue oneMonetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); MonetaryValue otherMonetaryValue = new MonetaryValue(10, Currency.getInstance("EUR")); DateAndTime oneLocalDate = new DateAndTime(2018, 10, 2, 9, 10); DateAndTime otherLocalDate = new DateAndTime(2019, 1, 2, 10, 40); DateAndTime anotherLocalDate = new DateAndTime(2015, 10, 2, 10, 40); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Add Transactions to Ledger ledger.addTransactionToLedger(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); ledger.addTransactionToLedger(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); ledger.addTransactionToLedger(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); //Act try { ledger.getTransactionsInDateRange(null, LocalDateTime.of(2030, 10, 2, 9, 20)); } //Assert catch (IllegalArgumentException getTransactionsInDateRange) { assertEquals("The specified dates cannot be null.", getTransactionsInDateRange.getMessage()); } } @Test @DisplayName("Get Ledger Transactions in a given period - Final Date null") void getLedgerTransactionsInPeriodFinalDateNull() { //Arrange AccountID oneAccount = new AccountID(new Denomination("myxpto"), new PersonID(new Email("personEmail@email.pt"))); AccountID otherAccount = new AccountID(new Denomination("xyz"), new PersonID(new Email("personEmail@email.pt"))); AccountID anotherAccount = new AccountID(new Denomination("abc"), new PersonID(new Email("personEmail@email.pt"))); CategoryID oneCategory = new CategoryID(new Denomination("ASD"), new PersonID(new Email("personEmail@email.com"))); CategoryID otherCategory = new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue oneMonetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); MonetaryValue otherMonetaryValue = new MonetaryValue(10, Currency.getInstance("EUR")); DateAndTime oneLocalDate = new DateAndTime(2018, 10, 2, 9, 10); DateAndTime otherLocalDate = new DateAndTime(2019, 1, 2, 10, 40); DateAndTime anotherLocalDate = new DateAndTime(2015, 10, 2, 10, 40); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Add Transactions to Ledger ledger.addTransactionToLedger(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); ledger.addTransactionToLedger(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); ledger.addTransactionToLedger(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); //Act try { ledger.getTransactionsInDateRange(LocalDateTime.of(2019, 2, 3, 10, 40), null); } //Assert catch (IllegalArgumentException getTransactionsInDateRange) { assertEquals("The specified dates cannot be null.", getTransactionsInDateRange.getMessage()); } } /** * isTransactionInLedger tests */ @DisplayName("test true") @Test void checkIfTransactionIsInsideALedger() { //Arrange: OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); MonetaryValue monetaryValue1 = new MonetaryValue(175, Currency.getInstance("EUR")); AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt"))); AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt"))); CategoryID category1 = new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))); Transaction transaction1 = new Transaction(monetaryValue1, new Description("payment"), new DateAndTime(2020, 1, 14, 13, 05), category1, account1, account2, new Type(true)); ledger.addTransactionToLedger(monetaryValue1, new Description("payment"), new DateAndTime(2020, 1, 14, 13, 05), category1, account1, account2, new Type(true)); //Act: boolean isTransactionInsideLedger = ledger.isTransactionInLedger(transaction1); //Assert: assertTrue(isTransactionInsideLedger); } @DisplayName("test false") @Test void checkIfTransactionIsInsideALedger2() { //Arrange: OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); MonetaryValue monetaryValue1 = new MonetaryValue(175, Currency.getInstance("EUR")); MonetaryValue monetaryValue2 = new MonetaryValue(225, Currency.getInstance("EUR")); AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt"))); AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt"))); CategoryID category1 = new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))); Transaction transaction1 = new Transaction(monetaryValue2, new Description("payment"), new DateAndTime(2020, 1, 14, 13, 05), category1, account1, account2, new Type(true)); ledger.addTransactionToLedger(monetaryValue1, new Description("payment"), new DateAndTime(2020, 1, 14, 13, 05), category1, account1, account2, new Type(true)); //Act: boolean isTransactionInsideLedger = ledger.isTransactionInLedger(transaction1); //Assert: assertFalse(isTransactionInsideLedger); } @Test @DisplayName("Sort Transactions in ASC by date") void sortTransactionsInAscendingOrderByDate() { //Arrange AccountID oneAccount = new AccountID(new Denomination("myxpto"), new PersonID(new Email("personEmail@email.pt"))); AccountID otherAccount = new AccountID(new Denomination("xyz"), new PersonID(new Email("personEmail@email.pt"))); AccountID anotherAccount = new AccountID(new Denomination("abc"), new PersonID(new Email("personEmail@email.pt"))); CategoryID oneCategory = new CategoryID(new Denomination("ASD"), new PersonID(new Email("personEmail@email.com"))); CategoryID otherCategory = new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue oneMonetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); MonetaryValue otherMonetaryValue = new MonetaryValue(10, Currency.getInstance("EUR")); DateAndTime oneLocalDate = new DateAndTime(2018, 10, 2, 9, 10); DateAndTime otherLocalDate = new DateAndTime(2019, 1, 2, 10, 40); DateAndTime anotherLocalDate = new DateAndTime(2015, 10, 2, 10, 40); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Add Transactions to Ledger ledger.addTransactionToLedger(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); ledger.addTransactionToLedger(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); ledger.addTransactionToLedger(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); //Expected Transactions Transaction expectedTransaction1 = new Transaction(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); Transaction expectedTransaction2 = new Transaction(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); Transaction expectedTransaction3 = new Transaction(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); ArrayList<Transaction> expected = new ArrayList<>(Arrays.asList(expectedTransaction3, expectedTransaction1, expectedTransaction2)); //Act ledger.sortLedgerByTransactionDateAscending(); //Assert assertEquals(expected, ledger.getLedgerTransactions()); } @Test @DisplayName("Sort Transactions in DESC by date") void sortTransactionsInDescendingOrderByDate() { //Arrange AccountID oneAccount = new AccountID(new Denomination("myxpto"), new PersonID(new Email("personEmail@email.pt"))); AccountID otherAccount = new AccountID(new Denomination("xyz"), new PersonID(new Email("personEmail@email.pt"))); AccountID anotherAccount = new AccountID(new Denomination("abc"), new PersonID(new Email("personEmail@email.pt"))); CategoryID oneCategory = new CategoryID(new Denomination("ASD"), new PersonID(new Email("personEmail@email.com"))); CategoryID otherCategory = new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue oneMonetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); MonetaryValue otherMonetaryValue = new MonetaryValue(10, Currency.getInstance("EUR")); DateAndTime oneLocalDate = new DateAndTime(2018, 10, 2, 9, 10); DateAndTime otherLocalDate = new DateAndTime(2019, 1, 2, 10, 40); DateAndTime anotherLocalDate = new DateAndTime(2015, 10, 2, 10, 40); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Add Transactions to Ledger ledger.addTransactionToLedger(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); ledger.addTransactionToLedger(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); ledger.addTransactionToLedger(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); //Expected Transactions Transaction expectedTransaction1 = new Transaction(oneMonetaryValue, new Description("payment"), oneLocalDate, oneCategory, oneAccount, otherAccount, new Type(true)); Transaction expectedTransaction2 = new Transaction(otherMonetaryValue, new Description("xpto"), otherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(false)); Transaction expectedTransaction3 = new Transaction(oneMonetaryValue, new Description("abc"), anotherLocalDate, otherCategory, anotherAccount, oneAccount, new Type(true)); ArrayList<Transaction> expected = new ArrayList<>(Arrays.asList(expectedTransaction2, expectedTransaction1, expectedTransaction3)); //Act ledger.sortLedgerByTransactionDateDescending(); //Assert assertEquals(expected, ledger.getLedgerTransactions()); } @Test @DisplayName("Get movements from one account - Success Case") void getMovementsFromOneAccountSuccessCase() { //Arrange Person person = new Person("Jose", new DateAndTime(1995, 12, 13), new Address("Lisboa"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt")); AccountID account = new AccountID(new Denomination("Millenium"), person.getID()); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Arrange-Transaction1 ledger.addTransactionToLedger(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("grocery"), person.getID()), new AccountID(new Denomination("Millenium"), person.getID()), new AccountID(new Denomination("Continente"), person.getID()), new Type(false)); Transaction transaction1 = new Transaction(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("grocery"), person.getID()), new AccountID(new Denomination("Millenium"), person.getID()), new AccountID(new Denomination("Continente"), person.getID()), new Type(false)); //Arrange-Transaction2 ledger.addTransactionToLedger(new MonetaryValue(5.4, Currency.getInstance("EUR")), new Description("schweppes"), new DateAndTime(2020, 1, 2, 14, 11), new CategoryID(new Denomination("grocery"), person.getID()), new AccountID(new Denomination("BNI"), person.getID()), new AccountID(new Denomination("Millenium"), person.getID()), new Type(false)); Transaction transaction2 = new Transaction(new MonetaryValue(5.4, Currency.getInstance("EUR")), new Description("schweppes"), new DateAndTime(2020, 1, 2, 14, 11), new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("BNI"), person.getID()), new AccountID(new Denomination("Millenium"), person.getID()), new Type(false)); //Arrange-Transaction3 ledger.addTransactionToLedger(new MonetaryValue(70, Currency.getInstance("EUR")), new Description("car gas"), new DateAndTime(2020, 1, 5, 17, 23), new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("CGD"), person.getID()), new AccountID(new Denomination("BP"), person.getID()), new Type(false)); Transaction transaction3 = new Transaction(new MonetaryValue(70, Currency.getInstance("EUR")), new Description("car gas"), new DateAndTime(2020, 1, 5, 17, 23), new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("CGD"), person.getID()), new AccountID(new Denomination("BP"), person.getID()), new Type(false)); List<Transaction> allTransactions = new ArrayList<>(Arrays.asList(transaction1, transaction2, transaction3)); List<Transaction> expectedTransactions = new ArrayList<>(Arrays.asList(transaction1, transaction2)); //Act List<Transaction> listOfTransactions = ledger.getTransactionsFromOneAccount(account, allTransactions); //Assert assertEquals(expectedTransactions, listOfTransactions); } @Test @DisplayName("Get movements from one account - Null Account") void getMovementsFromOneAccountNullAccount() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); AccountID account = null; ledger.addTransactionToLedger(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); Transaction transaction1 = new Transaction(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("QWERTY"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); List<Transaction> allTransactions = new ArrayList<>(Arrays.asList(transaction1)); //Act try { ledger.getTransactionsFromOneAccount(account, allTransactions); } //Assert catch (IllegalArgumentException getMovementsFromOneAccount) { assertEquals("The account cannot be null.", getMovementsFromOneAccount.getMessage()); } } @Test @DisplayName("Get movements from one account - Account without movements") void getMovementsFromOneAccountAccountWithoutMovements() { //Arrange Person person = new Person("Jose", new DateAndTime(1995, 12, 13), new Address("Lisboa"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt")); AccountID account = new AccountID(new Denomination("CaixaGeral"), person.getID()); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Arrange-Transaction1 ledger.addTransactionToLedger(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("grocery"), person.getID()), new AccountID(new Denomination("Millenium"), person.getID()), new AccountID(new Denomination("Continente"), person.getID()), new Type(false)); Transaction transaction1 = new Transaction(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("grocery"), person.getID()), new AccountID(new Denomination("Millenium"), person.getID()), new AccountID(new Denomination("Continente"), person.getID()), new Type(false)); List<Transaction> allTransactions = new ArrayList<>(Arrays.asList(transaction1)); List<Transaction> expectedTransactions = new ArrayList<>(); //Act List<Transaction> listOfTransactions = ledger.getTransactionsFromOneAccount(account, allTransactions); //Assert assertEquals(expectedTransactions, listOfTransactions); } /** * * US017/18 - Get the balance of the transactions given a specific date range */ @Test @DisplayName("Get the balance of transactions over a valid date range - Main Scenario of US17") void getPersonalBalanceInDateRange() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Init Transactions ledger.addTransactionToLedger(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("general"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(true)); ledger.addTransactionToLedger(new MonetaryValue(5.4, Currency.getInstance("EUR")), new Description("schweppes"), new DateAndTime(2020, 1, 1, 14, 11), new CategoryID(new Denomination("general"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger(new MonetaryValue(70, Currency.getInstance("EUR")), new Description("car gas"), new DateAndTime(2020, 1, 5, 17, 23), new CategoryID(new Denomination("general"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("CGD"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("BP"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); LocalDateTime initialDate = LocalDateTime.of(2020, 1, 1, 00, 00); LocalDateTime finalDate = LocalDateTime.of(2020, 1, 6, 00, 00); double expectedPersonalBalanceFromDateRange = -55.4; //Act double personalBalanceInDateRange = ledger.getBalanceInDateRange(initialDate, finalDate); //Assert assertEquals(expectedPersonalBalanceFromDateRange, personalBalanceInDateRange); } @Test @DisplayName("Get the balance of transactions for one day - valid day") void getBalanceForGivenDay() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Init Transactions ledger.addTransactionToLedger(new MonetaryValue(250, Currency.getInstance("EUR")), new Description("Hostel Barcelona"), new DateAndTime(2020, 1, 13, 13, 05), new CategoryID(new Denomination("general"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Revolut"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Friends & Company"), new PersonID(new Email("personEmail@email.pt"))), new Type(true)); ledger.addTransactionToLedger(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("Pack of Super Bock"), new DateAndTime(2020, 1, 13, 14, 11), new CategoryID(new Denomination("general"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger(new MonetaryValue(60, Currency.getInstance("EUR")), new Description("Car Gas"), new DateAndTime(2020, 1, 18, 17, 23), new CategoryID(new Denomination("general"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("CGD"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("BP"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); LocalDateTime initialDate = LocalDateTime.of(2020, 1, 13, 00, 00); LocalDateTime finalDate = LocalDateTime.of(2020, 1, 13, 23, 59); double expectedPersonalBalanceFromDateRange = 230; //Act double personalBalanceInDateRange = ledger.getBalanceInDateRange(initialDate, finalDate); //Assert assertEquals(expectedPersonalBalanceFromDateRange, personalBalanceInDateRange); } @Test @DisplayName("Get the balance of transactions over a valid date range but initial date and final date not in order") void getBalanceInDateRangeWithDatesDisordered() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Init Transactions ledger.addTransactionToLedger(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger(new MonetaryValue(5.4, Currency.getInstance("EUR")), new Description("schweppes"), new DateAndTime(2020, 1, 1, 14, 11), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger(new MonetaryValue(70, Currency.getInstance("EUR")), new Description("schweppes"), new DateAndTime(2020, 1, 5, 17, 23), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("CGD"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("BP"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); LocalDateTime finalDate = LocalDateTime.of(2020, 1, 6, 00, 00); LocalDateTime initialDate = LocalDateTime.of(2019, 12, 31, 00, 00); double expectedPersonalBalanceFromDateRange = -95.4; //Act double personalBalanceInDateRange = ledger.getBalanceInDateRange(initialDate, finalDate); //Assert assertEquals(expectedPersonalBalanceFromDateRange, personalBalanceInDateRange); } @Test @DisplayName("Get the balance transactions over invalid date range - final date higher than today!") void getBalanceInDateRangeWithNotValidDate() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); ledger.addTransactionToLedger(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger((new MonetaryValue(5.4, Currency.getInstance("EUR"))), new Description("schweppes"), new DateAndTime(2020, 1, 1, 14, 11), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger(new MonetaryValue(70, Currency.getInstance("EUR")), new Description("schweppes"), new DateAndTime(2020, 1, 5, 17, 23), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("CGD"),new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("BP"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); LocalDateTime initialDate = LocalDateTime.of(2020, 1, 27, 00, 00); LocalDateTime finalDate = LocalDateTime.of(2021, 1, 27, 00, 00); try { //Act double personalBalanceInDateRange = ledger.getBalanceInDateRange(initialDate, finalDate); fail(); } //Assert catch (IllegalArgumentException result) { assertEquals("One of the specified dates is not valid.", result.getMessage()); } } @Test @DisplayName("Get the balance transactions over invalid date range - inicial date null") void getBalanceInDateRangeWithNotValidDateInitialDateNull() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); ledger.addTransactionToLedger(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger((new MonetaryValue(5.4, Currency.getInstance("EUR"))), new Description("schweppes"), new DateAndTime(2020, 1, 1, 14, 11), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger(new MonetaryValue(70, Currency.getInstance("EUR")), new Description("schweppes"), new DateAndTime(2020, 1, 5, 17, 23), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("CGD"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("BP"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); LocalDateTime initialDate = null; LocalDateTime finalDate = LocalDateTime.of(2021, 1, 27, 00, 00); try { //Act ledger.getBalanceInDateRange(initialDate, finalDate); fail(); } //Assert catch (IllegalArgumentException result) { assertEquals("One of the specified dates is not valid.", result.getMessage()); } } @Test @DisplayName("Get the balance transactions over invalid date range - final date null") void getBalanceInDateRangeWithNotValidDateFinalDateNull() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); ledger.addTransactionToLedger(new MonetaryValue(20, Currency.getInstance("EUR")), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger((new MonetaryValue(5.4, Currency.getInstance("EUR"))), new Description("schweppes"), new DateAndTime(2020, 1, 1, 14, 11), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger(new MonetaryValue(70, Currency.getInstance("EUR")), new Description("schweppes"), new DateAndTime(2020, 1, 5, 17, 23), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("CGD"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("BP"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); LocalDateTime initialDate = LocalDateTime.of(2021, 1, 27, 00, 00); LocalDateTime finalDate = null; try { //Act ledger.getBalanceInDateRange(initialDate, finalDate); fail(); } //Assert catch (IllegalArgumentException result) { assertEquals("One of the specified dates is not valid.", result.getMessage()); } } @Test @DisplayName("Get the balance of ledger that is empty!") void getBalanceInDateRangeEmptyBalance() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); LocalDateTime initialDate = LocalDateTime.of(2019, 10, 27, 00, 00); LocalDateTime finalDate = LocalDateTime.of(2019, 9, 20, 00, 00); try { //Act ledger.getBalanceInDateRange(initialDate, finalDate); fail(); } //Assert catch (IllegalArgumentException result) { assertEquals("The ledger has no Transactions.", result.getMessage()); } } @Test @DisplayName("Get the balance of my own transactions over invalid date range - final date higher than today!") void getBalanceInDateRangeWithInvalidDate() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Init Transactions ledger.addTransactionToLedger((new MonetaryValue(20, Currency.getInstance("EUR"))), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger((new MonetaryValue(5.4, Currency.getInstance("EUR"))), new Description("schweppes"), new DateAndTime(2020, 1, 1, 14, 11), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium") , new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger((new MonetaryValue(70, Currency.getInstance("EUR"))), new Description("schweppes"), new DateAndTime(2020, 1, 5, 17, 23), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("CGD"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("BP"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); LocalDateTime initialDate = LocalDateTime.of(2020, 1, 27, 00, 00); LocalDateTime finalDate = LocalDateTime.of(2021, 1, 27, 00, 00); try { //Act ledger.getBalanceInDateRange(initialDate, finalDate); fail(); } //Assert catch (IllegalArgumentException result) { assertEquals("One of the specified dates is not valid.", result.getMessage()); } } @Test @DisplayName("Get the balance of my ledger that has zero transactions") void getBalanceInDateRangeOfEmptyLedger() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); LocalDateTime initialDate = LocalDateTime.of(2019, 10, 27, 00, 00); LocalDateTime finalDate = LocalDateTime.of(2019, 9, 20, 00, 00); try { //Act ledger.getBalanceInDateRange(initialDate, finalDate); fail(); } //Assert catch (IllegalArgumentException result) { assertEquals("The ledger has no Transactions.", result.getMessage()); } } @Test @DisplayName("Get the balance of my own transactions over a period with zero transactions in date range") void getBalanceInDateRangeEmptyBalanceOverDateRange() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Init Transactions ledger.addTransactionToLedger((new MonetaryValue(20, Currency.getInstance("EUR"))), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"),new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger((new MonetaryValue(5.4, Currency.getInstance("EUR"))), new Description("schweppes"), new DateAndTime(2020, 1, 1, 14, 11), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger((new MonetaryValue(70, Currency.getInstance("EUR"))), new Description("schweppes"), new DateAndTime(2020, 1, 5, 17, 23), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("CGD"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("BP"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); LocalDateTime initialDate = LocalDateTime.of(2019, 10, 27, 00, 00); LocalDateTime finalDate = LocalDateTime.of(2019, 9, 20, 00, 00); //Act double personalBalanceInDateRange = ledger.getBalanceInDateRange(initialDate, finalDate); // Assert assertEquals(0, personalBalanceInDateRange); } /** * tests for size of the Ledger. */ @Test @DisplayName("Test for validating add a new transaction") void addTransactionToLedgerChangeSize() { //Arrange AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt"))); AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt"))); CategoryID category = new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Act int sizeBefore = ledger.getLedgerSize(); ledger.addTransactionToLedger(monetaryValue, new Description("payment"), null, category, account1, account2, new Type(true)); int sizeAfter = ledger.getLedgerSize(); //Assert assertEquals(sizeBefore + 1, sizeAfter); } /** * Test - Method To String */ @Test @DisplayName("Test toString() Method") void testToStringMethod() { //Arrange AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt"))); AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt"))); CategoryID category = new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))); MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR")); DateAndTime date = new DateAndTime(2019, 10, 27, 00, 00); OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); ledger.addTransactionToLedger(monetaryValue, new Description("payment"), date, category, account1, account2, new Type(true)); String expected = "Ledger:[2019-10-27 00:00 | 200.0 EUR CREDIT | MERCEARIA -> TRANSPORTE | Description: \"PAYMENT\" | GROCERY]."; //Act String real = ledger.toString(); //Assert assertEquals(expected, real); } @Test @DisplayName("Get the Ledger Size") void getLedgerSize() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Transactions ledger.addTransactionToLedger((new MonetaryValue(20, Currency.getInstance("EUR"))), new Description("2 pacs of Gurosan"), new DateAndTime(2020, 1, 1, 13, 05), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger((new MonetaryValue(5.4, Currency.getInstance("EUR"))), new Description("schweppes"), new DateAndTime(2020, 1, 1, 14, 11), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); ledger.addTransactionToLedger((new MonetaryValue(70, Currency.getInstance("EUR"))), new Description("schweppes"), new DateAndTime(2020, 1, 5, 17, 23), new CategoryID(new Denomination("grocery"), new PersonID(new Email("personEmail@email.com"))), new AccountID(new Denomination("CGD"), new PersonID(new Email("personEmail@email.pt"))), new AccountID(new Denomination("BP"), new PersonID(new Email("personEmail@email.pt"))), new Type(false)); //Act int ledgerSize = ledger.getLedgerSize(); // Assert assertEquals(3, ledgerSize); } @Test @DisplayName("Schedule a Transaction") void scheduleNewTransaction() throws InterruptedException { // Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); int before = ledger.getLedgerSize(); // Act boolean newTransactionScheduled = ledger.scheduleNewTransaction(new Periodicity("daily"), new MonetaryValue(5, Currency.getInstance("EUR")), new Description("lunch at work"), new DateAndTime(2020, 1, 1, 13, 5), new CategoryID(new Denomination("food"), new PersonID(new Email("marta@email.com"))), new AccountID(new Denomination("Millenium"), new PersonID(new Email("marta@email.pt"))), new AccountID(new Denomination("Continente"), new PersonID(new Email("marta@email.pt"))), new Type(false)); Thread.sleep(2400); // daily = 500 int after = ledger.getLedgerSize(); //Assert assertEquals(0, before); assertEquals(5, after); assertTrue(newTransactionScheduled); } @Test @DisplayName("Get the Ledger Size - Empty") void getLedgerSizeEmpty() { //Arrange OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); //Act int ledgerSize = ledger.getLedgerSize(); // Assert assertEquals(0, ledgerSize); } @Test @DisplayName("hashcode test equal ledger") void equalsTestHashcode(){ OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); Ledger ledger1 = new Ledger(ownerID); boolean resultHash = ledger.hashCode() == ledger1.hashCode(); assertTrue(resultHash); } @Test @DisplayName("Equals test same object") void equalsTestSameObj(){ OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); boolean resultTrue = ledger.equals(ledger); assertTrue(resultTrue); } @Test @DisplayName("Equals test, instance of") void equalsTestInstance(){ OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); boolean result = ledger.equals(ownerID); assertFalse(result); } @Test @DisplayName("hashcode test equal ledger") void equalsTestHashcodeFalse(){ OwnerID ownerID = new GroupID(new Description("switch")); Ledger ledger = new Ledger(ownerID); Ledger ledger1 = new Ledger(new GroupID(new Description("amigos"))); boolean resultHash = ledger.hashCode() == ledger1.hashCode(); assertFalse(resultHash); } /** * Test getCreationDateToString */ @Test @DisplayName("get creationDate as String test") void getCreationDateToStringTest() { //Arrange: Ledger ledger = new Ledger(new PersonID(new Email("test@gmail.com"))); String expectedCreationDate = new DateAndTime().yearMonthDayToString(); //Act: String actualCreationDate = ledger.getCreationDateToString(); //Assert: assertEquals(expectedCreationDate, actualCreationDate); } }
package net.sf.ardengine.renderer.opengl.legacy.util; import javafx.scene.paint.Color; import net.sf.ardengine.Core; import static org.lwjgl.opengl.GL11.*; /** * Simple singleton for rendering lines of collision shapes */ public class LegacyCollisionRenderer { private LegacyCollisionRenderer(){}; public static void drawLines(float[] coords, Color color){ glDisable(GL_TEXTURE_2D); glColor4f((float)color.getRed(), (float)color.getGreen(), (float)color.getBlue(), 1); glPushMatrix(); glLineWidth(1.3f); glBegin(GL_LINE_STRIP); for( int i=0; i <coords.length; i+=2){ glVertex2f(coords[i], coords[i+1]); } //line strip glVertex2f(coords[0], coords[1]); glEnd(); glPopMatrix(); glEnable(GL_TEXTURE_2D); } }
package com.catasys.pre.dfappl.dfapplsummaryapi.service.implementation; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import com.catasys.pre.dfappl.dfapplsummaryapi.models.CareCoachAssignmentResponse; import com.catasys.pre.dfappl.dfapplsummaryapi.models.exceptions.CareCoachNotFoundException; import com.catasys.pre.dfappl.dfapplsummaryapi.models.exceptions.FeatureFlagTurnedOffException; import com.catasys.pre.dfappl.dfapplsummaryapi.models.exceptions.UnauthorizedException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.util.ReflectionTestUtils; import java.io.IOException; @ContextConfiguration(classes = {CareCoachAssignmentServiceImpl.class, String.class}) class CareCoachServiceImplTest { public static MockWebServer mockBackEnd; private CareCoachAssignmentResponse careCoachAssignmentResponse; private CareCoachAssignmentServiceImpl careCoachAssignmentService; private String baseUrl; @BeforeEach void setup() throws IOException { mockBackEnd = new MockWebServer(); mockBackEnd.start(); careCoachAssignmentResponse = new CareCoachAssignmentResponse(); careCoachAssignmentResponse.setSuccess(true); careCoachAssignmentResponse.setError("sampleError"); baseUrl = String.format("http://localhost:%s", mockBackEnd.getPort()); careCoachAssignmentService = new CareCoachAssignmentServiceImpl(baseUrl); ReflectionTestUtils.setField(careCoachAssignmentService, "eotCareCoachMemberURL", baseUrl); ReflectionTestUtils.setField(careCoachAssignmentService, "eotCareCoachMemberAPIUsername", "catasys"); ReflectionTestUtils.setField(careCoachAssignmentService, "eotCareCoachMemberAPIPassword", "Catasys@2"); ReflectionTestUtils.setField(careCoachAssignmentService, "updateEotCcAssignment", "true"); } @AfterAll static void tearDown() throws IOException { mockBackEnd.shutdown(); } @Test void testConstructor(){ careCoachAssignmentService = new CareCoachAssignmentServiceImpl(); Assertions.assertNotNull(careCoachAssignmentService); } @Test void testFor200Scenario() throws JsonProcessingException, InterruptedException { ObjectMapper objectMapper = new ObjectMapper(); mockBackEnd.enqueue(new MockResponse() .setBody(objectMapper.writeValueAsString(careCoachAssignmentResponse)) .addHeader("Content-Type", "application/json")); CareCoachAssignmentResponse careCoachAssignmentResponse1 = careCoachAssignmentService.recordCareCoachAssignment("226363572", "123654", "2021-11-12T09:29:21.291Z"); RecordedRequest recordedRequest = mockBackEnd.takeRequest(); Assertions.assertEquals(true, careCoachAssignmentResponse1.getSuccess()); Assertions.assertEquals("POST", recordedRequest.getMethod()); } @Test void testFor404Scenario() { mockBackEnd.enqueue(new MockResponse() .setResponseCode(404) .addHeader("Content-Type", "application/json")); Assertions.assertThrows(CareCoachNotFoundException.class, () -> careCoachAssignmentService.recordCareCoachAssignment("226363572", "sampleCareCoachID", "2021-11-12T09:29:21.291Z"), "eOnTrak feature flag turned off in Azure KV"); } @Test void testFor401Scenario() { mockBackEnd.enqueue(new MockResponse() .setResponseCode(401) .addHeader("Content-Type", "application/json")); Assertions.assertThrows(UnauthorizedException.class, () -> careCoachAssignmentService.recordCareCoachAssignment("226363572", "sampleCareCoachID", "2021-11-12T09:29:21.291Z")); } @Test void testFor400InvalidRequestException() { mockBackEnd.enqueue(new MockResponse() .setResponseCode(400) .addHeader("Content-Type", "application/json")); Assertions.assertThrows(InvalidRequestException.class, () -> careCoachAssignmentService.recordCareCoachAssignment("226363572", "sampleCareCoachID", "2021-11-12T09:29:21.291Z")); } @Test void testFor500() { mockBackEnd.enqueue(new MockResponse() .setResponseCode(500) .addHeader("Content-Type", "application/json")); Assertions.assertThrows(RuntimeException.class, () -> careCoachAssignmentService.recordCareCoachAssignment("226363572", "sampleCareCoachID", "2021-11-12T09:29:21.291Z")); } @Test void testCallEOTMemberEnrollmentDateForRunTimException() { ReflectionTestUtils.setField(careCoachAssignmentService, "updateEotCcAssignment", "false"); Assertions.assertThrows(FeatureFlagTurnedOffException.class, () -> careCoachAssignmentService.recordCareCoachAssignment("226363572", "sampleCareCoachID", "2021-11-12T09:29:21.291Z"), "eOnTrak feature flag turned off in Azure KV"); } }
package com.bl.Junit.TempConversion; public class TempConversionBL { public static int TempConversion(char ch) { char type = ch; int x; if (type=='C') { x = 1; return x; } if (type=='F') { x = 2; return x; }else { System.out.println("Wrong type of temperature"); return 0; } } }
package com.tencent.mm.g.c; import android.content.ContentValues; import android.database.Cursor; import com.tencent.mm.sdk.e.c; import com.tencent.tmassistantsdk.storage.table.DownloadSettingTable$Columns; public abstract class dc extends c { private static final int cJQ = "reportId".hashCode(); private static final int cJY = "retryTimes".hashCode(); private static final int cJZ = "retriedCount".hashCode(); private static final int cKa = "retryInterval".hashCode(); private static final int cKb = "networkType".hashCode(); private static final int cKc = "pkgMd5".hashCode(); private static final int cKd = "lastRetryTime".hashCode(); private static final int cKe = "firstTimeTried".hashCode(); public static final String[] ciG = new String[0]; private static final int ciP = "rowid".hashCode(); private static final int ckP = "appId".hashCode(); private static final int cke = DownloadSettingTable$Columns.TYPE.hashCode(); private static final int clC = "version".hashCode(); private boolean cJN = true; private boolean cJR = true; private boolean cJS = true; private boolean cJT = true; private boolean cJU = true; private boolean cJV = true; private boolean cJW = true; private boolean cJX = true; private boolean cjI = true; private boolean cky = true; private boolean clw = true; public String field_appId; public boolean field_firstTimeTried; public long field_lastRetryTime; public int field_networkType; public String field_pkgMd5; public int field_reportId; public int field_retriedCount; public long field_retryInterval; public int field_retryTimes; public int field_type; public int field_version; public final void d(Cursor cursor) { String[] columnNames = cursor.getColumnNames(); if (columnNames != null) { int length = columnNames.length; for (int i = 0; i < length; i++) { int hashCode = columnNames[i].hashCode(); if (ckP == hashCode) { this.field_appId = cursor.getString(i); } else if (clC == hashCode) { this.field_version = cursor.getInt(i); } else if (cke == hashCode) { this.field_type = cursor.getInt(i); } else if (cJY == hashCode) { this.field_retryTimes = cursor.getInt(i); } else if (cJZ == hashCode) { this.field_retriedCount = cursor.getInt(i); } else if (cKa == hashCode) { this.field_retryInterval = cursor.getLong(i); } else if (cKb == hashCode) { this.field_networkType = cursor.getInt(i); } else if (cKc == hashCode) { this.field_pkgMd5 = cursor.getString(i); } else if (cKd == hashCode) { this.field_lastRetryTime = cursor.getLong(i); } else if (cKe == hashCode) { this.field_firstTimeTried = cursor.getInt(i) != 0; } else if (cJQ == hashCode) { this.field_reportId = cursor.getInt(i); } else if (ciP == hashCode) { this.sKx = cursor.getLong(i); } } } } public final ContentValues wH() { ContentValues contentValues = new ContentValues(); if (this.cky) { contentValues.put("appId", this.field_appId); } if (this.clw) { contentValues.put("version", Integer.valueOf(this.field_version)); } if (this.cjI) { contentValues.put(DownloadSettingTable$Columns.TYPE, Integer.valueOf(this.field_type)); } if (this.cJR) { contentValues.put("retryTimes", Integer.valueOf(this.field_retryTimes)); } if (this.cJS) { contentValues.put("retriedCount", Integer.valueOf(this.field_retriedCount)); } if (this.cJT) { contentValues.put("retryInterval", Long.valueOf(this.field_retryInterval)); } if (this.cJU) { contentValues.put("networkType", Integer.valueOf(this.field_networkType)); } if (this.cJV) { contentValues.put("pkgMd5", this.field_pkgMd5); } if (this.cJW) { contentValues.put("lastRetryTime", Long.valueOf(this.field_lastRetryTime)); } if (this.cJX) { contentValues.put("firstTimeTried", Boolean.valueOf(this.field_firstTimeTried)); } if (this.cJN) { contentValues.put("reportId", Integer.valueOf(this.field_reportId)); } if (this.sKx > 0) { contentValues.put("rowid", Long.valueOf(this.sKx)); } return contentValues; } }
package com.example.railway.controller.rest; import com.example.railway.model.Machinist; import com.example.railway.model.Root; import com.example.railway.service.Machinist.MachinistServiceImpl; import com.example.railway.service.Root.RootServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("api/machinists") public class MachinistRestController { @Autowired MachinistServiceImpl service; @GetMapping("/delete/{id}") public Machinist deleteById(@PathVariable("id") String id){ return service.delete(id); } @PostMapping("/create/") public Machinist create(@RequestBody Machinist machinist){ return service.create(machinist); } @GetMapping("/get/all") public List<Machinist> getAll(){ return service.getAll() ; } @GetMapping("/get/byBirthYear/{year}") public List<Machinist> getAllByBirthYear(@PathVariable("year") int year){ return service.getAllByBirthYear(year ); } @GetMapping("/get/gender/{gender}") public List<Machinist> getAllByGender(@PathVariable("gender") String gender){ return service.getAllByGender(gender) ; } @GetMapping("/get/yearOfMedical/{year}") public List<Machinist> getAllByYearOfMedical(@PathVariable("year") int year){ return service.getAllByYearOfMedical(year) ; } @GetMapping("/get/amount") public Object getAmountOfMachinists(){ return service.getAmountOfMachinists() ; } @GetMapping("/get/{id}") public Machinist getById(@PathVariable("id") String id){ return service.getById(id); } @PostMapping ("/update/") public Machinist update(@RequestBody Machinist machinist){ return service.update(machinist); } }
/** * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */ public class Solution { public int maxPoints(Point[] points) { if(points==null||points.length==0) return 0; if(points.length==1||points.length==2) return points.length; HashMap<Double,Integer> map =new HashMap<Double,Integer>(); double k; int max=1,temp; for(int i=0;i<points.length;i++) { temp=1; map.clear(); for(int j=0;j<points.length;j++) { if(i==j) continue; if(points[i].x==points[j].x&&points[i].y==points[j].y) { temp++; continue; } k = points[i].x==points[j].x ? Double.MAX_VALUE:((double)points[j].y - (double)points[i].y)/((double)points[j].x - (double)points[i].x); if(map.containsKey(k)) map.put(k,map.get(k)+1); else map.put(k,1); } int count=0; for(Integer tmpint:map.values()) if(tmpint>count) count=tmpint; count+=temp; if(count>max) max=count; } return max; } }
import java.io.*; import java.util.*; /** * Created by Denice on 19/11/2560. */ public class TicketCounter extends Thread { ArrayList<Show> shows; private MyBarrier finish; private int checkpoint; private String filename; private Scanner scanner; public void setMyBarrier(MyBarrier f){ finish = f; finish.addThreads(); } public TicketCounter(ArrayList<Show> s, String f, int c){ filename = f; shows =s; checkpoint = c; //Check filename boolean error = true; do{ try { scanner = new Scanner(new File(filename + ".txt")); error = false; } catch (FileNotFoundException e) { System.err.print("Enter file to " + filename +": "); Scanner scan_err = new Scanner(System.in); filename = scan_err.nextLine(); } }while(error); } public int index(int d,int t){ return d*2 -(2-t) -1; } public void run(){ //Read file while (scanner.hasNext()){ int n=scanner.nextInt(); String customerName=scanner.next(); int day=scanner.nextInt(); String time=scanner.next(); int tmp; if(time.equalsIgnoreCase("evening"))tmp=2;else tmp=1; int seats=scanner.nextInt(); if(checkpoint==n) try{ finish.reach(); }catch(Exception e){/*error case : max seats is minimal*/}; // check time to print if(shows.get(index(day,tmp)).bookSeats(customerName,seats)){ System.out.printf("%s > #%2d %s books %d seats for day %d (%s%-10s) -- succeed\r\n", filename,n,customerName,seats,day," ",time); }else if(tmp==1){ if(shows.get(index(day,2)).bookSeats(customerName,seats)){ System.out.printf("%s > #%2d %s books %d seats for day %d (%s%-10s) -- succeed\r\n", filename,n,customerName,seats,day," ","evening"); }else{ System.out.printf("%s > #%2d %s books %d seats for day %d (%s%-10s) -- fail\r\n", filename,n,customerName,seats,day," ",time); } }else{ System.out.printf("%s > #%2d %s books %d seats for day %d (%s%-10s) -- fail\r\n", filename,n,customerName,seats,day," ",time); } } } } /////////////////////////////////////////////////////////////////////////////////////// class MyBarrier { private int numthreads = 0; ArrayList<Show> shows; public MyBarrier(){} public MyBarrier(ArrayList<Show> n){ shows=n; } public synchronized void addThreads() { numthreads++; } public synchronized void reach() { numthreads--; if (numthreads > 0) { try { wait(); } catch (InterruptedException e) {} } else { System.out.println("\nCheckpoint"); ArrayList<Show> forSort = new ArrayList<>(shows); Collections.sort(forSort); for (int i=0;i<forSort.size();i++)forSort.get(i).left(); System.out.println(""); notifyAll(); } } }; ///////////////////////////////////////////////////////////////////////////////////////
package com.sixmac.dao; import com.sixmac.entity.MessageJoin; import com.sixmac.entity.MessageTeam; import com.sixmac.entity.Team; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; /** * Created by Administrator on 2016/6/3 0003 下午 2:33. */ public interface MessageJoinDao extends JpaRepository<MessageJoin, Long> { //根据球队查询等待用户处理的申请加入球队消息 @Query("select a from MessageJoin a where a.team = ?1 and a.status = 0 ") public List<MessageJoin> findByTeam(Team team); @Query("select a from MessageJoin a where a.user.id = ?1 and a.status != 0 ") public List<MessageJoin> findByUserId(Long userId); }
package cn.ehanmy.hospital.mvp.ui.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.jess.arms.base.BaseActivity; import com.jess.arms.base.DefaultAdapter; import com.jess.arms.di.component.AppComponent; import com.jess.arms.http.imageloader.ImageLoader; import com.jess.arms.http.imageloader.glide.ImageConfigImpl; import com.jess.arms.integration.cache.Cache; import com.jess.arms.utils.ArmsUtils; import com.paginate.Paginate; import org.simple.eventbus.Subscriber; import javax.inject.Inject; import butterknife.BindView; import cn.ehanmy.hospital.R; import cn.ehanmy.hospital.app.EventBusTags; import cn.ehanmy.hospital.di.component.DaggerOrderFormCenterComponent; import cn.ehanmy.hospital.di.module.OrderFormCenterModule; import cn.ehanmy.hospital.mvp.contract.OrderFormCenterContract; import cn.ehanmy.hospital.mvp.model.entity.order.GoodsOrderBean; import cn.ehanmy.hospital.mvp.model.entity.order.OrderBean; import cn.ehanmy.hospital.mvp.presenter.OrderFormCenterPresenter; import cn.ehanmy.hospital.mvp.ui.adapter.HeightItemDecoration; import cn.ehanmy.hospital.mvp.ui.adapter.OrderCenterListAdapter; import cn.ehanmy.hospital.mvp.ui.widget.CustomDialog; import cn.ehanmy.hospital.mvp.ui.widget.MoneyView; import static com.jess.arms.utils.Preconditions.checkNotNull; /** * 订单中心页面 */ public class OrderFormCenterActivity extends BaseActivity<OrderFormCenterPresenter> implements OrderFormCenterContract.View, View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, TabLayout.OnTabSelectedListener, OrderCenterListAdapter.OnChildItemClickLinstener { @BindView(R.id.title_Layout) View title_Layout; @BindView(R.id.search_layout) View search_layout; @BindView(R.id.code) View code; @BindView(R.id.search_btn) View search; @BindView(R.id.clear_btn) View clear; @BindView(R.id.search_key) EditText searchKey; // provideCache().put("tellphone", phone.getText().toString()); @BindView(R.id.tab) TabLayout tabLayout; @BindView(R.id.contentList) RecyclerView contentList; @BindView(R.id.no_date) View noDataV; @BindView(R.id.swipeRefreshLayout) SwipeRefreshLayout swipeRefreshLayout; @Inject RecyclerView.LayoutManager mLayoutManager; @Inject OrderCenterListAdapter mAdapter; @Inject ImageLoader mImageLoader; CustomDialog confirmPayDialog = null; private Paginate mPaginate; private boolean isLoadingMore; private boolean hasLoadedAllItems; private int times = 1; @Override public void setupActivityComponent(@NonNull AppComponent appComponent) { DaggerOrderFormCenterComponent //如找不到该类,请编译一下项目 .builder() .appComponent(appComponent) .orderFormCenterModule(new OrderFormCenterModule(this)) .build() .inject(this); } @Override public int initView(@Nullable Bundle savedInstanceState) { return R.layout.activity_order_form_center; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0 } @Override public void initData(@Nullable Bundle savedInstanceState) { code.setVisibility(View.GONE); search.setOnClickListener(this); clear.setOnClickListener(this); new TitleUtil(title_Layout, this, "订单中心"); tabLayout.addTab(tabLayout.newTab().setTag("1").setText("未支付")); tabLayout.addTab(tabLayout.newTab().setTag("31").setText("可消费")); tabLayout.addTab(tabLayout.newTab().setTag("5").setText("已完成")); tabLayout.addTab(tabLayout.newTab().setText("全部")); tabLayout.addOnTabSelectedListener(this); LinearLayout linearLayout = (LinearLayout) tabLayout.getChildAt(0); linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE); linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.drawable.tablayout_divider_vertical)); ArmsUtils.configRecyclerView(contentList, mLayoutManager); contentList.addItemDecoration(new HeightItemDecoration(8)); contentList.setAdapter(mAdapter); mAdapter.setOnChildItemClickLinstener(this); swipeRefreshLayout.setOnRefreshListener(this); initPaginate(); provideCache().put("type", "1"); mPresenter.getOrderList(true); searchKey.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { provideCache().put("key", s + ""); } @Override public void afterTextChanged(Editable s) { } }); } @Override public void showMessage(@NonNull String message) { checkNotNull(message); ArmsUtils.snackbarText(message); } @Override public void launchActivity(@NonNull Intent intent) { checkNotNull(intent); ArmsUtils.startActivity(intent); } @Override public void killMyself() { finish(); } public Activity getActivity() { return this; } @Override public Cache getCache() { return provideCache(); } @Override protected void onDestroy() { DefaultAdapter.releaseAllHolder(contentList);//super.onDestroy()之后会unbind,所有view被置为null,所以必须在之前调用 super.onDestroy(); this.mPaginate = null; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.search_btn: String s = searchKey.getText().toString(); if (ArmsUtils.isEmpty(s)) { showMessage("请输入搜索关键字后重试"); return; } mPresenter.getOrderList(true); break; case R.id.clear_btn: searchKey.setText(""); provideCache().put("key", null); mPresenter.getOrderList(true); break; } } @Override public void showLoading() { swipeRefreshLayout.setRefreshing(true); } @Override public void hideLoading() { swipeRefreshLayout.setRefreshing(false); } /** * 开始加载更多 */ @Override public void startLoadMore() { isLoadingMore = true; } /** * 结束加载更多 */ @Override public void endLoadMore() { isLoadingMore = false; } @Override public void showError(boolean hasDate) { contentList.setVisibility(hasDate ? View.VISIBLE : View.INVISIBLE); noDataV.setVisibility(hasDate ? View.INVISIBLE : View.VISIBLE); } @Subscriber(tag = EventBusTags.CHANGE_APPOINTMENT_TIME) private void updateAppointmentInfo(int index) { mPresenter.getOrderList(true); } @Override public void setLoadedAllItems(boolean has) { this.hasLoadedAllItems = has; } /** * 初始化Paginate,用于加载更多 */ private void initPaginate() { if (mPaginate == null) { Paginate.Callbacks callbacks = new Paginate.Callbacks() { @Override public void onLoadMore() { mPresenter.getOrderList(false); } @Override public boolean isLoading() { return isLoadingMore; } @Override public boolean hasLoadedAllItems() { return hasLoadedAllItems; } }; mPaginate = Paginate.with(contentList, callbacks) .setLoadingTriggerThreshold(0) .build(); mPaginate.setHasMoreDataToLoad(false); } } @Override public void onRefresh() { mPresenter.getOrderList(true); } @Override public void onTabSelected(TabLayout.Tab tab) { switch (tab.getPosition()) { case 0: provideCache().put("type", "1"); break; case 1: provideCache().put("type", "31"); break; case 2: provideCache().put("type", "5"); break; case 3: provideCache().put("type", ""); break; } mPresenter.getOrderList(true); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } @Override public void onChildItemClick(View v, OrderCenterListAdapter.ViewName viewname, int position) { switch (viewname) { case DETAIL: Intent intent = new Intent(OrderFormCenterActivity.this, OrderInfoActivity.class); intent.putExtra(OrderInfoActivity.KEY_FOR_ORDER_ID, mAdapter.getItem(position).getOrderId()); startActivity(intent); break; case PAY: Intent payIntent = new Intent(OrderFormCenterActivity.this, CommitOrderActivity.class); payIntent.putExtra(CommitOrderActivity.KEY_FOR_GO_IN_TYPE, CommitOrderActivity.GO_IN_TYPE_ORDER_LIST); payIntent.putExtra(CommitOrderActivity.KEY_FOR_ORDER_BEAN, mAdapter.getItem(position)); startActivity(payIntent); break; case APPOINTMENT: // 预约 Intent intent2 = new Intent(this, ChoiceTimeActivity.class); intent2.putExtra("from", "orderCenter"); intent2.putExtra("projectId", mAdapter.getItem(position).getGoodsList().get(0).getProjectId()); ArmsUtils.startActivity(intent2); break; case HUAKOU: confirmPay(mAdapter.getItem(position)); break; case UNAPPOINTMENT: OrderBean item = mAdapter.getItem(position); mPresenter.unappointment(item.getGoodsList().get(0).getReservationId()); break; case CHANGE: // 修改预约 Intent intent3 = new Intent(this, ChoiceTimeActivity.class); intent3.putExtra("from", "orderCenterDetail"); GoodsOrderBean goodsOrderBean = mAdapter.getItem(position).getGoodsList().get(0); intent3.putExtra("projectId", goodsOrderBean.getProjectId()); intent3.putExtra("reservationId",goodsOrderBean.getReservationId()); ArmsUtils.startActivity(intent3); break; } } private void confirmPay(final OrderBean orderBean) { confirmPayDialog = CustomDialog.create(getSupportFragmentManager()) .setViewListener(new CustomDialog.ViewListener() { @Override public void bindView(View view) { TextView et = view.findViewById(R.id.count); et.setText("" + times); view.findViewById(R.id.add).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (times < orderBean.getGoodsList().get(0).getSurplusTimes()) { times++; et.setText("" + times); } } }); view.findViewById(R.id.minus).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (times > 1) { times--; et.setText("" + times); } } }); GoodsOrderBean goodsOrderBean = orderBean.getGoodsList().get(0); OrderFormCenterActivity.this.mImageLoader.loadImage(OrderFormCenterActivity.this, ImageConfigImpl .builder() .placeholder(R.drawable.place_holder_img) .url(goodsOrderBean.getImage()) .imageView(view.findViewById(R.id.image)) .build()); ((TextView) view.findViewById(R.id.name)).setText(goodsOrderBean.getName()); MoneyView moneyView = view.findViewById(R.id.price); moneyView.setMoneyText(ArmsUtils.formatLong(orderBean.getTotalPrice())); view.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GoodsOrderBean goodsOrderBean1 = orderBean.getGoodsList().get(0); mPresenter.orderHuakou(goodsOrderBean1.getReservationId(), orderBean.getOrderId(), times); } }); } }) .setLayoutRes(R.layout.order_center_huakou_dialog_layout) .setDimAmount(0.5f) .isCenter(true) .setCancelOutside(false) .setWidth(ArmsUtils.dip2px(OrderFormCenterActivity.this, 556)) .show(); } public void huakouOk(boolean isOk){ if(confirmPayDialog != null){ confirmPayDialog.dismiss(); confirmPayDialog = null; } if(isOk){ mPresenter.getOrderList(true); }else{ } } }
package test; import java.util.Vector; import model.AccessPoint; import model.AccessPointNetwork; import model.GridPoint; import model.Level; import model.Plan; import model.Room; import model.impl.AccessPointNetworkImpl; import model.impl.GridPointFactory; import model.impl.LevelImpl; import model.impl.PlanImpl; import model.impl.RoomImpl; public class GeneticSolutionPlan extends PlanImpl { private double fitness; private AccessPointNetwork accessPointNetwork; private Vector<Level> levels; /** * A lot of cloning, we need new gridpoint objects * @param original */ public GeneticSolutionPlan(Plan original){ original.getLevels(); original.getAccessPointNetwork(); // first create new levels levels = new Vector<Level>(); for(Level level : original.getLevels()){ Level newLevel = new LevelImpl(); for(Room room : level.getRooms()){ Room newRoom = new RoomImpl(room.getName(), room.getWalls()); for(GridPoint gp : room.getGridPoints()){ GridPoint newGP = gp.clone(); newGP.setRoom(newRoom); } } } // create a copy of the AP vector accessPointNetwork = new AccessPointNetworkImpl(); for(Level level : original.getLevels()){ for(AccessPoint ap : original.get_AccessPoints(level.getNumber())){ accessPointNetwork.addAccessPoint(ap); } } } }
package com.tfjybj.integral.provider; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StopWatch; /** * @author quinn * @version 创建时间:2018/10/10 17:41 */ public class TestExecTimeWatcher extends TestWatcher { private static final Logger logger = LoggerFactory.getLogger(TestExecTimeWatcher.class); private StopWatch sw = new StopWatch(); protected void starting(Description description) { String name = description.getDisplayName(); //description.getTestClass() + " : " + description.getMethodName() + " _ " + logger.warn(""); logger.warn("---------- Begin Test : " + name + "----------------------------------------------------------"); sw.start(); } protected void finished(Description description) { sw.stop(); long elapsed = sw.getLastTaskTimeMillis(); String name = description.getDisplayName(); //description.getTestClass() + " : " + description.getMethodName() + " _ " + logger.warn(">>>>> 执行时长: " + elapsed + ". " + name + " <<<<<<<<<<<<<<<<<<<<"); } }
/** * @author Pawel Wloch @SoftLab * @date 12.10.2018 */ package org.softlab.cs.tradevalidator.validation.service; import java.io.IOException; public interface TradeDataValidationService { /** * * @param tradeData to be validated. Should come as json in String * @return json array of json objects written in simple string * @throws IOException (should never) */ public String validateTradeData(String tradeData); }
// @formatter:off package logic; import static logic.Parsable.ParsableCache.*; public interface Parsable { ParsableCache parsableCache = new ParsableCache(); static void addToParserCache (char c) { if (ParsableCache.isParserAValue (c) || getParserCache ().equals ("") && c == '.') setParserCache (parsableCache.parserCache += c); } static void resetParsableCache () { parsableCache.parserCache = ""; parsableCache.isValuePositive = true; } static double dumpParserCache() { if (parsableCache.parserCache.length () == 0) return Double.NaN; double cache = Double.parseDouble (getParserCacheString ()); Parsable.resetParsableCache (); return cache; } static void toggleSign () { parsableCache.isValuePositive = ! parsableCache.isValuePositive; } static boolean isParserAValue() { try { Double.parseDouble (Parsable.parsableCache.parserCache); return true; } catch (NumberFormatException e) { return false; } } // Parsable implementation -------------------------------------------------------------------------------------------- class ParsableCache implements Parsable { boolean isValuePositive = true; String parserCache = ""; static public String getParserCache () { return Parsable.parsableCache.parserCache; } static public void setParserCache (String string) { Parsable.parsableCache.parserCache = string; } static boolean isParserAValue (char c) { try { Double.parseDouble (Parsable.parsableCache.parserCache + c); return true; } catch (NumberFormatException e) { return false; } } static String getParserCacheString () { return Parsable.parsableCache.isValuePositive ? Parsable.parsableCache.parserCache : "-" + Parsable.parsableCache.parserCache; } } } // @formatter:on
package com.se.details.dto; import lombok.Getter; import java.util.List; import java.util.Map; public class DetailsActorsResponse { private DetailsActorsResponse() { } @Getter public static class ActorMessageReponse { private final Map<String, List<PartdetailsFeatures>> features; private final String category; private final Long actorId; public ActorMessageReponse(Map<String, List<PartdetailsFeatures>> features, String category, Long actorId) { this.features = features; this.category = category; this.actorId = actorId; } } }
import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Arrays; import static org.junit.Assert.*; public class MatricesTest { private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); private final PrintStream originalOut = System.out; private final PrintStream originalErr = System.err; @Before public void setUpStreams() { System.setOut(new PrintStream(outContent)); System.setErr(new PrintStream(errContent)); } @After public void restoreStreams() { System.setOut(originalOut); System.setErr(originalErr); } @Test public void testGradient() { int[][] one = new int[][]{{12, 1, 4}, {3, 6, 8}, {2, 5, 10}, {7, 9, 11}}; assertArrayEquals(new int[][]{{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}}, Matrices.gradient(one)); } @Test public void testToArray() { int[][] one = new int[][]{{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}}; System.out.println(Arrays.toString(Matrices.toArray(one))); assertArrayEquals(new int[]{1,2,3,4,5,6,7,8,9,10,11,12}, Matrices.toArray(one)); int[][] two= new int[][]{{1,2,3}, {4,5,6}, {7,8,9}}; System.out.println(Arrays.toString(Matrices.toArray(two))); assertArrayEquals(new int[]{1,2,3,4,5,6,7,8,9}, Matrices.toArray(two)); int[][] three = new int[][]{{1,2,3}}; System.out.println(Arrays.toString(Matrices.toArray(three))); assertArrayEquals(new int[]{1,2,3}, Matrices.toArray(three)); } @Test public void testSpiralPrint(){ int[][] one = new int[][]{{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}}; Matrices.spiralPrint(one); assertEquals("1 2 3 6 9 12 11 10 7 4 5 8 ", outContent.toString()); } @Test public void testMultiTable(){ Matrices.multiTable(12); assertEquals("1\t2\t3\t4\t5\t6\t7\t8\t9\t10\t11\t12\t\n" + "2\t4\t6\t8\t10\t12\t14\t16\t18\t20\t22\t24\t\n" + "3\t6\t9\t12\t15\t18\t21\t24\t27\t30\t33\t36\t\n" + "4\t8\t12\t16\t20\t24\t28\t32\t36\t40\t44\t48\t\n" + "5\t10\t15\t20\t25\t30\t35\t40\t45\t50\t55\t60\t\n" + "6\t12\t18\t24\t30\t36\t42\t48\t54\t60\t66\t72\t\n" + "7\t14\t21\t28\t35\t42\t49\t56\t63\t70\t77\t84\t\n" + "8\t16\t24\t32\t40\t48\t56\t64\t72\t80\t88\t96\t\n" + "9\t18\t27\t36\t45\t54\t63\t72\t81\t90\t99\t108\t\n" + "10\t20\t30\t40\t50\t60\t70\t80\t90\t100\t110\t120\t\n" + "11\t22\t33\t44\t55\t66\t77\t88\t99\t110\t121\t132\t\n" + "12\t24\t36\t48\t60\t72\t84\t96\t108\t120\t132\t144\t\n", outContent.toString()); } @Test public void testOceans(){ int[][] one = new int[][]{ {1,0,0,0}, {1,0,0,0}, {1,0,0,0}, {1,0,0,0}}; int[][] two = new int[][]{ {0,1,1,0}, {0,1,0,0}, {1,0,0,0}, {0,1,0,0}}; int[][] three = new int[][]{{1,1,1,1}, {1,1,1,1}, {1,1,1,1}, {1,1,1,1}}; int[][] four = new int[][]{{1,0,1,1}, {0,0,0,1}, {1,0,0,1}, {0,0,1,1}}; assertEquals(1, Matrices.countIslands(one)); assertEquals(1, Matrices.countIslands(two)); assertEquals(1, Matrices.countIslands(three)); assertEquals(3, Matrices.countIslands(four)); } }
package com.somethinglurks.jbargain.scraper.node.post; import com.somethinglurks.jbargain.api.node.post.ForumPost; import com.somethinglurks.jbargain.api.node.post.poll.PollOption; import com.somethinglurks.jbargain.scraper.node.post.poll.ScraperPollOption; import com.somethinglurks.jbargain.scraper.user.ScraperUser; import com.somethinglurks.jbargain.scraper.util.date.StringToDate; import org.jsoup.nodes.Element; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ScraperForumPost extends ScraperPost implements ForumPost { public ScraperForumPost(Element element, ScraperUser user) { super(element, user); } @Override public List<PollOption> getPollOptions() { boolean scoresHidden = element.select("div#poll li div.n-vote").text().contains("?"); List<PollOption> pollOptions = new ArrayList<>(); for (Element item : element.select("div#poll li")) { pollOptions.add(new ScraperPollOption(item, this.getId(), scoresHidden)); } return pollOptions; } @Override public boolean isPollExpired() { return element.select("div#poll span.marker.expired").size() == 1; } @Override public Date getPollExpiryDate() { // Check if poll has an expiration date if (isPollExpired() || element.select("div#poll span.options i.fa-calendar").size() == 0) { return null; } else { String dateString = element.select("div#poll span.options") .text() .substring(4); // Ignore the three-character day, the comma, and the space before the date return StringToDate.parsePostDate(dateString, true); } } @Override public boolean canSuggestPollOptions() { return element.select("div#poll span.options i.fa-comment").size() == 1; } @Override public boolean canChangeVotes() { return element.select("div#poll span.options i.fa-exchange").size() == 1; } }
package graphana.script.bindings.visualization; import genscript.ParseSystem; import genscript.execution.ExecuterTree; import genscript.execution.ExecuterTreeElem; import genscript.execution.ExecuterTreeNodeLazy; import genscript.parse.IndexReader; import genscript.parse.NTProductions; import genscript.parse.SearchGraph; import genscript.syntax.TokenizedParser; import global.StringOps; import graphana.graphs.GraphLibrary; import graphana.graphs.defaultstates.StatusFullText; import graphana.graphs.exceptions.InvalidGraphConfigException; import libraries.jung.JungLib; import scriptinterface.execution.ExecutionScope; import java.util.HashMap; public class ScriptVisualizer { public static <VertexType, EdgeType, ScopeType extends ExecutionScope, ReaderType extends IndexReader> VertexType execTreeToGraphib(ExecuterTreeElem<ScopeType, ReaderType> curElem, GraphLibrary<VertexType, EdgeType> targetGraph) { VertexType result = targetGraph.addVertex(curElem.getName()); targetGraph.setVertexData(result, new StatusFullText(curElem.toString())); if (curElem instanceof ExecuterTreeNodeLazy) { ExecuterTreeNodeLazy<ScopeType, ReaderType> node = (ExecuterTreeNodeLazy<ScopeType, ReaderType>) curElem; for (ExecuterTreeElem<ScopeType, ReaderType> child : node.getChildren()) { VertexType childVertex = execTreeToGraphib(child, targetGraph); targetGraph.addEdge(result, childVertex); } } return result; } public static <VertexType, EdgeType, ScopeType extends ExecutionScope, ReaderType extends IndexReader> VertexType execTreeToGraphLib(ExecuterTree<ScopeType, ReaderType> executerTree, GraphLibrary<VertexType, EdgeType> targetGraph) { return execTreeToGraphib(executerTree.getRoot(), targetGraph); } public static <ScopeType extends ExecutionScope, ReaderType extends IndexReader> JungLib execTreeToGraphLib (ExecuterTree<ScopeType, ReaderType> executerTree) { JungLib result = new JungLib(); try { result.createGraph(true, false, false); } catch (InvalidGraphConfigException e) { } execTreeToGraphLib(executerTree, result); return result; } private static <VertexType, EdgeType> VertexType getSyntaxVertex(SearchGraph.Node curNode, GraphLibrary<VertexType, EdgeType> targetGraph) { for (VertexType vertex : targetGraph.getVertices()) { if (((VertexNodeHolder) targetGraph.getVertexData(vertex)).getSearchNode() == curNode) return vertex; } return null; } private static <VertexType, EdgeType> VertexType addSyntaxVertex(SearchGraph.Node curNode, GraphLibrary<VertexType, EdgeType> targetGraph, boolean isRoot, boolean showPriorities, NTProductions curParser) { VertexType result = getSyntaxVertex(curNode, targetGraph); if (result != null) return result; result = targetGraph.addVertex(); targetGraph.setVertexData(result, new VertexNodeHolder(curNode, isRoot, showPriorities, curParser)); return result; } private static <VertexType, EdgeType> EdgeType addSyntaxEdge(SearchGraph.Node childNode, NTProductions searchGraph, VertexType startVertex, String text, GraphLibrary<VertexType, EdgeType> targetGraph, boolean showPriorities, HashMap<String, Boolean> alreadyCreated) { VertexType childVertex = getSyntaxVertex(childNode, targetGraph); boolean alrAdded = (childVertex != null); if (!alrAdded) childVertex = addSyntaxVertex(childNode, targetGraph, false, showPriorities, searchGraph); EdgeType edge = targetGraph.getEdge(startVertex, childVertex); if (edge == null) { edge = targetGraph.addEdge(startVertex, childVertex); targetGraph.setEdgeData(edge, new StatusFullText(text)); } else { String prevText = ((StatusFullText) targetGraph.getEdgeData(edge)).getText("", null); if (!prevText.endsWith(" ...")) targetGraph.setEdgeData(edge, new StatusFullText(((prevText.length() > 12) ? prevText + " ..." : prevText + ", " + text))); } if (!alrAdded) { parserToGraphLib(searchGraph, childVertex, targetGraph, showPriorities, alreadyCreated); } return edge; } private static <VertexType, EdgeType> void parserToGraphLib(NTProductions searchGraph, VertexType curVertex, GraphLibrary<VertexType, EdgeType> targetGraph, boolean showPriorities, HashMap<String, Boolean> alreadyCreated) { SearchGraph.Node curNode = ((VertexNodeHolder) targetGraph.getVertexData(curVertex)).getSearchNode(); int i = 0; for (SearchGraph.Node child : curNode.getChildren()) { if (child != null) { String text; if (searchGraph instanceof TokenizedParser) text = ((TokenizedParser) searchGraph).getTokenSet().getTokenIdentifier(i).getName(); else text = "" + (char) i; addSyntaxEdge(child, searchGraph, curVertex, text, targetGraph, showPriorities, alreadyCreated); } i++; } if (curNode.hasNonTerminal()) { NTProductions subSearchGraph = curNode.getNonTerminal().getSubSearchGraph(); addSyntaxEdge(curNode.getNonTerminal().getNextNode(), searchGraph, curVertex, "<" + subSearchGraph .getName() + ">" + (showPriorities ? " [" + StringOps.intToStr(curNode.getNonTerminal() .getPriority()) + "]" : ""), targetGraph, showPriorities, alreadyCreated); parserToGraphLib(subSearchGraph, targetGraph, showPriorities, alreadyCreated); } } private static <VertexType, EdgeType> void parserToGraphLib(NTProductions parser, GraphLibrary<VertexType, EdgeType> targetGraph, boolean showPriorities, HashMap<String, Boolean> alreadyCreated) { if (alreadyCreated.containsKey(parser.getName())) return; alreadyCreated.put(parser.getName(), true); NTProductions curParser = parser; while (curParser != null) { VertexType vRoot = addSyntaxVertex(curParser.getRoot(), targetGraph, true, showPriorities, parser); parserToGraphLib(curParser, vRoot, targetGraph, showPriorities, alreadyCreated); curParser = curParser.getAlternativeParser(); } } public static <VertexType, EdgeType> void parserToGraphLib(NTProductions parser, GraphLibrary<VertexType, EdgeType> targetGraph, boolean showPriorities) { parserToGraphLib(parser, targetGraph, showPriorities, new HashMap<>()); } public static <VertexType, EdgeType> void parseSystemToGraphLib(ParseSystem<?, ?, ?> parseSystem, GraphLibrary<VertexType, EdgeType> targetGraph, boolean showPriorities) { parserToGraphLib(parseSystem.getStartParser(), targetGraph, showPriorities); } public static JungLib parseSystemToJungLib(ParseSystem<?, ?, ?> parseSystem, boolean showPriorities) { JungLib result = new JungLib(); try { result.createGraph(true, false, false); } catch (InvalidGraphConfigException e) { e.printStackTrace(); } parseSystemToGraphLib(parseSystem, result, showPriorities); return result; } public static JungLib parserToJungLib(NTProductions parser, boolean showPriorities) { JungLib result = new JungLib(); try { result.createGraph(true, false, false); } catch (InvalidGraphConfigException e) { e.printStackTrace(); } parserToGraphLib(parser, result, showPriorities); return result; } }
/* BLE demo: Use a single button to send data to the Duo board from the Android app to control the * LED on and off on the board through BLE. * * The app is built based on the example code provided by the RedBear Team: * https://github.com/RedBearLab/Android */ package com.example.lianghe.InClass_EXE2_REGLed; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.os.IBinder; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.example.lianghe.InClass_EXE2_REGLed.BLE.RBLGattAttributes; import com.example.lianghe.InClass_EXE2_REGLed.BLE.RBLService; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { // Define the device name and the length of the name // Note the device name and the length should be consistent with the ones defined in the Duo sketch private String mTargetDeviceName = "BLEDemo"; private int mNameLen = 0x08; private final static String TAG = MainActivity.class.getSimpleName(); // Declare all variables associated with the UI components private Button mConnectBtn = null; private TextView mDeviceName = null; private TextView mRssiValue = null; private TextView mUUID = null; private SeekBar mPWMOutSeekbar; private String mBluetoothDeviceName = ""; private String mBluetoothDeviceUUID = ""; // Declare all Bluetooth stuff private BluetoothGattCharacteristic mCharacteristicTx = null; private RBLService mBluetoothLeService; private BluetoothAdapter mBluetoothAdapter; private BluetoothDevice mDevice = null; private String mDeviceAddress; private boolean flag = true; private boolean mConnState = false; private boolean mScanFlag = false; private byte[] mData = new byte[3]; private static final int REQUEST_ENABLE_BT = 1; private static final long SCAN_PERIOD = 1000; // millis final private static char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; // Process service connection. Created by the RedBear Team private final ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder service) { mBluetoothLeService = ((RBLService.LocalBinder) service) .getService(); if (!mBluetoothLeService.initialize()) { Log.e(TAG, "Unable to initialize Bluetooth"); finish(); } } @Override public void onServiceDisconnected(ComponentName componentName) { mBluetoothLeService = null; } }; private void setButtonDisable() { flag = false; mConnState = false; mPWMOutSeekbar.setEnabled(flag); mConnectBtn.setText("Connect"); mRssiValue.setText(""); mDeviceName.setText(""); mUUID.setText(""); } private void setButtonEnable() { flag = true; mConnState = true; mPWMOutSeekbar.setEnabled(flag); mConnectBtn.setText("Disconnect"); } // Process the Gatt and get data if there is data coming from Duo board. Created by the RedBear Team private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (RBLService.ACTION_GATT_DISCONNECTED.equals(action)) { Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT).show(); setButtonDisable(); } else if (RBLService.ACTION_GATT_SERVICES_DISCOVERED .equals(action)) { Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show(); getGattService(mBluetoothLeService.getSupportedGattService()); } else if (RBLService.ACTION_GATT_RSSI.equals(action)) { displayData(intent.getStringExtra(RBLService.EXTRA_DATA)); } } }; // Display the received RSSI on the interface private void displayData(String data) { if (data != null) { mRssiValue.setText(data); mDeviceName.setText(mBluetoothDeviceName); mUUID.setText(mBluetoothDeviceUUID); } } // Get Gatt service information for setting up the communication private void getGattService(BluetoothGattService gattService) { if (gattService == null) return; setButtonEnable(); startReadRssi(); mCharacteristicTx = gattService .getCharacteristic(RBLService.UUID_BLE_SHIELD_TX); } // Start a thread to read RSSI from the board private void startReadRssi() { new Thread() { public void run() { while (flag) { mBluetoothLeService.readRssi(); try { sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }; }.start(); } // Scan all available BLE-enabled devices private void scanLeDevice() { new Thread() { @Override public void run() { mBluetoothAdapter.startLeScan(mLeScanCallback); try { Thread.sleep(SCAN_PERIOD); } catch (InterruptedException e) { e.printStackTrace(); } mBluetoothAdapter.stopLeScan(mLeScanCallback); } }.start(); } // Callback function to search for the target Duo board which has matched UUID // If the Duo board cannot be found, debug if the received UUID matches the predefined UUID on the board private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) { runOnUiThread(new Runnable() { @Override public void run() { byte[] serviceUuidBytes = new byte[16]; String serviceUuid = ""; for (int i = (21+mNameLen), j = 0; i >= (6+mNameLen); i--, j++) { serviceUuidBytes[j] = scanRecord[i]; } /* * This is where you can test if the received UUID matches the defined UUID in the Arduino * Sketch and uploaded to the Duo board: 0x713d0000503e4c75ba943148f18d941e. */ serviceUuid = bytesToHex(serviceUuidBytes); if (stringToUuidString(serviceUuid).equals( RBLGattAttributes.BLE_SHIELD_SERVICE .toUpperCase(Locale.ENGLISH)) && device.getName().equals(mTargetDeviceName)) { mDevice = device; mBluetoothDeviceName = mDevice.getName(); mBluetoothDeviceUUID = serviceUuid; } } }); } }; // Convert an array of bytes into Hex format string private String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; int v; for (int j = 0; j < bytes.length; j++) { v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } // Convert a string to a UUID format private String stringToUuidString(String uuid) { StringBuffer newString = new StringBuffer(); newString.append(uuid.toUpperCase(Locale.ENGLISH).substring(0, 8)); newString.append("-"); newString.append(uuid.toUpperCase(Locale.ENGLISH).substring(8, 12)); newString.append("-"); newString.append(uuid.toUpperCase(Locale.ENGLISH).substring(12, 16)); newString.append("-"); newString.append(uuid.toUpperCase(Locale.ENGLISH).substring(16, 20)); newString.append("-"); newString.append(uuid.toUpperCase(Locale.ENGLISH).substring(20, 32)); return newString.toString(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Associate all UI components with variables mConnectBtn = (Button) findViewById(R.id.connectBtn); mDeviceName = (TextView) findViewById(R.id.deviceName); mRssiValue = (TextView) findViewById(R.id.rssiValue); mPWMOutSeekbar = (SeekBar) findViewById(R.id.LEDGreenSeekBar); mUUID = (TextView) findViewById(R.id.uuidValue); // Connection button click event mConnectBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mScanFlag == false) { // Scan all available devices through BLE scanLeDevice(); Timer mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { if (mDevice != null) { mDeviceAddress = mDevice.getAddress(); mBluetoothLeService.connect(mDeviceAddress); mScanFlag = true; } else { runOnUiThread(new Runnable() { public void run() { Toast toast = Toast .makeText( MainActivity.this, "Couldn't search Ble Shiled device!", Toast.LENGTH_SHORT); toast.setGravity(0, 0, Gravity.CENTER); toast.show(); } }); } } }, SCAN_PERIOD); } System.out.println(mConnState); if (mConnState == false) { mBluetoothLeService.connect(mDeviceAddress); } else { mBluetoothLeService.disconnect(); mBluetoothLeService.close(); setButtonDisable(); } } }); // Send data to Duo board // Configure the servo Seekbar mPWMOutSeekbar.setEnabled(false); mPWMOutSeekbar.setMax(255); // Servo can rotate from 0 to 180 degree mPWMOutSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { byte[] buf = new byte[] { (byte) 0x02, (byte) 0x00, (byte) 0x00 }; buf[1] = (byte) mPWMOutSeekbar.getProgress(); mCharacteristicTx.setValue(buf); mBluetoothLeService.writeCharacteristic(mCharacteristicTx); } }); // Bluetooth setup. Created by the RedBear team. if (!getPackageManager().hasSystemFeature( PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, "Ble not supported", Toast.LENGTH_SHORT) .show(); finish(); } final BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = mBluetoothManager.getAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(this, "Ble not supported", Toast.LENGTH_SHORT) .show(); finish(); return; } Intent gattServiceIntent = new Intent(MainActivity.this, RBLService.class); bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE); } @Override protected void onResume() { super.onResume(); // Check if BLE is enabled on the device. Created by the RedBear team. if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter()); } @Override protected void onStop() { super.onStop(); flag = false; unregisterReceiver(mGattUpdateReceiver); } @Override protected void onDestroy() { super.onDestroy(); if (mServiceConnection != null) unbindService(mServiceConnection); } // Create a list of intent filters for Gatt updates. Created by the RedBear team. private static IntentFilter makeGattUpdateIntentFilter() { final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(RBLService.ACTION_GATT_CONNECTED); intentFilter.addAction(RBLService.ACTION_GATT_DISCONNECTED); intentFilter.addAction(RBLService.ACTION_GATT_SERVICES_DISCOVERED); intentFilter.addAction(RBLService.ACTION_DATA_AVAILABLE); intentFilter.addAction(RBLService.ACTION_GATT_RSSI); return intentFilter; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // User chose not to enable Bluetooth. if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) { finish(); return; } super.onActivityResult(requestCode, resultCode, data); } }
package com.blackvelvet.cybos.bridge.cpforedib ; import com4j.*; /** * Defines methods to create COM objects */ public abstract class ClassFactory { private ClassFactory() {} // instanciation is not allowed /** * CpForeField Class */ public static com.blackvelvet.cybos.bridge.cpforedib.ICpForeField createCpForeField() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.ICpForeField.class, "{93CEC1C0-47AE-474C-93BD-A952B67C5256}" ); } /** * CpForeFields Class */ public static com.blackvelvet.cybos.bridge.cpforedib.ICpForeFields createCpForeFields() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.ICpForeFields.class, "{EF426FAC-8B2F-4D4E-883F-42ADCA3D258C}" ); } /** * OvFutMst Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createOvFutMst() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{60291C5F-0F0D-413F-A7E5-8FB699E8F050}" ); } /** * OvFutCur Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createOvFutCur() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{10C45173-F22A-4037-AEF9-0A13BA3FA146}" ); } /** * OvFutBid Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createOvFutBid() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{2117D620-501B-48F5-A6C0-2EA83A91453A}" ); } /** * FxMgMst Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createFxMgMst() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{DFCAA3BE-2C51-4D22-8B40-8BD5A26987B9}" ); } /** * FxMgCur Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createFxMgCur() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{1BA716D8-C71E-42B8-813D-F07BBDC08887}" ); } /** * FxMgOrdReceive Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createFxMgOrdReceive() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{1BDD5625-B398-44EF-B81D-28F599E5F932}" ); } /** * FxMgConclusion Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createFxMgConclusion() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{1593F7B5-6E9A-47D2-A121-0A370A363F64}" ); } /** * FxMgBalance Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createFxMgBalance() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{CDB1D9C6-C6DF-4004-8BB7-E6D282BBF938}" ); } /** * OvFutOrdReceive Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createOvFutOrdReceive() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{DF4AF880-ED67-4825-A61C-24D1E5D62BF1}" ); } /** * OvFutConclusion Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createOvFutConclusion() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{F49DAF7B-8F8C-4EBA-A379-A7A8D7119152}" ); } /** * OvFutBalance Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createOvFutBalance() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{B5F48DBB-14A4-4346-966C-35187E1390B6}" ); } /** * OvFutureChart Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createOvFutureChart() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{C5082D47-B750-4F6B-A71B-2FFF2BECEFB9}" ); } /** * FxMgChart Class */ public static com.blackvelvet.cybos.bridge.cpforedib.IForeDib createFxMgChart() { return COM4J.createInstance( com.blackvelvet.cybos.bridge.cpforedib.IForeDib.class, "{13C7321A-77F2-46EA-8330-405553D0EB44}" ); } }
package com.tencent.mm.plugin.collect.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.plugin.collect.ui.CollectMainUI.15; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.x; class CollectMainUI$15$1 implements OnClickListener { final /* synthetic */ 15 hYT; CollectMainUI$15$1(15 15) { this.hYT = 15; } public final void onClick(DialogInterface dialogInterface, int i) { x.i("MicroMsg.CollectMainUI", "save code from click"); if (this.hYT.hYN.hYH != null) { CollectMainUI.cn(this.hYT.hYN.hYH.username, this.hYT.hYN.hYH.rWY); h.mEJ.h(15387, new Object[]{Integer.valueOf(2)}); } } }
/* 2. Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. */ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { const int TEN = 10; ListNode curr1 = l1; ListNode curr2 = l2; int carry = l1.val + l2.val; ListNode result = new ListNode(carry%10); carry /= TEN; ListNode curr_res = result; while (curr1.next != null || curr2.next != null) { if (curr1.next != null) { carry += curr1.next.val; curr1 = curr1.next; } if (curr2.next != null) { carry += curr2.next.val; curr2 = curr2.next; } curr_res.next = new ListNode(carry%TEN); carry /= TEN; curr_res = curr_res.next; } if (carry != 0) curr_res.next = new ListNode(carry%TEN); return result; } }
package com.quiz.projectWilayah.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.quiz.projectWilayah.entity.DesaEntity; import com.quiz.projectWilayah.entity.KecamatanEntity; @Repository public interface DesaRepository extends JpaRepository<DesaEntity, Integer>{ List<DesaEntity> findByKecamatanEntityKecamatanCode(String kecamatanCode); List<DesaEntity> findByProvinsiEntityProvinsiCode(String provinsiCode); List<DesaEntity> findByKabupatenEntityKabupatenCode(String kabupatenCode); @Query(value = "select * from desa_entity where status = 1 and id = ?", nativeQuery = true) List<DesaEntity> findDesaActiveById(Integer id); @Query(value = "select * from desa_entity where status = 1 and desa_code = ?", nativeQuery = true) List<DesaEntity> findDesaActiveByCode(String code); @Query(value = "select * from desa_entity where status = 1", nativeQuery = true) List<DesaEntity> findAllDesaActive(); }
package edu.hust.mr.InvertedIdx; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob; import org.apache.hadoop.mapreduce.lib.jobcontrol.JobControl; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; /** *由于reduce的输入无法将相同的单词形成一个list集合,因此考虑使用两个MapReduce。 * * 思路2:(w-单词,f-词频,d-文件) * job1的Map端: * 1,map():将每个文件按照<w, d>键值对的形式输出; * 2,combiner():将每个文件中相同的单词累加,统计出该文件的单词词频,形成新的键值对<w:f, d>; * 3,MapReduce框架会自动将combiner的输出结果按key进行多次排序,<w1:2, d1> <w1:3, d3> <w2:2, d1> <w3:1, d2>....; * 4,patition():将排序后的结果进行分区,使用自定义分区方式(第3步排序时为了方便第4步的快速分区); * Reduce端: * 5,MapReduce框架自动将每个分区的结果进行排序汇总,形成<key,list<value>>; * 6,reduce():拆分list<value>,改变组合形式,因为从patition到reduce的过程可能是这样的: * w1:2 d1 w1:2 list<d1,d2> w1 d1:2 * w1:2 d2 ==> w1:3 list<d3> ==> w1 d2:2 * w1:3 d3 w1 d3:3 * patition输出 reduce的输入 reduce的输出 * job2的Map端: * 7,map():为了保证同一个单词交给同一个reduce,将输入拆分成<w, d:f>键值对的形式直接交给reduce; * 8,reduce():组合,生成文档列表 */ public class InvertedIndex_V22 extends Configured implements Tool { enum counter { LINESKIP } static class InvertedIndexMapper1 extends Mapper<LongWritable, Text, Text, Text> { Text outputKey = new Text(); Text outputValue = new Text(); FileSplit split; @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { try { split = (FileSplit) context.getInputSplit(); StringTokenizer strs = new StringTokenizer(value.toString()); while (strs.hasMoreElements()) { String str = (String) strs.nextElement(); outputKey.set(str); outputValue.set(split.getPath().getName()); context.write(outputKey, outputValue); } } catch (Exception e) { context.getCounter(counter.LINESKIP).increment(1);//源文件格式错误,则跳过,计数器+1 return; } } } /** * 统计各文档的词频 */ static class InvertedIndexCombiner1 extends Reducer<Text, Text, Text, Text> { Text outputKey = new Text(); Text outputValue = new Text(); @Override public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { Text outputValue = new Text(); try { //<word, list<doc1,doc1,doc1>> 统计word的在单文件中的词频 int sum =0; for (Text value : values) { sum++; if(value != null){ outputValue = value;//测试发现values的第一个元素为空 } } String outputkey = key.toString() + ":" + sum; outputKey .set(outputkey); context.write(outputKey, outputValue); } catch (Exception e) { context.getCounter(counter.LINESKIP).increment(1);//源文件格式错误,则跳过,计数器+1 return; } } } /** * 按单词分区 */ static class WordPatitioner1 extends HashPartitioner<Text, Text> { public int getPartition(Text key, Text value, int numReduceTasks) { key = new Text(key.toString().split(":")[0]); return super.getPartition(key , value, numReduceTasks); }; } /** * 改变组合形式 */ static class InvertedIndexReducer1 extends Reducer<Text, Text, Text, Text> { @Override public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { String[] line = key.toString().split(":"); String word = line[0]; String freq = line[1]; for (Text t : values) { context.write(new Text(word), new Text(t.toString() + ":" + freq)); } } } //////////////////////////////////////////////////////////////////////////////////////////// /* job1的输出结果 Everything 1.txt:1 Everything 2.txt:2 MapReduce 2.txt:1 MapReduce 1.txt:2 MapReduce 3.txt:3 hello 3.txt:1 is 2.txt:1 is 1.txt:2 powerful 2.txt:1 simple 2.txt:1 simple 1.txt:3 */ static class InvertedIndexMapper2 extends Mapper<LongWritable, Text, Text, Text> { Text outputKey = new Text(); Text outputValue = new Text(); @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { //为了保证同一个单词交给同一个reduce,key还是单词,不能直接:context.write(NullWritable.get(), value); String[] line = value.toString().split("\t"); outputKey.set(line[0]); outputValue.set(line[1]); context.write(outputKey, outputValue); } } /** * 生成文档列表 */ static class InvertedIndexReducer2 extends Reducer<Text, Text, Text, Text> { @Override public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { String doc=""; for (Text text : values) { doc = text.toString() + "; " + doc;//doc += text.toString() + "; "; 控制输出顺序 } context.write(key, new Text(doc)); } } @Override public int run(String[] args) throws Exception { JobConf conf = new JobConf(InvertedIndex_V22.class); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if(otherArgs.length != 2){ System.err.println("Usage: InvertedIndex <in> <out>"); System.exit(2); } FileSystem hdfs = FileSystem.get(conf); Path inPath = new Path(args[0]); Path tmpPath = new Path(args[0] + "tmp/"); Path outPath = new Path(args[1]); if (hdfs.exists(tmpPath)) { hdfs.delete(tmpPath, true); } if (hdfs.exists(outPath)) { hdfs.delete(outPath, true); } //job1 Job job1 = new Job(conf, "job1"); job1.setJarByClass(InvertedIndex_V22.class); FileInputFormat.addInputPath(job1, inPath); FileOutputFormat.setOutputPath(job1, tmpPath); job1.setMapperClass(InvertedIndexMapper1.class); job1.setMapOutputKeyClass(Text.class); job1.setMapOutputValueClass(Text.class); job1.setCombinerClass(InvertedIndexCombiner1.class); job1.setReducerClass(InvertedIndexReducer1.class); job1.setNumReduceTasks(2); job1.setOutputKeyClass(Text.class); job1.setOutputValueClass(Text.class); //job2 Job job2 = new Job(conf, "job2"); job2.setJarByClass(InvertedIndex_V22.class); FileInputFormat.addInputPath(job2, tmpPath); FileOutputFormat.setOutputPath(job2, outPath); job2.setMapperClass(InvertedIndexMapper2.class); job2.setMapOutputKeyClass(Text.class); job2.setMapOutputValueClass(Text.class); job2.setReducerClass(InvertedIndexReducer2.class); job2.setNumReduceTasks(1); job2.setOutputKeyClass(Text.class); job2.setOutputValueClass(Text.class); return handleJobChain(job1, job2, "JobGroup"); } /** * 组合多个Job,相互之间可以有依赖 * @param job1 * @param job2 * @param chainName 任务组名 * @return * @throws IOException */ public static int handleJobChain(Job job1 ,Job job2, String chainName) throws IOException{ ControlledJob ctrlJob1 = new ControlledJob(job1.getConfiguration());//为每一个job创建一个控制器 ctrlJob1.setJob(job1); ControlledJob ctrlJob2 = new ControlledJob(job2.getConfiguration()); ctrlJob2.setJob(job2); ctrlJob2.addDependingJob(ctrlJob1);//指定job2依赖于job1 JobControl jobCtrl = new JobControl(chainName);//任务组控制器,控制改组的所有任务 jobCtrl.addJob(ctrlJob1); jobCtrl.addJob(ctrlJob2); Thread t = new Thread(jobCtrl);//hadoop的JobControl类实现了线程Runnable接口。我们需要实例化一个线程来让它启动。 t.start(); while (true) { if (jobCtrl.allFinished()) { System.out.println(jobCtrl.getSuccessfulJobList()); jobCtrl.stop();//终止线程 return 0; } if (jobCtrl.getFailedJobList().size() > 0) { System.out.println(jobCtrl.getFailedJobList()); jobCtrl.stop(); return 1; } } } public static void main(String[] args) throws Exception { args = new String[]{ "hdfs://master:9000/user/hadoop/InvertedIdx/", "hdfs://master:9000/user/hadoop/InvertedIdxOut2/" }; int status = new InvertedIndex_V22().run(args); System.exit(status); } }
package action05; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; /* Задача1: Вывести все методы класса String Задача2(ReflectionTask1Example) Написать метод принимающий любой объект. Метод возвращает все классы в иерархию которых входит данный объект. Задача3:(ReflectionTask2Example) Написать метод, принимающий любой объект, выводящий список всех интерфейсов по иерархии наследования классов. */ public class ReflectionApiTest { public static void main(String[] args) { System.out.println(getAllObjectMethods(new String())); System.out.println(getParents(new ArrayList<>())); System.out.println(getInterfaces(new ArrayList<>())); } // Task 1 public static ArrayList<Method> getAllObjectMethods(Object o) { ArrayList<Method> list = new ArrayList<>(); Method[] methods = o.getClass().getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { list.add(methods[i]); } return list; } //Task 2 public static ArrayList<Class<?>> getParents(Object obj) { ArrayList<Class<?>> list = new ArrayList<>(); list.add(obj.getClass()); Class<?> cls = obj.getClass().getSuperclass(); while (cls != null) { list.add(cls); cls = cls.getSuperclass(); } return list; } // Task 3 public static HashSet<Class<?>> getInterfaces(Object obj) { HashSet<Class<?>> resultSet = new HashSet<>(); ArrayList<Class<?>> classes = getParents(obj); for (Class<?> cl : classes) { Class<?> inf[] = cl.getInterfaces(); for (int i = 0; i < inf.length; i++) { resultSet.add(inf[i]); } } return resultSet; } }
package org.hieu.interceptingfilter; /** * @author hieu * * The intercepting filter design pattern is used when we want to do some pre-processing / post-processing with request or response of the application. Filters are defined and applied on the request before passing the request to actual target application. Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern. Filter - Filter which will perform certain task prior or after execution of request by request handler. Filter Chain - Filter Chain carries multiple filters and help to execute them in defined order on target. Target - Target object is the request handler Filter Manager - Filter Manager manages the filters and Filter Chain. Client - Client is the object who sends request to the Target object. We're going to create a FilterChain, FilterManager, Target, and Client as various objects representing our entities.AuthenticationFilter and DebugFilter represents concrete filters. InterceptingFilterDemo, our demo class will use Client to demonstrate Intercepting Filter Design Pattern. * */ public class InterceptingFilterDemo { public static void main(String[] args) { FilterManager filterManager = new FilterManager(new Target()); filterManager.setFilter(new AuthenticationFilter()); filterManager.setFilter(new DebugFilter()); Client client = new Client(); client.setFilterManager(filterManager); client.sendRequest("HOME"); } }