text
stringlengths
10
2.72M
package se.jaitco.queueticketapi.filter; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.MalformedJwtException; import io.jsonwebtoken.SignatureException; import io.jsonwebtoken.UnsupportedJwtException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.web.filter.OncePerRequestFilter; import se.jaitco.queueticketapi.service.JwtTokenService; import se.jaitco.queueticketapi.service.SecurityContextHolderService; import se.jaitco.queueticketapi.service.UserDetailsServiceImpl; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Slf4j public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { protected static final String AUTHORIZATION = "Authorization"; protected static final String BEARER_WITH_SPACE = "Bearer "; protected static final int BEARER_WITH_SPACE_LENGTH = BEARER_WITH_SPACE.length(); @Autowired private SecurityContextHolderService securityContextHolderService; @Autowired private UserDetailsServiceImpl userServiceDetail; @Autowired private JwtTokenService jwtTokenService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String authToken = request.getHeader(AUTHORIZATION); authToken = getAuthToken(authToken); if (authToken != null) { String username = getUsernameFromToken(authToken); doAuthentication(request, authToken, username); } chain.doFilter(request, response); } private void doAuthentication(HttpServletRequest request, String authToken, String username) { if (username != null && securityContextHolderService.getAuthentication() == null) { UserDetails userDetails = this.userServiceDetail.loadUserByUsername(username); if (jwtTokenService.validateToken(authToken, userDetails)) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); securityContextHolderService.setAuthentication(authentication); } } } private String getUsernameFromToken(String authToken) { String username = null; try { username = jwtTokenService.getUsernameFromToken(authToken); } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { log.error("getUsernameFromToken error, token was malformed: {}", authToken, e); } return username; } private String getAuthToken(String authToken) { if (authToken != null && authToken.startsWith(BEARER_WITH_SPACE)) { authToken = authToken.substring(BEARER_WITH_SPACE_LENGTH); } return authToken; } }
package com.company.utils.sort_algorithms; /** * @author Administrator * @data 四月 14 2017 15:51. */ public class SelectSort { public static void selectionSort(int[] arr){ if (arr == null||arr.length==0){ return; } for (int i=0;i<arr.length;i++){ int min = i ; for (int j=i+1;j<arr.length;j++){ min = arr[min]<arr[j]?min:j; } if (min!=i) swap(arr, i, min); } } public static void swap(int[] arr,int i,int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void main(String[] args) { int[] arr = {11, 5, 2,8,10, 5, 7, 15,3, 7,6,9,1, 2, 3, 4}; System.out.println("原始数据为:"); for (int a:arr){ System.out.print(a+" "); } System.out.println(); System.out.println("选择排序后输出为:"); selectionSort(arr); for (int a:arr){ System.out.print(a+" "); } } }
package com.zzidc.web.controller; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; /** * @ClassName FileController * @Author chenxue * @Description TODO * @Date 2019/4/1 10:43 **/ @RestController @RequestMapping(value = "/file") public class FileController { private static String folder = "E:\\test"; @RequestMapping(value = "uploadFile",method = RequestMethod.POST) @ApiOperation(value = "文件上传接口",notes = "使用此接口上传文件") @ApiImplicitParam(name = "file",value = "使用MultipartFile的实例对象来接收文件数据",required = true,dataTypeClass = MultipartFile.class) public FileInfo uploadFile(@RequestParam MultipartFile file) throws IOException { System.out.println("上传文件"); File newFile = new File(folder,System.currentTimeMillis() + ".txt"); file.transferTo(newFile); return new FileInfo(newFile.getAbsolutePath()); } @RequestMapping(value = "downloadFile/{id}",method = RequestMethod.GET) @ApiOperation(value = "文档下载接口",notes = "使用此接口下载文档") @ApiImplicitParams({ @ApiImplicitParam(name = "id",value = "文件ID",dataTypeClass = String.class,required = true), @ApiImplicitParam(name = "request",value = "HttpServletRequest实例对象,自动注入,无需传递",required = true,dataTypeClass = HttpServletRequest.class), @ApiImplicitParam(name = "response",value = "HttpServletResponse实例对象",required = true,dataTypeClass = HttpServletResponse.class) }) public void downLoadFile(@PathVariable String id, HttpServletRequest request, HttpServletResponse response){ try( InputStream inputStream = new FileInputStream(new File(folder,id+".txt")); OutputStream outputStream = response.getOutputStream(); ){ response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=test.txt"); byte[] bytes = new byte[1024]; while(inputStream.read(bytes) != -1){ outputStream.write(bytes); } //IoUtil.copy(inputStream,outputStream); outputStream.flush(); }catch (IOException e){ e.printStackTrace(); } } }
package com.naukri.imagecropper; /** * Created by akash.singla on 12/2/2015. */ public class EdgeSelection { boolean left = false; boolean right = false; boolean top = false; boolean bottom = false; boolean leftBottom = false; boolean rightTop = false; }
package com.tencent.mm.plugin.qqmail.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.plugin.qqmail.ui.ComposeUI.10; class ComposeUI$10$1 implements OnClickListener { final /* synthetic */ 10 mfw; ComposeUI$10$1(10 10) { this.mfw = 10; } public final void onClick(DialogInterface dialogInterface, int i) { this.mfw.mfs.setResult(0); this.mfw.mfs.finish(); } }
package 并发; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; /** * @Author: Mr.M * @Date: 2019-05-15 10:33 * @Description: **/ public class copyOnWriteArrayListDemo { public static void main(String[] args) { CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList(); CopyOnWriteArraySet copyOnWriteArraySet = new CopyOnWriteArraySet(); } }
package com.beiming.modules.sys.dict.service.impl; import com.beiming.modules.base.service.AbstractService; import com.beiming.modules.sys.dict.domain.dto.SysDictModifyDTO; import com.beiming.modules.sys.dict.domain.dto.SysDictQueryDTO; import com.beiming.modules.sys.dict.domain.entity.SysDict; import com.beiming.modules.sys.dict.domain.vo.SysDictVO; import com.beiming.modules.sys.dict.mapper.SysDictMapper; import com.beiming.modules.sys.dict.service.SysDictService; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import java.util.List; import java.util.stream.Collectors;; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SysDictServiceImpl extends AbstractService implements SysDictService { @Autowired SysDictMapper sysDictMapper; @Override public PageInfo<SysDictVO> list(SysDictQueryDTO query) { SysDict target = new SysDict(); BeanUtils.copyProperties(query, target); Page<SysDictVO> page = PageHelper.startPage(query.getPageNum(), query.getPageSize()); List<SysDict> list = sysDictMapper.select(target); PageInfo<SysDictVO> pageInfo = new PageInfo<>(page); pageInfo.setList(list.stream().map(x -> dto2vo(x)).collect(Collectors.toList())); return pageInfo; } @Override public void insert(SysDictModifyDTO save) { SysDict target = new SysDict(); BeanUtils.copyProperties(save, target); sysDictMapper.insert(target); } @Override public void update(SysDictModifyDTO update) { SysDict target = new SysDict(); BeanUtils.copyProperties(update, target); sysDictMapper.updateByPrimaryKeySelective(target); } @Override public SysDictVO info(Integer id) { SysDict sysDict = sysDictMapper.selectByPrimaryKey(id); SysDictVO sysDictVO = dto2vo(sysDict); return sysDictVO; } @Override public void delete(List<Integer> delete) { for(Integer id : delete){ sysDictMapper.deleteByPrimaryKey(id); } } //DTO转VO private SysDictVO dto2vo(SysDict source) { SysDictVO target = new SysDictVO(); BeanUtils.copyProperties(source, target); return target; } }
package com.example.midtermalik; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; public class AddToDoFragment extends Fragment { private EditText title; private Button btn; public AddToDoFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.todo_add_frame, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); title = view.findViewById(R.id.add_todo_title); btn = view.findViewById(R.id.btn_add); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String titleText = title.getText().toString(); ToDo todo = new ToDo(titleText); } }); } }
package com.sfa.controller; import java.util.HashMap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.ResponseBody; import com.sfa.dto.JSONResult; import com.sfa.security.Auth; import com.sfa.security.Auth.Role; import com.sfa.security.AuthUser; import com.sfa.service.ChartService; import com.sfa.util.ChangeDate; import com.sfa.util.ChangeListMap; import com.sfa.vo.ChartVo; import com.sfa.vo.UserVo; @Controller @RequestMapping(value = "/chart") public class ChartController { @Autowired private ChartService chartService; @Autowired private ChangeListMap changeListMap; @Auth @RequestMapping(value = "/", method = RequestMethod.GET) public String chart(@AuthUser UserVo authUser,Model model) { String date=((ChangeDate.today()).substring(0, 4)); model.addAttribute("date", date); System.out.println(date); return "chart/teamchart"; } @Auth @ResponseBody @RequestMapping(value = "/sale", method = RequestMethod.POST) public JSONResult getSaleByYear(@AuthUser UserVo authUser, @RequestParam(value = "date", required = true, defaultValue = "") String date) { if ("".equals(date)) { date=((ChangeDate.today()).substring(0, 4)); System.out.println(date); } List<ChartVo> list = chartService.getSaleByYear(authUser.getId(), date); HashMap <String,Long> map =changeListMap.change(list); if (list == null) { return JSONResult.fail(); } else { return JSONResult.success(map); } } @Auth @ResponseBody @RequestMapping(value = "/sale/estimate", method = RequestMethod.POST) public JSONResult getEstimateSaleByYear(@AuthUser UserVo authUser, @RequestParam(value = "date", required = true, defaultValue = "") String date) { if ("".equals(date)) { date=((ChangeDate.today()).substring(0, 4)); } List<ChartVo> list = chartService.getEstimateSaleByYear(authUser.getId(), date); HashMap <String,Long> map =changeListMap.change(list); if (list == null) { return JSONResult.fail(); } else { return JSONResult.success(map); } } @Auth @ResponseBody @RequestMapping(value = "/mile", method = RequestMethod.POST) public JSONResult getMileByYear(@AuthUser UserVo authUser, @RequestParam(value = "date", required = true, defaultValue = "") String date) { if ("".equals(date)) { date=((ChangeDate.today()).substring(0, 4)); } List<ChartVo> list = chartService.getMileByYear(authUser.getId(), date); HashMap <String,Long> map =changeListMap.change(list); if (list == null) { return JSONResult.fail(); } else { return JSONResult.success(map); } } @Auth @ResponseBody @RequestMapping(value = "/mile/estimate", method = RequestMethod.POST) public JSONResult getEstimateMileByYear(@AuthUser UserVo authUser, @RequestParam(value = "date", required = true, defaultValue = "") String date) { if ("".equals(date)) { date=((ChangeDate.today()).substring(0, 4)); } List<ChartVo> list = chartService.getEstimateByYear(authUser.getId(), date); HashMap <String,Long> map =changeListMap.change(list); System.out.println("estimate"+map); if (list == null) { return JSONResult.fail(); } else { return JSONResult.success(map); } } @Auth(value = Auth.Role.팀장) @ResponseBody @RequestMapping(value="/sale/id", method=RequestMethod.POST) public JSONResult getSaleById (@AuthUser UserVo authUser,@RequestParam(value="date",required=true, defaultValue="")String date, @RequestParam(value="id",required=true, defaultValue="")String id) { if ("".equals(date)) { date=((ChangeDate.today()).substring(0, 4)); } List<ChartVo> list = chartService.getSaleById(id, date); System.out.println(list); return JSONResult.success(list); } @Auth(value = Auth.Role.팀장) @ResponseBody @RequestMapping(value="/sale/dept", method=RequestMethod.POST) public JSONResult getSaleBydept (@AuthUser UserVo authUser,@RequestParam(value="date",required=true, defaultValue="")String date) { if ("".equals(date)) { date=((ChangeDate.today()).substring(0, 4)); } List<ChartVo> list = chartService.getSaleByDept(date); System.out.println(list); return JSONResult.success(list); } @Auth(value = Auth.Role.팀장) @ResponseBody @RequestMapping(value="/sale/dept/estimate", method=RequestMethod.POST) public JSONResult getEstimateSaleBydept (@AuthUser UserVo authUser,@RequestParam(value="date",required=true, defaultValue="")String date) { if ("".equals(date)) { date=((ChangeDate.today()).substring(0, 4)); } List<ChartVo> list = chartService.getEstimateSaleBydept(date); System.out.println(list); return JSONResult.success(list); } @Auth(value = Auth.Role.팀장) @ResponseBody @RequestMapping(value="/mile/dept", method=RequestMethod.POST) public JSONResult getMileBydept (@AuthUser UserVo authUser,@RequestParam(value="date",required=true, defaultValue="")String date) { if ("".equals(date)) { date=((ChangeDate.today()).substring(0, 4)); } List<ChartVo> list = chartService.getMileBydept(date); System.out.println(list); return JSONResult.success(list); } @Auth(value = Auth.Role.팀장) @ResponseBody @RequestMapping(value="/mile/dept/estimate", method=RequestMethod.POST) public JSONResult getEstimateMileBydept (@AuthUser UserVo authUser,@RequestParam(value="date",required=true, defaultValue="")String date) { if ("".equals(date)) { date=((ChangeDate.today()).substring(0, 4)); } List<ChartVo> list = chartService.getEstimateMileBydept(date); System.out.println(list); return JSONResult.success(list); } }
package br.com.treinar.academico; public class PrimeiraClasse { public static void main(String[] args) { System.out.println("ABC ABC toda crianca tem q le e aprendÍ"); } }
package entities.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import entities.model.Categorie; import entities.model.Produit; import entities.service.ICategorieService; @Controller @RequestMapping("/categorie") public class CategorieController { @Autowired private ICategorieService categorieService; public void setCategorieService(ICategorieService categorieService) { this.categorieService = categorieService; } /** * définition et mapping accueil */ @RequestMapping(value = "/accueil", method = RequestMethod.GET) public String accueil(ModelMap model) { model.addAttribute("nomApp", "APPLICATION DE GESTION DES CATEGORIES"); model.addAttribute("salutation", "Avec SPRING MVC"); return "accueil"; } /** * Afficher liste categorie */ @RequestMapping(value = "/listeCategorie", method = RequestMethod.GET) public String afficherCategorie(ModelMap model) { List<Categorie> listeCategorie = categorieService.getAllCategorie(); model.addAttribute("categorieListe", listeCategorie); return "afficherListeCategorie"; } /** * update d'categorie */ /** * Ajout d'categorie */ // Methode pour afficher le formulaire d'ajout et lui attribuer le modele @RequestMapping(value = "/affichFormAjout", method = RequestMethod.GET) public ModelAndView affichFormAjout() { return new ModelAndView("ajouterCategorie", "categorieForm", new Categorie()); } // Methode pour soummettre le formulaire d'ajout et lui attribuer le modele @RequestMapping(value = "/soumettreFormAjout", method = RequestMethod.POST) public String soumettreFormAjout(Model model, @Valid @ModelAttribute("categorieForm") Categorie categorie,BindingResult resultatValidation ) { if(resultatValidation.hasErrors()){ return "ajouterCategorie"; } if(categorie.getIdCategorie()==0){ // appel de la methode ajouter du service categorieService.addCategorie(categorie); } // else{ // /** // * appel de la méthode update du service // */ // categorieService.updateCategorie(categorie); // } // rafraichissement de la liste List<Categorie> listeCategorie = categorieService.getAllCategorie(); model.addAttribute("categorieListe", listeCategorie); return "afficherListeCategorie"; } /** * suppression categorie */ @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET) public String deleteCategorie(Model model, @PathVariable("id") long id) { Categorie categorie = categorieService.getCategorieById(id); categorieService.deleteCategorie(categorie); /** * rafraichissement de la liste et affichage d'un message d'alerte */ List<Categorie> listeCategorie = categorieService.getAllCategorie(); model.addAttribute("categorieListe", listeCategorie); model.addAttribute("css", "success"); model.addAttribute("msg", "Categorie is deleted!"); return "afficherListeCategorie"; } }
package servlets; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Type; import java.util.Collection; 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 Jama.Matrix; import beans.Test; import beans.CellModel; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * Servlet implementation class CellModels */ @WebServlet("/CellModels") public class CellModels extends HttpServlet { private static final long serialVersionUID = 1L; public CellModels() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Input StringBuilder buffer = new StringBuilder(); BufferedReader reader = request.getReader(); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } String data = buffer.toString(); Gson gson = new Gson(); Type type = new TypeToken<Collection<Test>>(){}.getType(); List<Test> tests = gson.fromJson(data, type); // Model CellModel model = new CellModel(tests); model.build(); double[] coefficients = model.getCoefficients(); // Output String json = new Gson().toJson(coefficients); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.print(json); } }
package com.cognitive.newswizard.service.util; import static java.time.format.DateTimeFormatter.BASIC_ISO_DATE; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.time.ZoneOffset; public class DateTimeUtil { private static ZoneOffset CURRENT_ZONE_OFFSET = ZoneId.systemDefault().getRules().getOffset(Instant.now()); public static LocalDate basicIsoDateStringToLocalDate(final String date) { return BASIC_ISO_DATE.parse(date, LocalDate::from); } public static long localDateToTimeMilis(final LocalDate date, final boolean beginingOfDay) { if (beginingOfDay) { return date.atTime(0, 0, 0, 0).toInstant(CURRENT_ZONE_OFFSET).toEpochMilli(); } return date.atTime(23, 59, 59, 999999999).toInstant(CURRENT_ZONE_OFFSET).toEpochMilli(); } }
package com.ajonx.game.audio; import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; public class Sound { public String path; public Clip clip; public boolean playing = false; public int numLoops = 0; public Sound(String path) { try { File soundFile = new File("res/sounds/" + path + ".wav"); AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile); AudioFormat format = ais.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, format); clip = (Clip) AudioSystem.getLine(info); clip.open(ais); } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) { e.printStackTrace(); } } public Sound(Sound copy) { this.path = copy.path; this.clip = copy.clip; this.playing = false; this.numLoops = copy.numLoops; } // Resets the sound and starts it public void play() { playing = true; clip.setFramePosition(0); if (numLoops != 0) clip.loop(numLoops); clip.start(); } public void stop() { playing = false; clip.stop(); } public Sound loop() { return loop(Clip.LOOP_CONTINUOUSLY); } public Sound loop(int times) { this.numLoops = (times > 0) ? (times - 1) : times; return this; } public int getLength() { return clip.getFrameLength(); } public boolean isFinished() { return clip.getFramePosition() >= clip.getFrameLength(); } }
import java.util.Arrays; import java.util.Iterator; /* * 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. */ /** * * @author arwanakhoiruddin */ public class MyNode { int[] state; int n; String info; int heuristicValue; int level; MyNode up; MyNode bottom; MyNode left; MyNode right; MyNode parent; public MyNode(int[] state, int n, String info) { this.state = state; this.n = n; this.info = info; } /** * expand the current node * @return */ public MyNode expand() { addNodeOnMoveUp(state, n); addNodeOnMoveBottom(state, n); addNodeOnMoveLeft(state, n); addNodeOnMoveRight(state, n); return this; } /** * Generates new state when the blank part is shifted up * * @param state * @param n * @return */ public MyNode addNodeOnMoveUp(int[] state, int n) { MyNode newNode = null; int[] tempState = new int[state.length]; int i = 0; for (int o : state) { tempState[i++] = o; } // find the blank positon to understand how it can move int zeroCoord = findBlankPosition(state); if (zeroCoord < n) { // cannot move up this.up = null; } else { // exchange values between blank and the upper value of the blank position int tmp = tempState[zeroCoord]; tempState[zeroCoord] = tempState[zeroCoord - n]; tempState[zeroCoord - n] = tmp; // check first if the same state has been generated before if (!stateHasBeenCreated(tempState)) { newNode = new MyNode(tempState, n, "up"); this.up = newNode; newNode.parent = this; Search.nodes.addLast(this.up); return newNode; } } return newNode; } /** * Generates new state when the blank part is shifted down * * @param state * @param n * @return MyNode */ public MyNode addNodeOnMoveBottom(int[] state, int n) { MyNode newNode = null; int[] tempState = new int[state.length]; int i = 0; for (int o : state) { tempState[i++] = o; } // find the blank positon to understand how it can move int zeroCoord = findBlankPosition(state); if (zeroCoord >= (state.length - n)) { // cannot move down this.bottom = null; } else { // exchange values between blank and the bottom value of the blank position int tmp = tempState[zeroCoord]; tempState[zeroCoord] = tempState[zeroCoord + n]; tempState[zeroCoord + n] = tmp; if (!stateHasBeenCreated(tempState)) { newNode = new MyNode(tempState, n, "bottom"); this.bottom = newNode; newNode.parent = this; Search.nodes.addLast(this.bottom); return newNode; } } return newNode; } /** * Generates new state when the blank part is shifted left * * @param state * @param n */ public MyNode addNodeOnMoveLeft(int[] state, int n) { MyNode newNode = null; int[] tempState = new int[state.length]; int i = 0; for (int o : state) { tempState[i++] = o; } // find the blank positon to understand how it can move int zeroCoord = findBlankPosition(state); if ((zeroCoord % n) == 0) { // cannot move to the left this.left = null; } else { // exchange values between blank and the upper part of the blank int tmp = tempState[zeroCoord]; tempState[zeroCoord] = tempState[zeroCoord - 1]; tempState[zeroCoord - 1] = tmp; if (!stateHasBeenCreated(tempState)) { newNode = new MyNode(tempState, n, "left"); this.left = newNode; newNode.parent = this; Search.nodes.addLast(this.left); } } return newNode; } /** * Generates new state when the blank part is shifted right * * @param state * @param n */ public MyNode addNodeOnMoveRight(int[] state, int n) { MyNode newNode = null; int[] tempState = new int[state.length]; int i = 0; for (int o : state) { tempState[i++] = o; } // find the blank positon to understand how it can move int zeroCoord = findBlankPosition(state); if (((zeroCoord + 1) % n) == 0) { // cannot move to the right this.right = null; } else { // exchange values between blank and the upper part of the blank int tmp = tempState[zeroCoord]; tempState[zeroCoord] = tempState[zeroCoord + 1]; tempState[zeroCoord + 1] = tmp; if (!stateHasBeenCreated(tempState)) { newNode = new MyNode(tempState, n, "right"); this.right = newNode; newNode.parent = this; Search.nodes.addLast(this.right); } } return newNode; } /** * find the position of the blank in the current state * @param state * @return */ private int findBlankPosition(int[] state) { int i = 0; while (i < state.length) { if (state[i] == 0) { break; } else { i++; } } return i; } /** * detect if the state has been created before * @param state * @return */ public boolean stateHasBeenCreated(int[] state) { boolean created = false; Iterator it = Search.nodes.iterator(); while (it.hasNext()) { MyNode createdNode = (MyNode) it.next(); if (arrayIsSame(createdNode.state, state)) { created = true; break; } } return created; } /** * check if the content of the array is same or not * @param arr1 * @param arr2 * @return */ public boolean arrayIsSame(int[] arr1, int[] arr2) { int i = 0; boolean same = true; for (int o : arr1) { if (arr2[i++] != o) { same = false; break; } } return same; } }
package com.ebay.lightning.client; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import com.ebay.lightning.client.caller.ServiceCaller; import com.ebay.lightning.core.beans.LightningRequest; import com.ebay.lightning.core.beans.LightningResponse; import com.ebay.lightning.core.beans.Task; import com.ebay.lightning.core.beans.URLTask; import com.ebay.lightning.core.config.SystemConfig; import com.ebay.lightning.core.manager.TaskExecutionManager; import com.ebay.lightning.core.store.LightningRequestReport; import com.ebay.lightning.core.utils.UrlUtils; import com.ebay.lightning.core.utils.UrlUtils.ContentType; import com.ebay.lightning.core.utils.ZipUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; /** * The class <code>LightningClientBuilderTest</code> contains tests for the * class <code>{@link LightningClientBuilder}</code>. * * @author shashukla */ public class LightningClientBuilderTest { private static final String RESERVATION_DENIED = "{ \"id\": \"youGotIt\", \"state\" : \"DENIED\" }"; private static final String RESERVATION_ACCEPTED = "{\"id\": \"youGotIt\" , \"state\" : \"ACCEPTED\" }"; private LightningClientBuilder testBuilder; private UrlUtils urlUtils; private String payload; private List<Task> tasks; private ServiceCaller testCaller; private static final Logger log = Logger.getLogger(LightningClientBuilderTest.class); @Before public void setUp() throws Exception { urlUtils = Mockito.mock(UrlUtils.class); testCaller = Mockito.mock(ServiceCaller.class); tasks = generateTasks(1000); testBuilder = new LightningClientBuilder(); testBuilder.setUrlUtils(urlUtils); } @After public void tearDown() { log.info("LightningClinetBuilderTest - Done!"); } @Test public void testBuild_WithSeeds() throws Exception { final String reserveApiUrl = "http://{host}:0/reserve"; final String pollApiUrl = "http://{host}:0/poll"; final String submitApiUrl = "http://{host}:0/submit"; final String auditApiUrl = "http://{host}:0/audit"; final String auditJsonApiUrl = "http://{host}:0/audit/json"; final String auditSummaryApiUrl = "http://{host}:0/auditSummary"; final String lightningStatsApiUrl = "http://{host}:0/lightningStats"; final String systemConfigApiUrl = "http://{host}:0/getSystemConfig"; final String systemConfigUpdateApiUrl = "http://{host}:0/updateSystemConfig"; testBuilder.setPollApiUrlTemplate(pollApiUrl).setReserveApiUrlTemplate(reserveApiUrl).setAuditApiUrlTemplate(auditApiUrl) .setSubmitApiUrlTemplate(submitApiUrl).setAuditJsonApiUrlTemplate(auditJsonApiUrl).setAuditSummaryUrlTemplate(auditSummaryApiUrl) .setLightningStatsUrlTemplate(lightningStatsApiUrl).setSystemConfigUpdateUrlTemplate(systemConfigUpdateApiUrl) .setSystemConfigUrlTemplate(systemConfigApiUrl); Mockito.when(urlUtils.get("http://localhost:0/reserve/1000")).thenReturn(RESERVATION_ACCEPTED); final List<String> seeds = new ArrayList<>(); final String servingIp = "localhost"; seeds.add(servingIp); testBuilder.setSeeds(seeds); LightningClient clientWithSeeds = testBuilder.build(); Mockito.when(urlUtils.post(anyString(), any(UrlUtils.ContentType.class), any(HashMap.class), anyString())) .thenReturn("{\"status\": \"submitted\"}"); LightningRequest req = clientWithSeeds.submit(tasks); Mockito.when(urlUtils.get("http://localhost:0/poll/" + req.getSessionId() + "/false")).thenReturn("{\"response\": \"response\"}"); assertEquals(servingIp, req.getServingHostIp()); assertNotNull(req); final LightningResponse expectedResponse = new LightningResponse(null, null); final byte[] zippedResponse = ZipUtil.zipAsByteArray(expectedResponse); Mockito.when(urlUtils.getByteArray("http://localhost:0/poll/" + req.getSessionId() + "/false")).thenReturn(zippedResponse); final LightningResponse pollResponse = clientWithSeeds.pollResponse(req, false);// Giving // Null assertNotNull(pollResponse); payload = ZipUtil.zip(req); Mockito.when(urlUtils.get("http://localhost:0/reserve/1000")).thenReturn(RESERVATION_ACCEPTED); Mockito.when(urlUtils.post("http://localhost:0/submit", ContentType.APPLICATION_JSON, null, payload)) .thenReturn("{\"status\": \"submitted\"}"); clientWithSeeds = testBuilder.build(); req = clientWithSeeds.submit(tasks); Mockito.when(urlUtils.get("http://localhost:0/poll/" + req.getSessionId() + "/false")).thenReturn("{\"response\": \"response\"}"); assertEquals(servingIp, req.getServingHostIp()); assertNotNull(req); } @Test public void testBuild_NoSeeds() throws Exception { final LightningClient client = testBuilder.build(); Exception actual = null; try { Mockito.when(urlUtils.get("http://localhost:0/reserve/1000")).thenReturn(RESERVATION_ACCEPTED); Mockito.when(urlUtils.post("http://localhost:0/submit", ContentType.APPLICATION_JSON, null, payload)) .thenReturn("{\"status\": \"submitted\"}"); Mockito.when(urlUtils.get("http://localhost:0/poll/1000")).thenReturn("{\"response\": \"response\"}"); client.submit(tasks); } catch (final Exception e) { actual = e; } assertNotNull("Submit without any seeds should result in exception", actual); } @Test public void testEmbeddedMode() throws Exception { Mockito.when(urlUtils.get("http://localhost:0/reserve/1000")).thenReturn(RESERVATION_ACCEPTED); final LightningClient testClient = testBuilder.setEmbeddedMode(true).build(); Mockito.when(urlUtils.post(anyString(), any(UrlUtils.ContentType.class), any(HashMap.class), anyString())) .thenReturn("{\"status\": \"submitted\"}"); final LightningRequest testRequest = testClient.submit(tasks); Mockito.when(urlUtils.get("http://localhost:0/poll/" + testRequest.getSessionId() + "/false")).thenReturn("{\"response\": \"response\"}"); assertNotNull(testRequest); LightningRequestReport testReport = testClient.getAuditJsonReport(testRequest.getSessionId(), testRequest.getServingHostIp()); assertNotNull(testReport); testReport = testClient.getAuditReport(testRequest); assertNotNull(testReport); testReport = testClient.getAuditReport(testRequest.getSessionId(), testRequest.getServingHostIp()); assertNotNull(testReport); final SystemConfig testConfig = testClient.updateSystemConfig(testRequest.getServingHostIp(), new SystemConfig()); assertNotNull(testConfig); final TaskExecutionManager testManager = Mockito.mock(TaskExecutionManager.class); final LightningResponse testResponse = Mockito.mock(LightningResponse.class); Mockito.when(testManager.pollResults("1000", false)).thenReturn(testResponse); final LightningResponse resultResponse = testClient.pollResponse(testRequest, false); assertNotNull(resultResponse); } private static List<Task> generateTasks(int taskCount) throws Exception { final List<Task> tasks = new ArrayList<>(); for (int j = 0; j < taskCount; j++) { tasks.add(new URLTask("http://localhost:8080")); } return tasks; } }
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String month = in.next(); String day = in.next(); String year = in.next(); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); Calendar calendar = Calendar.getInstance(); try { calendar.setTime(new SimpleDateFormat("MM/dd/yyyy").parse(month + "/" + day + "/" + year)); System.out.println(calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase()); } catch (ParseException e) { e.printStackTrace(); } } }
package xyz.kikutaro.line.bot.sendgrid; import com.linecorp.bot.model.action.MessageAction; import com.linecorp.bot.model.message.TemplateMessage; import com.linecorp.bot.model.message.TextMessage; import com.linecorp.bot.model.message.VideoMessage; import com.linecorp.bot.model.message.template.ButtonsTemplate; import com.linecorp.bot.model.message.template.CarouselColumn; import com.linecorp.bot.model.message.template.CarouselTemplate; import java.util.Arrays; import org.springframework.stereotype.Controller; /** * * @author kikuta */ @Controller public class SendGridBotController { public TemplateMessage menuMessage(String message) { return new TemplateMessage(message, new ButtonsTemplate( "https://sendgrid.kke.co.jp/blog/wp/wp-content/uploads/2016/09/SG_Logo_Blog-592x366.jpg" , message ,"必要な情報を以下からお選びください。",Arrays.asList( new MessageAction("Webサイト", "Webサイト"), new MessageAction("プランを確認する", "プラン"), new MessageAction("動画をみる", "動画") ))); } public TextMessage webSiteMessage() { return new TextMessage("こちらのURLをクリックしてください→ https://sendgrid.kke.co.jp/"); } public TemplateMessage planMessage() { return new TemplateMessage("プラン", new CarouselTemplate( Arrays.asList( new CarouselColumn(null, "Free", "0円 12,000通/月", Arrays.asList( new MessageAction("機能確認", "Free"), new MessageAction("申込む", "申込む") ) ), new CarouselColumn(null, "Bronze", "1,180円/月 40,000通/月", Arrays.asList( new MessageAction("機能確認", "Bronze"), new MessageAction("申込む", "申込む") ) ), new CarouselColumn(null, "Silver", "9,480円/月 100,000通/月", Arrays.asList( new MessageAction("機能確認", "Silver"), new MessageAction("申込む", "申込む") ) ), new CarouselColumn(null, "Gold", "22,980円/月 300,000通/月", Arrays.asList( new MessageAction("機能確認", "Gold"), new MessageAction("申込む", "申込む") ) ), new CarouselColumn(null, "Platinum", "45,980円/月 700,000通/月", Arrays.asList( new MessageAction("機能確認", "Platinum"), new MessageAction("申込む", "申込む") ) ) ) )); } public VideoMessage movieMessage() { return new VideoMessage("https://vimeo.com/41433099", "https://sendgrid.kke.co.jp/blog/wp/wp-content/uploads/2016/09/SG_Logo_Blog-592x366.jpg"); } public TextMessage applyMessage() { return new TextMessage("こちらのURLをクリックしてください→ https://sendgrid.kke.co.jp/app?p=signup.index"); } }
package pr; import java.io.IOException; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.*; public class PageRankMapper extends Mapper<LongWritable, Text, Text, Text> { private Text outKey = new Text(); // output key private Text outValue = new Text(); // output value public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); // convert Text to string int separateIndex = line.indexOf("\t"); // String nodeId = line.substring(0, separateIndex); String rest = line.substring(separateIndex, line.length()); // get the // rest of // the line String[] valuesList = rest.split("\t"); // the array contains the // PageRank and the outlinks String pagerank = valuesList[1]; // the first element is empty StringBuilder sb = new StringBuilder(); // save the outlinks int numOfNodes = valuesList.length - 2; Double outputPageRank = Double.parseDouble(pagerank) / numOfNodes; outValue.set(outputPageRank.toString()); for (int i = 2; i < valuesList.length; i++) { // start from the third // element since the // second is PageRank outKey.set(valuesList[i]); context.write(outKey, outValue); sb.append(valuesList[i] + "\t"); } context.write(new Text(nodeId), new Text(":" + sb.toString())); } }
package ru.lischenko_dev.fastmessenger.adapter; import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.Typeface; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.style.StyleSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.picasso.Picasso; import org.greenrobot.eventbus.EventBus; import java.text.SimpleDateFormat; import java.util.ArrayList; import ru.lischenko_dev.fastmessenger.R; import ru.lischenko_dev.fastmessenger.common.Account; import ru.lischenko_dev.fastmessenger.common.ThemeManager; import ru.lischenko_dev.fastmessenger.view.CircleView; import ru.lischenko_dev.fastmessenger.vkapi.VKUtils; import ru.lischenko_dev.fastmessenger.vkapi.models.VKAttachment; import ru.lischenko_dev.fastmessenger.vkapi.models.VKMessage; import de.hdodenhof.circleimageview.*; public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> { private ArrayList<MessageItem> items; private Context context; private ThemeManager manager; private OnItemClickListener listener; public MessageAdapter(ArrayList<MessageItem> items, Context context) { this.items = items; this.context = context; this.manager = ThemeManager.get(context); } public void setListener(OnItemClickListener l) { this.listener = l; } private void initListeners(View v, final int position) { v.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (listener != null) { listener.onItemLongClick(v, position); } return true; } }); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listener != null) { listener.onItemClick(v, position); } } }); } @Override public MessageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_messages_list, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } public void destroy() { if (EventBus.getDefault().isRegistered(this)) EventBus.getDefault().unregister(this); } @Override public void onBindViewHolder(ViewHolder holder, int position) { initListeners(holder.itemView, position); MessageItem item = items.get(position); manager.setHrBackgroundColor(holder.hr); holder.ivChat.setVisibility(item.message.isChat() ? View.VISIBLE : View.GONE); holder.counter.setVisibility(!item.message.is_out && !item.message.read_state ? View.VISIBLE : View.GONE); holder.counter.setCircleColor(0xff1565c0); holder.counter.setText(String.valueOf(item.message.unread)); holder.counter.setTextColor(Color.WHITE); holder.counter.setTextSize(12); String count = String.valueOf(item.message.unread); if (count.length() > 3) { holder.counter.setText(count.substring(0, 1) + "K+"); } else if (count.length() > 2) holder.counter.setTextSize(10); holder.tvName.setTextColor(manager.getPrimaryTextColor()); holder.tvBody.setTextColor(manager.getSecondaryTextColor()); holder.tvDate.setTextColor(manager.getSecondaryTextColor()); holder.tvName.setText(item.message.isChat() ? item.message.title : item.user.toString()); holder.tvDate.setText(new SimpleDateFormat("HH:mm").format(item.message.date * 1000)); holder.rl.setBackgroundDrawable(item.message.read_state ? null : item.message.is_out ? context.getResources().getDrawable(R.drawable.ic_not_read_body) : null); if (holder.rl.getBackground() != null) holder.rl.getBackground().setColorFilter(manager.getUnreadColor(), PorterDuff.Mode.MULTIPLY); if (!item.message.isChat() && !item.message.is_out) holder.ivAvaSmall.setVisibility(View.GONE); try { Picasso.with(context).load(item.message.isChat() ? item.message.photo_200 : item.user.photo_200).placeholder(R.drawable.camera_200).into(holder.ivAva); Picasso.with(context).load(item.message.isChat() ? item.message.is_out ? Account.get(context).getSmallAvatar() : item.user.photo_50 : item.message.is_out ? Account.get(context).getSmallAvatar() : item.user.photo_50).placeholder(R.drawable.camera_200).into(holder.ivAvaSmall); } catch (Exception e) { Log.e("АААААААА ОШИИИИИБКААААА", e.toString()); } holder.ivAvaSmall.setVisibility(item.message.isChat() ? View.VISIBLE : item.message.is_out ? View.VISIBLE : View.GONE); holder.ivOnline.setVisibility(item.message.isChat() ? View.GONE : item.user.online ? View.VISIBLE : View.GONE); if(!item.message.isChat()) try { holder.ivOnline.setVisibility(item.user.online ? View.VISIBLE : View.GONE); holder.ivOnline.setBorderColor(manager.isDarkTheme() ? 0xff212121 : 0xffffffff); holder.ivOnline.setBorderWidth(2); } catch (Exception e) { e.printStackTrace(); } holder.tvBody.setText(item.message.body); if (item.message.body.length() == 0) if (!item.message.attachments.isEmpty()) { for (VKAttachment att : item.message.attachments) { holder.tvBody.setText(Html.fromHtml(String.format("<b>%s</b>", VKUtils.getStringAttachment(att.type)))); holder.tvBody.setTextColor(context.getResources().getColor(R.color.colorPrimary)); } } if (!TextUtils.isEmpty(item.message.action)) { String action = null; switch (item.message.action) { case VKMessage.ACTION_CHAT_CREATE: action = " created chat"; break; case VKMessage.ACTION_CHAT_PHOTO_UPDATE: action = " updated photo in chat"; break; case VKMessage.ACTION_CHAT_PHOTO_REMOVE: action = " removed photo in chat"; break; case VKMessage.ACTION_CHAT_TITLE_UPDATE: action = " changed title in chat"; break; case VKMessage.ACTION_CHAT_KICK_USER: if (item.user.uid == item.message.action_mid) { action = " leaved from chat"; } else { action = " kicked user from chat"; } break; case VKMessage.ACTION_CHAT_INVITE_USER: if (item.user.uid == item.message.action_mid) { action = " returned to chat"; } else { action = " invited user to chat"; } break; } Spannable text = new SpannableString(action); text.setSpan(new StyleSpan(Typeface.BOLD), 0, action.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); holder.tvBody.setText(text); holder.tvBody.setTextColor(Color.parseColor("#1565c0")); } } @Override public int getItemCount() { return items.size(); } public interface OnItemClickListener { void onItemClick(View view, int position); void onItemLongClick(View view, int position); } public static class ViewHolder extends RecyclerView.ViewHolder { TextView tvBody; TextView tvDate; ImageView ivAva; ImageView ivAvaSmall; TextView tvName; CircleImageView ivOnline; LinearLayout rl; ImageView ivChat; CircleView counter; View hr; public ViewHolder(View v) { super(v); tvBody = (TextView) v.findViewById(R.id.tvBody); tvDate = (TextView) v.findViewById(R.id.tvDate); ivAva = (ImageView) v.findViewById(R.id.ivAva); ivAvaSmall = (ImageView) v.findViewById(R.id.ivAvaSmall); tvName = (TextView) v.findViewById(R.id.tvName); ivOnline = (CircleImageView) v.findViewById(R.id.ivOnline); rl = (LinearLayout) v.findViewById(R.id.main_container); ivChat = (ImageView) v.findViewById(R.id.ivChat); counter = (CircleView) v.findViewById(R.id.ivCount); hr = v.findViewById(R.id.hr); } } }
package com.tom.contact.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.tom.contact.Data.Contact; import com.tom.contact.R; import java.util.List; public class ContactAdapter extends BaseAdapter { Context context; LayoutInflater inflater; List<Contact> contactList; public ContactAdapter(Context ctx,List<Contact> contacts){ this.context=ctx; this.contactList=contacts; this.inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return this.contactList.size(); } @Override public Object getItem(int position) { return this.contactList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView=inflater.inflate(R.layout.layout_contact_listitem,null); TextView txvFirstname=convertView.findViewById(R.id.txvFirstName); TextView txvLastName=convertView.findViewById(R.id.txvLastName); TextView txvPhone=convertView.findViewById(R.id.txvPhone); txvFirstname.setText(this.contactList.get(position).getFirstName()); txvLastName.setText(this.contactList.get(position).getLastName()); txvPhone.setText(this.contactList.get(position).getPhone()); return convertView; } }
package temakereso.helper; public enum FormType { TOPIC_FORM, CONSULTATION_FORM; }
class Playlist { private List<Song> list }
package String; public class CountAndSay_38 { /*38. 报数*/ /* 首先理解题意,每轮报数记录重复出现的字符个数; 优化:尾递归 将递归调用放在最后return处,大大减少递归的用时和消耗; */ public String res = ""; public String countAndSay(int n) { if(n == 0){ return res; } return fun("1",n); } public String fun(String s, int k){ if(k == 1){ return s; }else{ int i = 0; StringBuilder sb = new StringBuilder(); while(i < s.length()){ int count = 1; while(i < s.length() - 1 && s.charAt(i) == s.charAt(i + 1)){ count++; i++; } sb.append(count); sb.append(s.charAt(i)); i++; } s = sb.toString(); } return fun(s,k - 1); } }
package com.rest.webservices.versioning; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class PersonVersioningController { //Here we are doing versioning using uri versioning @GetMapping("v1/person") public Person1 personV1() { return new Person1("Bob Charlie"); } @GetMapping("v2/person") public Person2 personV2() { return new Person2(new Name("Bob", "Charlie")); } //Here we are doing versioning using RequestParameters @GetMapping(value="/person/param", params = "version=1") public Person1 paramV1() { return new Person1("Bob Charlie"); } @GetMapping(value="/person/param", params = "version=2") public Person2 paramV2() { return new Person2(new Name("Bob", "Charlie")); } //Here we are doing versioning using Header Versioning @GetMapping(value="/person/header", headers = "X-API-VERSION=1") public Person1 headerV1() { return new Person1("Bob Charlie"); } @GetMapping(value="/person/header", headers = "X-API-VERSION=2") public Person2 headerV2() { return new Person2(new Name("Bob", "Charlie")); } //Here we are doing versioning using produces also called Content Negotiation or Accept Versioning @GetMapping(value="/person/produces", produces = "application/vnd.company.app-v1+json") public Person1 producesV1() { return new Person1("Bob Charlie"); } @GetMapping(value="/person/produces", produces = "application/vnd.company.app-v2+json") public Person2 producesV2() { return new Person2(new Name("Bob", "Charlie")); } }
package com.tencent.mm.plugin.luckymoney.f2f.ui; import android.util.Pair; import android.view.View; import com.tencent.mm.aa.j; import com.tencent.mm.aa.q; import com.tencent.mm.ab.d; import com.tencent.mm.model.bv.a; import com.tencent.mm.model.s; import com.tencent.mm.platformtools.ab; import com.tencent.mm.plugin.luckymoney.f2f.ui.ShuffleView.5; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.bl; import java.util.Map; class LuckyMoneyF2FQRCodeUI$1 implements a { final /* synthetic */ LuckyMoneyF2FQRCodeUI kOv; LuckyMoneyF2FQRCodeUI$1(LuckyMoneyF2FQRCodeUI luckyMoneyF2FQRCodeUI) { this.kOv = luckyMoneyF2FQRCodeUI; } public final void a(d.a aVar) { Map z = bl.z(ab.a(aVar.dIN.rcl), "sysmsg"); if (z != null) { String str = (String) z.get(".sysmsg.sendId"); final String str2 = (String) z.get(".sysmsg.username"); final String str3 = (String) z.get(".sysmsg.amount"); final String str4 = (String) z.get(".sysmsg.receiveId"); if (bi.getInt((String) z.get(".sysmsg.islucky"), 0) > 0) { LuckyMoneyF2FQRCodeUI.a(this.kOv, str2); } if (!bi.G(new String[]{str, str2, str3})) { this.kOv.runOnUiThread(new Runnable() { public final void run() { if (!LuckyMoneyF2FQRCodeUI.a(LuckyMoneyF2FQRCodeUI$1.this.kOv).contains(str4)) { LuckyMoneyF2FQRCodeUI.a(LuckyMoneyF2FQRCodeUI$1.this.kOv).add(0, str4); if (!s.he(str2)) { j jVar = new j(); jVar.username = str2; q.KH().a(jVar); } LuckyMoneyF2FQRCodeUI.b(LuckyMoneyF2FQRCodeUI$1.this.kOv).put(str4, str2); ShuffleView c = LuckyMoneyF2FQRCodeUI.c(LuckyMoneyF2FQRCodeUI$1.this.kOv); if (c.kOO.size() > 0) { if (c.kOT.isStarted()) { c.kOT.end(); } if (c.kOS.isStarted()) { c.kOS.end(); } if (c.eRT != null) { c.kOX = c.eRT; c.kOO.remove(c.kOX); if (c.kOQ != null) { c.kOQ.start(); } c.sf(c.kOZ); if (c.kPc > 0) { c.kOZ = c.baP(); c.eRT = (View) c.kOO.get(c.kOZ); } else { c.eRT = null; c.kOZ = 0; } } else { c.sd(c.baP()); c.kOX = c.eRT; c.kOT.addListener(new 5(c)); } } LuckyMoneyF2FQRCodeUI.d(LuckyMoneyF2FQRCodeUI$1.this.kOv).remove(LuckyMoneyF2FQRCodeUI.c(LuckyMoneyF2FQRCodeUI$1.this.kOv).getExitView()); LuckyMoneyF2FQRCodeUI.e(LuckyMoneyF2FQRCodeUI$1.this.kOv).J(0, 60000); LuckyMoneyF2FQRCodeUI.f(LuckyMoneyF2FQRCodeUI$1.this.kOv).add(new Pair(str2, Integer.valueOf(bi.getInt(str3, 0)))); } } }); } } } }
/** **************************************************************************** * Copyright (c) The Spray Project. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Spray Dev Team - initial API and implementation **************************************************************************** */ package org.eclipselabs.spray.xtext.scoping; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.log4j.Logger; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Platform; import org.eclipse.emf.codegen.ecore.genmodel.GenModel; import org.eclipse.emf.codegen.ecore.genmodel.GenPackage; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.Resource.Diagnostic; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.xtext.EcoreUtil2; import org.eclipselabs.spray.mm.spray.Diagram; import org.eclipselabs.spray.mm.spray.Import; import com.google.common.collect.Iterables; import com.google.inject.Singleton; @Singleton public class PackageSelector { private static final Logger LOGGER = Logger.getLogger(PackageSelector.class); private Map<IContainer, Boolean> projectToChanged = new HashMap<IContainer, Boolean>(); private Map<IProject, Iterable<EPackage>> javaProjectToEPackages = new HashMap<IProject, Iterable<EPackage>>(); private JavaProjectHelper javaProjectHelper = new JavaProjectHelper(); private boolean workspaceChanged = true; public Iterable<EPackage> getFilteredEPackages(EObject modelElement) { IJavaProject project = javaProjectHelper.getJavaProject(modelElement); Iterable<EPackage> ePackages = null; if (project != null && !projectsHasChangedSinceLastRun(project) && !workspaceChanged) { ePackages = javaProjectToEPackages.get(project.getProject()); } if (ePackages == null) { ePackages = getEPackages(); if (project != null) { ePackages = filterAccessibleEPackages(project, ePackages); javaProjectToEPackages.put(project.getProject(), ePackages); } workspaceChanged = false; } return ePackages; } /** * @return */ private boolean projectsHasChangedSinceLastRun(IJavaProject project) { if (projectToChanged.size() == 0) { return true; } try { for (Map.Entry<IContainer, Boolean> entry : projectToChanged.entrySet()) { for (String requiredProjectName : project.getRequiredProjectNames()) { if (requiredProjectName.equals(entry.getKey().getName()) && entry.getValue() == Boolean.TRUE) { return true; } } } } catch (JavaModelException e) { e.printStackTrace(); } return false; } private List<EPackage> getEPackages() { registerWorkspaceEPackagesAndGenModels(); Set<Entry<String, Object>> packages = new HashSet<Entry<String, Object>>(); packages.addAll(EPackage.Registry.INSTANCE.entrySet()); List<EPackage> ePackages = new ArrayList<EPackage>(); try { Object packageObj = null; EPackage.Descriptor ePackageDescriptor = null; EPackage ePackage = null; for (Entry<String, Object> entry : packages) { packageObj = entry.getValue(); if (packageObj instanceof EPackage) { ePackages.add((EPackage) packageObj); } else if (packageObj instanceof EPackage.Descriptor) { ePackageDescriptor = (EPackage.Descriptor) packageObj; try { ePackage = ePackageDescriptor.getEPackage(); if (ePackage != null) { ePackages.add(ePackage); } } catch (Exception e) { e.printStackTrace(); } } } return ePackages; } catch (Exception e) { e.printStackTrace(); } return ePackages; } public void registerWorkspaceEPackagesAndGenModels() { if (isPlatformRunning()) { IWorkspace ws = getWorkspace(); if (ws != null) { final IWorkspaceRoot wsRoot = ws.getRoot(); if (wsRoot != null) { for (IProject project : wsRoot.getProjects()) { registerProjectChangeListener(ws, project); try { if (project.isOpen() && project.hasNature("org.eclipse.pde.PluginNature") && projectHasChangedSinceLastRun(project)) { project.accept(new ModelResourceVisitor(wsRoot)); } } catch (CoreException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } } recomputeResourceAndURIMaps(); } } /** * */ protected void recomputeResourceAndURIMaps() { EcorePlugin.computePlatformPluginToPlatformResourceMap(); EcorePlugin.computePlatformURIMap(); } /** * @return */ protected IWorkspace getWorkspace() { return ResourcesPlugin.getWorkspace(); } /** * @return */ protected boolean isPlatformRunning() { return Platform.isRunning(); } /** * @param project * @return */ private boolean projectHasChangedSinceLastRun(IProject project) { if (!projectToChanged.containsKey(project)) { projectToChanged.put(project, Boolean.TRUE); } Boolean changed = projectToChanged.get(project); if (changed) { projectToChanged.put(project, Boolean.FALSE); } return workspaceChanged | changed; } private void registerProjectChangeListener(final IWorkspace ws, final IProject project) { if (project != null && !projectToChanged.containsKey(project)) { projectToChanged.put(project, Boolean.TRUE); ws.addResourceChangeListener(new IResourceChangeListener() { @Override public void resourceChanged(IResourceChangeEvent event) { IResource resource = event.getResource(); if (resource != null) { IContainer projectContainingChange = javaProjectHelper.getProject(resource); if (projectContainingChange != null) { projectToChanged.put(projectContainingChange, true); } if (resource.equals(project) && (event.getBuildKind() == IResourceChangeEvent.PRE_DELETE || event.getBuildKind() == IResourceChangeEvent.PRE_CLOSE)) { projectToChanged.remove(project); javaProjectToEPackages.remove(project); } } else { workspaceChanged = true; } } }); } } public List<String> getAlreadyImportedForElement(EObject modelElement) { EObject container = null; if (modelElement instanceof Diagram) { container = modelElement; } else { container = EcoreUtil2.getContainerOfType(modelElement, Diagram.class); } return getAlreadyImported(container); } public List<String> getAlreadyImported(EObject container) { Import ni; List<String> alreadyImported = new ArrayList<String>(); if (container != null) { for (EObject child : container.eContents()) { if (child instanceof Import) { ni = (Import) child; alreadyImported.add(ni.getImportedNamespace()); } } } return alreadyImported; } public Iterable<EPackage> filterAccessibleEPackages(IJavaProject javaProject, Iterable<EPackage> ePackages) { List<EPackage> filteredEPackages = new ArrayList<EPackage>(); try { GenPackage genPackage = null; String fullqualifiedPackageClassName = null; IType type = null; for (EPackage ePackage : ePackages) { genPackage = getGenPackage(ePackage); if (genPackage != null) { fullqualifiedPackageClassName = genPackage.getClassPackageName() + "." + genPackage.getPackageClassName(); type = javaProject.findType(fullqualifiedPackageClassName); if (type != null) { filteredEPackages.add(ePackage); } } } } catch (JavaModelException e) { e.printStackTrace(); } return filteredEPackages; } private GenPackage getGenPackage(EPackage pack) { return getGenPackage(pack.getNsURI(), pack.getName()); } public GenPackage getGenPackage(String uri, String packageName) { URI genModelLoc = EcorePlugin.getEPackageNsURIToGenModelLocationMap().get(uri); if (genModelLoc == null) { LOGGER.error("No genmodel found for package URI " + uri + ". If you are running in stanalone mode make sure register the genmodel file."); return null; } ResourceSet rs = createResourceSet(); Resource genModelResource; try { genModelResource = rs.getResource(genModelLoc, true); if (genModelResource != null) { for (GenModel g : Iterables.filter(genModelResource.getContents(), GenModel.class)) { for (GenPackage genPack : g.getGenPackages()) { if (genPack.getEcorePackage().getNsURI().equals(uri) && genPack.getEcorePackage().getName().equals(packageName)) { return genPack; } } } } } catch (Exception e) { if (e instanceof java.io.FileNotFoundException) { System.err.println(e.getMessage()); } else if (e instanceof Diagnostic) { System.err.println(e.getMessage()); } else { e.printStackTrace(); } } return null; } /** * @return */ protected ResourceSet createResourceSet() { return new ResourceSetImpl(); } /** * @param model * @return */ public IJavaProject getJavaProject(EObject model) { return javaProjectHelper.getJavaProject(model); } }
package com.smxknife.java2.generics._method; /** * @author smxknife * 2019-04-17 */ public class GroupMethod { /** * 泛型方法的基本介绍 * @param clazz 传入的泛型实参 * @return T 返回值为T类型 * 说明: * 1)public 与 返回值中间<T>非常重要,可以理解为声明此方法为泛型方法。 * 2)只有声明了<T>的方法才是泛型方法,泛型类中的使用了泛型的成员方法并不是泛型方法。 * 3)<T>表明该方法将使用泛型类型T,此时才可以在方法中使用泛型类型T。 * 4)与泛型类的定义一样,此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型。 */ public <T> T getGroup(Class<T> clazz) throws IllegalAccessException, InstantiationException { return clazz.newInstance(); } public static void main(String[] args) throws InstantiationException, IllegalAccessException { GroupMethod groupMethod = new GroupMethod(); groupMethod.<String>getGroup(String.class); } }
package edu.isi.karma.cleaning.correctness; import java.util.ArrayList; import java.util.Arrays; import org.apache.commons.lang3.tuple.Pair; import edu.isi.karma.cleaning.DataPreProcessor; import edu.isi.karma.cleaning.DataRecord; import edu.isi.karma.cleaning.UtilTools; public class InspectorUtil { public static final int input_output = 1; public static final int input = 2; public static final int output = 3; public static String genKey(DataRecord record, int option){ if(option == input_output) return record.origin + " " + record.transformed; else if(option == input){ return record.origin; } else if(option == output){ return record.transformed; } else{ return ""; } } public static double[] getMeanVector(DataPreProcessor dpp, ArrayList<DataRecord> records, int targetContent){ ArrayList<double[]> classVectors = new ArrayList<double[]>(); for(DataRecord r: records){ String dr = genKey(r, targetContent); classVectors.add(dpp.getFeatureArray(dr)); } double[] tmean = UtilTools.sum(classVectors); tmean = UtilTools.produce(1.0/records.size(), tmean); return tmean; } public static double getDistance(DataPreProcessor dpp, DataRecord rec, double[] reference, double[] weight, int targetContent){ String dr = genKey(rec, targetContent); double[] self = dpp.getFeatureArray(dr); double ret = UtilTools.distance(self, reference, weight); return ret; } public static Pair<double[], double[]> getMeanVectorandStdevDistance(DataPreProcessor dpp, ArrayList<DataRecord> records, int targetContent){ ArrayList<double[]> classVectors = new ArrayList<double[]>(); for(DataRecord r: records){ String dr = genKey(r, targetContent); classVectors.add(dpp.getFeatureArray(dr)); } double[] tmean = UtilTools.sum(classVectors); tmean = UtilTools.produce(1.0/records.size(), tmean); double d_mu = 0; double[] alldists = new double[records.size()]; for(int i =0; i< records.size(); i++) { alldists[i]= UtilTools.distance(dpp.getFeatureArray(genKey(records.get(i), targetContent)), tmean, null); } Arrays.sort(alldists); double d_median = alldists.length > 0 ? alldists[alldists.length/2] : 0; for(int i =0; i< records.size(); i++) { d_mu += Math.pow(UtilTools.distance(dpp.getFeatureArray(genKey(records.get(i), targetContent)), tmean, null)-d_median, 2); } d_mu = Math.sqrt(d_mu/records.size()); double[] x = {d_median, d_mu}; Pair<double[], double[]> ret = Pair.of(x, tmean); return ret; } }
package com.sxf.entity; public class StudentClass { private Integer id; private Integer cid; private Integer sid; private String sname; private String cname; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getCid() { return cid; } public void setCid(Integer cid) { this.cid = cid; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } @Override public String toString() { return "StudentClass{" + "id=" + id + ", cid=" + cid + ", sid=" + sid + ", sname='" + sname + '\'' + ", cname='" + cname + '\'' + '}'; } }
package br.com.rogerio.scanner; import java.io.FileNotFoundException; import java.io.FileReader; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class LerArquivo { /** * @param args */ public static void main(String[] args) { Scanner sc = null; try { sc = new Scanner(new FileReader("c:/lixo/teste.txt")).useDelimiter(";"); while(sc.hasNext()){ String coluna1 = sc.next(); String coluna2 = sc.next(); System.out.println(coluna1); System.out.println(coluna2); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { sc.close(); } } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RemoveDuplicateArray { public static void main(String[] args){ removeDuplicate(Arrays.asList(new Integer[]{3, 1, 1, 6, 7})); } public static List removeDuplicate(List<Integer> list){ List<Integer> newList = new ArrayList<Integer>(list); for(int i = 0; i < list.size(); i++){ for(int j = i+1; j < list.size(); j++){ if(list.get(i) == list.get(j)){ newList.remove(j); } } } System.out.println(newList); return newList; } }
package com.udogan.magazayonetimi.ui; import javax.swing.JPanel; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; import javax.swing.text.MaskFormatter; import com.udogan.magazayonetimi.models.Distributor; import com.udogan.magazayonetimi.utils.dao.DbServicessBase; import javax.swing.SwingConstants; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.ParseException; import java.util.List; import static javax.swing.JOptionPane.showMessageDialog; import java.awt.BorderLayout; import javax.swing.JTable; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.JButton; import javax.swing.JFormattedTextField; import javax.swing.JScrollPane; public class DistributorIslemleriPaneli extends JPanel { private JPanel pnlDetay; private JPanel panelTablo; private JTable table; private JLabel lblUnvan; private JTextField txtIsim; private JTextField txtYetkili; private JTextField txtTelefon; private JTextPane txtAdres; private JLabel lblYetkili; private JLabel lblTelefon; private JLabel lblAdres; private JButton btnKaydet; private JScrollPane scrollPane; public MainFrame parentFrame; public DistributorIslemleriPaneli(MainFrame parentFrame) { this.parentFrame = parentFrame; setSize(1000, 500); GroupLayout groupLayout = new GroupLayout(this); groupLayout.setHorizontalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addContainerGap() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false) .addComponent(getPanelTablo(), GroupLayout.PREFERRED_SIZE, 748, GroupLayout.PREFERRED_SIZE) .addComponent(getPnlDetay(), GroupLayout.PREFERRED_SIZE, 745, GroupLayout.PREFERRED_SIZE)) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); groupLayout.setVerticalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addComponent(getPnlDetay(), GroupLayout.PREFERRED_SIZE, 199, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(getPanelTablo(), GroupLayout.PREFERRED_SIZE, 213, GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); groupLayout.linkSize(SwingConstants.HORIZONTAL, new Component[] {getPnlDetay(), getPanelTablo()}); setLayout(groupLayout); tabloyuDoldur(); } public void tabloyuDoldur() { try { DbServicessBase<Distributor> dao = new DbServicessBase<Distributor>(); Distributor temp = new Distributor(); List<Distributor> distributorListesi = dao.getAllRows(temp); String[] columnNames = { "id", "Unvan", "Yetkili Kişi", "Telefon", "Adres" }; Object[][] data = new Object[distributorListesi.size()][columnNames.length]; for (int i = 0; i < distributorListesi.size(); i++) { data[i][0] = ((Distributor) distributorListesi.get(i)).getId(); data[i][1] = ((Distributor) distributorListesi.get(i)).getIsim(); data[i][2] = ((Distributor) distributorListesi.get(i)).getYetkili(); data[i][3] = ((Distributor) distributorListesi.get(i)).getTelefon(); data[i][4] = ((Distributor) distributorListesi.get(i)).getAdres(); } table.setModel(new DefaultTableModel(data, columnNames)); table.setPreferredScrollableViewportSize(new Dimension(500, 70)); table.setFillsViewportHeight(true); TableColumnModel tcm = table.getColumnModel(); tcm.removeColumn(tcm.getColumn(0)); } catch (Exception e) { showMessageDialog(null, e.getMessage()); } } private JPanel getPnlDetay() { if (pnlDetay == null) { pnlDetay = new JPanel(); pnlDetay.setAlignmentY(Component.TOP_ALIGNMENT); pnlDetay.setAlignmentX(Component.LEFT_ALIGNMENT); pnlDetay.setLayout(null); pnlDetay.add(getLblUnvan()); pnlDetay.add(getTxtIsim()); pnlDetay.add(getTxtYetkili()); pnlDetay.add(getTxtTelefon()); pnlDetay.add(getTxtAdres()); pnlDetay.add(getLblYetkili()); pnlDetay.add(getLblTelefon()); pnlDetay.add(getLblAdres()); pnlDetay.add(getBtnKaydet()); } return pnlDetay; } private JPanel getPanelTablo() { if (panelTablo == null) { panelTablo = new JPanel(); panelTablo.setAlignmentY(Component.TOP_ALIGNMENT); panelTablo.setAlignmentX(Component.LEFT_ALIGNMENT); panelTablo.setLayout(new BorderLayout(0, 0)); panelTablo.add(getScrollPane()); } return panelTablo; } private JTable getTable() { if (table == null) { table = new JTable(); table.setAlignmentY(Component.TOP_ALIGNMENT); table.setAlignmentX(Component.LEFT_ALIGNMENT); table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int secilenSatir = table.getSelectedRow(); Distributor degistirilecekDistributor = new Distributor(); degistirilecekDistributor.setId(Long.parseLong(table.getModel().getValueAt(secilenSatir, 0).toString())); degistirilecekDistributor.setIsim(table.getModel().getValueAt(secilenSatir, 1).toString()); degistirilecekDistributor.setYetkili(table.getModel().getValueAt(secilenSatir, 2).toString()); degistirilecekDistributor.setTelefon(table.getModel().getValueAt(secilenSatir, 3).toString()); degistirilecekDistributor.setAdres(table.getModel().getValueAt(secilenSatir, 4).toString()); DistributorDegistirme frame = new DistributorDegistirme(e, degistirilecekDistributor); parentFrame.setEnabled(false); frame.setVisible(true); } }); } return table; } private JLabel getLblUnvan() { if (lblUnvan == null) { lblUnvan = new JLabel("Unvan :"); lblUnvan.setHorizontalAlignment(SwingConstants.RIGHT); lblUnvan.setBounds(24, 13, 87, 20); } return lblUnvan; } private JTextField getTxtIsim() { if (txtIsim == null) { txtIsim = new JTextField(); txtIsim.setBounds(121, 13, 176, 20); txtIsim.setColumns(10); } return txtIsim; } private JTextField getTxtYetkili() { if (txtYetkili == null) { txtYetkili = new JTextField(); txtYetkili.setBounds(121, 46, 176, 20); txtYetkili.setColumns(10); } return txtYetkili; } private JTextField getTxtTelefon() { if (txtTelefon == null) { MaskFormatter fmt; try { fmt = new MaskFormatter("0###-###-####"); txtTelefon = new JFormattedTextField(fmt); txtTelefon.setBounds(121, 79, 94, 20); txtTelefon.setColumns(10); } catch (ParseException e) { txtTelefon = new JTextField(); txtTelefon.setBounds(108, 91, 135, 20); txtTelefon.setColumns(10); } } return txtTelefon; } private JTextPane getTxtAdres() { if (txtAdres == null) { txtAdres = new JTextPane(); txtAdres.setBounds(121, 112, 176, 71); } return txtAdres; } private JLabel getLblYetkili() { if (lblYetkili == null) { lblYetkili = new JLabel("Yetkili Ki\u015Fi :"); lblYetkili.setHorizontalAlignment(SwingConstants.RIGHT); lblYetkili.setBounds(24, 46, 87, 20); } return lblYetkili; } private JLabel getLblTelefon() { if (lblTelefon == null) { lblTelefon = new JLabel("Telefon :"); lblTelefon.setHorizontalAlignment(SwingConstants.RIGHT); lblTelefon.setBounds(24, 79, 87, 20); } return lblTelefon; } private JLabel getLblAdres() { if (lblAdres == null) { lblAdres = new JLabel("Adres :"); lblAdres.setHorizontalAlignment(SwingConstants.RIGHT); lblAdres.setBounds(24, 112, 87, 20); } return lblAdres; } private JButton getBtnKaydet() { if (btnKaydet == null) { btnKaydet = new JButton("Kaydet"); btnKaydet.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { DbServicessBase<Distributor> dao = new DbServicessBase<Distributor>(); Distributor eklenecekDistributor = new Distributor(); eklenecekDistributor.setIsim(txtIsim.getText()); eklenecekDistributor.setYetkili(txtYetkili.getText()); eklenecekDistributor.setTelefon(txtTelefon.getText()); eklenecekDistributor.setAdres(txtAdres.getText()); if (dao.save(eklenecekDistributor)) { tabloyuDoldur(); txtIsim.setText(""); txtYetkili.setText(""); txtTelefon.setText(""); txtAdres.setText(""); } else { showMessageDialog(null, "Kaydetme İşlemi Başarısız Oldu!"); } } }); btnKaydet.setBounds(319, 160, 89, 23); } return btnKaydet; } private JScrollPane getScrollPane() { if (scrollPane == null) { scrollPane = new JScrollPane(); scrollPane.setAlignmentY(Component.TOP_ALIGNMENT); scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT); scrollPane.setViewportView(getTable()); } return scrollPane; } }
package com.class02; import org.testng.annotations.Test; public class priorty { @Test (priority=0) public void FirstTest() { System.out.println("First test annotation "); } @Test (priority=1) public static void secondTest() { System.out.println("Second test annotation "); } @Test (priority=2) public static void thirdTest() { System.out.println("Third test annotation "); } @Test //(Priority=3) public static void fourthTest() { System.out.println("Fouth test annotation "); } }
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class Kadai02Test { @Test void testCountString() { Kadai02 k = new Kadai02(); assertEquals(3,k.countString("aaabcdd", 'a')); assertEquals(0,k.countString("aaabcdd", 'あ')); assertEquals(1,k.countString("aaabcdd", 'b')); assertEquals(0,k.countString(null, 'a')); assertEquals(0,k.countString("bcd", 'a')); } }
/* * Copyright 2013 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.ui.server.services.mock; import static com.google.common.base.Predicates.and; import static com.google.common.base.Predicates.notNull; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.base.Strings.nullToEmpty; import static com.google.common.collect.Lists.newArrayList; import static java.lang.System.currentTimeMillis; import static org.overlord.rtgov.ui.client.model.ResolutionState.RESOLVED; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringReader; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.TreeSet; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Alternative; import org.overlord.rtgov.ui.client.model.NameValuePairBean; import org.overlord.rtgov.ui.client.model.ResolutionState; import org.overlord.rtgov.ui.client.model.BatchRetryResult; import org.overlord.rtgov.ui.client.model.CallTraceBean; import org.overlord.rtgov.ui.client.model.Constants; import org.overlord.rtgov.ui.client.model.MessageBean; import org.overlord.rtgov.ui.client.model.SituationBean; import org.overlord.rtgov.ui.client.model.SituationResultSetBean; import org.overlord.rtgov.ui.client.model.SituationSummaryBean; import org.overlord.rtgov.ui.client.model.SituationsFilterBean; import org.overlord.rtgov.ui.client.model.TraceNodeBean; import org.overlord.rtgov.ui.client.model.UiException; import org.overlord.rtgov.ui.server.services.ISituationsServiceImpl; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; /** * Concrete implementation of the faults service. * * @author eric.wittmann@redhat.com */ @ApplicationScoped @Alternative public class MockSituationsServiceImpl implements ISituationsServiceImpl { private Map<String,SituationSummaryBean> idToSituation = new HashMap<String,SituationSummaryBean>(); /** * Constructor. */ public MockSituationsServiceImpl() { } @PostConstruct public void init() { SituationSummaryBean situation = new SituationSummaryBean(); situation.setSituationId("1"); //$NON-NLS-1$ situation.setSeverity("critical"); //$NON-NLS-1$ situation.setType("Rate Limit Exceeded"); //$NON-NLS-1$ situation.setSubject("{urn:namespace}ImportantService|VeryImportantOperation"); //$NON-NLS-1$ situation.setTimestamp(new Date()); situation.setDescription("Some description of the Situation goes here in this column so that it can be read by the user."); //$NON-NLS-1$ situation.getProperties().put("Property-1", "Property one Value"); //$NON-NLS-1$ //$NON-NLS-2$ situation.getProperties().put("Property-2", "Property two Value"); //$NON-NLS-1$ //$NON-NLS-2$ situation.getProperties().put("Property-3", "Property three Value"); //$NON-NLS-1$ //$NON-NLS-2$ situation.getProperties().put("resolutionState", ResolutionState.UNRESOLVED.name()); //$NON-NLS-1$ //$NON-NLS-2$ situation.getProperties().put("host", "hostA"); //$NON-NLS-1$ //$NON-NLS-2$ idToSituation.put(situation.getSituationId(),situation); situation = new SituationSummaryBean(); situation.setSituationId("2"); //$NON-NLS-1$ situation.setSeverity("high"); //$NON-NLS-1$ situation.setType("SLA Violation"); //$NON-NLS-1$ situation.setSubject("{urn:namespace}ServiceA|OperationB"); //$NON-NLS-1$ situation.setTimestamp(new Date()); situation.setDescription("Some description of the Situation goes here in this column so that it can be read by the user."); //$NON-NLS-1$ situation.getProperties().put("resolutionState", ResolutionState.UNRESOLVED.name()); //$NON-NLS-1$ //$NON-NLS-2$ situation.getProperties().put("host", "hostA"); //$NON-NLS-1$ //$NON-NLS-2$ idToSituation.put(situation.getSituationId(),situation); situation = new SituationSummaryBean(); situation.setSituationId("3"); //$NON-NLS-1$ situation.setSeverity("high"); //$NON-NLS-1$ situation.setType("SLA Violation"); //$NON-NLS-1$ situation.setSubject("{urn:namespace}ServiceA|OperationB"); //$NON-NLS-1$ situation.setTimestamp(new Date()); situation.setDescription("Some description of the Situation goes here in this column so that it can be read by the user."); //$NON-NLS-1$ situation.getProperties().put("Property-1", "Property one Value"); //$NON-NLS-1$ //$NON-NLS-2$ situation.getProperties().put("Property-2", "Property two Value"); //$NON-NLS-1$ //$NON-NLS-2$ situation.getProperties().put("resolutionState", ResolutionState.UNRESOLVED.name()); //$NON-NLS-1$ //$NON-NLS-2$ situation.getProperties().put("host", "hostB"); //$NON-NLS-1$ //$NON-NLS-2$ idToSituation.put(situation.getSituationId(),situation); situation = new SituationSummaryBean(); situation.setSituationId("4"); //$NON-NLS-1$ situation.setSeverity("low"); //$NON-NLS-1$ situation.setType("Rate Limit Approaching"); //$NON-NLS-1$ situation.setSubject("{urn:namespace}SomeService|AnotherOperation"); //$NON-NLS-1$ situation.setTimestamp(new Date()); situation.setDescription("Some description of the Situation goes here in this column so that it can be read by the user."); //$NON-NLS-1$ situation.getProperties().put("resolutionState", ResolutionState.RESOLVED.name()); //$NON-NLS-1$ //$NON-NLS-2$ situation.getProperties().put("host", "hostB"); //$NON-NLS-1$ //$NON-NLS-2$ idToSituation.put(situation.getSituationId(),situation); } /** * @see org.overlord.rtgov.ui.server.services.ISituationsServiceImpl#search(SituationsFilterBean, int, String, boolean) */ @Override public SituationResultSetBean search(SituationsFilterBean filters, int page, String sortColumn, boolean ascending) throws UiException { SituationResultSetBean rval = new SituationResultSetBean(); List<SituationSummaryBean> situations = filter(filters, idToSituation.values()); sort(situations, sortColumn, ascending); rval.setSituations(situations); rval.setItemsPerPage(20); rval.setStartIndex(0); rval.setTotalResults(situations.size()); return rval; } private List<SituationSummaryBean> filter(final SituationsFilterBean filter, Iterable<SituationSummaryBean> situations) { Predicate<SituationSummaryBean> predicate = notNull(); if (!isNullOrEmpty(filter.getDescription())) { predicate = and(predicate, new Predicate<SituationSummaryBean>() { @Override public boolean apply(SituationSummaryBean input) { return nullToEmpty(input.getDescription()).contains(filter.getDescription()); } }); } if (!isNullOrEmpty(filter.getResolutionState())) { predicate = and(predicate, new Predicate<SituationSummaryBean>() { @Override public boolean apply(SituationSummaryBean input) { return nullToEmpty(input.getResolutionState()).equals(filter.getResolutionState()); } }); } if (!isNullOrEmpty(filter.getSeverity())) { predicate = and(predicate, new Predicate<SituationSummaryBean>() { @Override public boolean apply(SituationSummaryBean input) { return nullToEmpty(input.getSeverity()).equals(filter.getSeverity()); } }); } if (!isNullOrEmpty(filter.getType())) { predicate = and(predicate, new Predicate<SituationSummaryBean>() { @Override public boolean apply(SituationSummaryBean input) { return nullToEmpty(input.getType()).equals(filter.getType()); } }); } if (!isNullOrEmpty(filter.getSubject())) { predicate = and(predicate, new Predicate<SituationSummaryBean>() { @Override public boolean apply(SituationSummaryBean input) { return nullToEmpty(input.getSubject()).contains(filter.getSubject()); } }); } if (!isNullOrEmpty(filter.getProperties())) { final Properties properties = new Properties(); try { properties.load(new StringReader(filter.getProperties().replaceAll(";|,", "\n"))); } catch (IOException e) { e.printStackTrace(); } predicate = and(predicate, new Predicate<SituationSummaryBean>() { @Override public boolean apply(SituationSummaryBean input) { for (Entry<Object, Object> entry : properties.entrySet()) { if (!nullToEmpty(input.getProperties().get(entry.getKey())).contains( (String) entry.getValue())) { return false; } } return true; } }); } Iterable<SituationSummaryBean> iterable = Iterables.filter(situations, predicate); return newArrayList(iterable); } /** * Sorts the list of situations. * @param situations * @param sortColumn * @param ascending */ private void sort(List<SituationSummaryBean> situations, final String sortColumn, final boolean ascending) { TreeSet<SituationSummaryBean> sorted = new TreeSet<SituationSummaryBean>(new Comparator<SituationSummaryBean>() { @SuppressWarnings("unchecked") @Override public int compare(SituationSummaryBean sit1, SituationSummaryBean sit2) { Comparable<?> c1; Comparable<?> c2; if (sortColumn.equals(Constants.SORT_COLID_TYPE)) { c1 = sit1.getType(); c2 = sit2.getType(); } else if (sortColumn.equals(Constants.SORT_COLID_SUBJECT)) { c1 = sit1.getSubject(); c2 = sit2.getSubject(); } else if (sortColumn.equals(Constants.SORT_COLID_RESOLUTION_STATE)) { c1 = sit1.getResolutionState(); c2 = sit2.getResolutionState(); } else { c1 = sit1.getTimestamp(); c2 = sit2.getTimestamp(); } int rval = 0; if (ascending) { rval = ((Comparable<Object>) c1).compareTo(c2); } else { rval = ((Comparable<Object>) c2).compareTo(c1); } if (rval == 0) { rval = sit1.getSituationId().compareTo(sit2.getSituationId()); } return rval; } }); sorted.addAll(situations); situations.clear(); situations.addAll(sorted); } /** * @see org.overlord.rtgov.ui.server.services.ISituationsServiceImpl#getService(java.lang.String) */ @Override public SituationBean get(String situationId) throws UiException { SituationSummaryBean situationSummaryBean = idToSituation.get(situationId); SituationBean situation = new SituationBean(); situation.setSituationId(situationSummaryBean.getSituationId()); //$NON-NLS-1$ situation.setSeverity(situationSummaryBean.getSeverity()); //$NON-NLS-1$ situation.setType(situationSummaryBean.getType()); //$NON-NLS-1$ situation.setSubject(situationSummaryBean.getSubject()); //$NON-NLS-1$ situation.setTimestamp(situationSummaryBean.getTimestamp()); situation.setDescription(situationSummaryBean.getDescription()); //$NON-NLS-1$ Map<String, String> properties = situationSummaryBean.getProperties(); situation.setProperties(properties); //$NON-NLS-1$ //$NON-NLS-2$ situation.getContext().add(new NameValuePairBean("Context-1", "This is the value of the context 1 property.")); //$NON-NLS-1$ //$NON-NLS-2$ situation.getContext().add(new NameValuePairBean("Context-2", "This is the value of the context 2 property.")); //$NON-NLS-1$ //$NON-NLS-2$ MessageBean message = createMockMessage(); situation.setMessage(message); CallTraceBean callTrace = createMockCallTrace(); situation.setCallTrace(callTrace); situation.setResubmitPossible(situation.getSubject().contains("OperationB")); return situation; } /** * Creates a mock message. */ private MessageBean createMockMessage() { String msgContent = "<collection>\r\n" + //$NON-NLS-1$ "<asset>\r\n" + //$NON-NLS-1$ " <author>krisv</author>\r\n" + //$NON-NLS-1$ " <binaryContentAttachmentFileName></binaryContentAttachmentFileName>\r\n" + //$NON-NLS-1$ " <binaryLink>http://localhost:8080/drools-guvnor/rest/packages/srampPackage/assets/Evaluation/binary\r\n" + //$NON-NLS-1$ " </binaryLink>\r\n" + //$NON-NLS-1$ " <description></description>\r\n" + //$NON-NLS-1$ " <metadata>\r\n" + //$NON-NLS-1$ " <checkInComment>&lt;content from webdav&gt;</checkInComment>\r\n" + //$NON-NLS-1$ " <created>2012-10-05T14:34:14.970-04:00</created>\r\n" + //$NON-NLS-1$ " <disabled>false</disabled>\r\n" + //$NON-NLS-1$ " <format>bpmn</format>\r\n" + //$NON-NLS-1$ " <note>&lt;![CDATA[ &lt;content from webdav&gt; ]]&gt;</note>\r\n" + //$NON-NLS-1$ " <state>Draft</state>\r\n" + //$NON-NLS-1$ " <uuid>09512d48-585d-4393-86e2-39418369f066</uuid>\r\n" + //$NON-NLS-1$ " <versionNumber>9</versionNumber>\r\n" + //$NON-NLS-1$ " </metadata>\r\n" + //$NON-NLS-1$ " <published>2012-10-05T15:11:32.923-04:00</published>\r\n" + //$NON-NLS-1$ " <refLink>http://localhost:8080/drools-guvnor/rest/packages/srampPackage/assets/Evaluation\r\n" + //$NON-NLS-1$ " </refLink>\r\n" + //$NON-NLS-1$ " <sourceLink>http://localhost:8080/drools-guvnor/rest/packages/srampPackage/assets/Evaluation/source\r\n" + //$NON-NLS-1$ " </sourceLink>\r\n" + //$NON-NLS-1$ " <title>Evaluation</title>\r\n" + //$NON-NLS-1$ " </asset>\r\n" + //$NON-NLS-1$ "</asset>"; //$NON-NLS-1$ MessageBean msg = new MessageBean(); msg.setContent(msgContent); return msg; } /** * Creates a mock call trace! */ protected CallTraceBean createMockCallTrace() { CallTraceBean callTrace = new CallTraceBean(); TraceNodeBean rootNode = createTraceNode("Call", "Success", "urn:switchyard:parent", "submitOrder", 47, 100); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ callTrace.getTasks().add(rootNode); TraceNodeBean childNode = createTraceNode("Call", "Success", "urn:switchyard:application", "lookupItem", 10, 55); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ rootNode.getTasks().add(childNode); TraceNodeBean leafNode = createTraceNode("Task", "Success", null, null, 3, 30); //$NON-NLS-1$ //$NON-NLS-2$ leafNode.setDescription("Information: Found the item."); //$NON-NLS-1$ childNode.getTasks().add(leafNode); leafNode = createTraceNode("Task", "Success", null, null, 7, 70); //$NON-NLS-1$ //$NON-NLS-2$ leafNode.setDescription("Information: Secured the item."); //$NON-NLS-1$ childNode.getTasks().add(leafNode); childNode = createTraceNode("Call", "Success", "urn:switchyard:application", "deliver", 8, 44); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ childNode.setIface("org.overlord.public.interface.Application"); //$NON-NLS-1$ childNode.setOperation("doIt"); //$NON-NLS-1$ childNode.getProperties().put("property-1", "Value for property 1"); //$NON-NLS-1$ //$NON-NLS-2$ childNode.getProperties().put("property-2", "Value for property 2"); //$NON-NLS-1$ //$NON-NLS-2$ childNode.getProperties().put("property-3", "Value for property 3"); //$NON-NLS-1$ //$NON-NLS-2$ childNode.getProperties().put("property-4", "Value for property 4"); //$NON-NLS-1$ //$NON-NLS-2$ rootNode.getTasks().add(childNode); leafNode = createTraceNode("Task", "Success", null, null, 4, 100); //$NON-NLS-1$ //$NON-NLS-2$ leafNode.setDescription("Information: Delivering the order."); //$NON-NLS-1$ childNode.getTasks().add(leafNode); return callTrace; } /** * Creates a single trace node. * @param type * @param status * @param component * @param op * @param duration * @param percentage */ protected TraceNodeBean createTraceNode(String type, String status, String component, String op, long duration, int percentage) { TraceNodeBean node = new TraceNodeBean(); node.setType(type); node.setStatus(status); node.setComponent(component); node.setOperation(op); node.setDuration(duration); node.setPercentage(percentage); return node; } /** * @see org.overlord.rtgov.ui.server.services.ISituationsServiceImpl#resubmit(java.lang.String, java.lang.String) */ @Override public void resubmit(String situationId, String message, String username) throws UiException { // Do nothing! System.out.println("Resubmitted message for situation: " + situationId); //$NON-NLS-1$ System.out.println(message); SituationSummaryBean situationSummaryBean = idToSituation.get(situationId); Map<String, String> properties = situationSummaryBean.getProperties(); if (username != null) { properties.put("resubmitBy", username); } properties.put("resubmitAt", Long.toString(currentTimeMillis())); if ("Success".equals(properties.get("resubmitResult"))) { properties.put("resubmitErrorMessage", "Timeout while.."); properties.put("resubmitResult", "Error"); } else { properties.put("resubmitResult", "Success"); properties.remove("resubmitErrorMessage"); } } @Override public void assign(String situationId, String userName) throws UiException { idToSituation.get(situationId).getProperties().put("assignedTo", userName); } @Override public void unassign(String situationId) throws UiException { SituationSummaryBean situationSummaryBean = idToSituation.get(situationId); Map<String, String> properties = situationSummaryBean.getProperties(); properties.remove("assignedTo"); String resolutionState = properties.get("resolutionState"); if (resolutionState != null && RESOLVED != ResolutionState.valueOf(resolutionState)) { properties.remove("resolutionState"); } } @Override public void updateResolutionState(String situationId, ResolutionState resolutionState) { idToSituation.get(situationId).getProperties().put("resolutionState", resolutionState.name()); } @Override public BatchRetryResult resubmit(SituationsFilterBean situationsFilterBean, String username) { BatchRetryResult batchRetryResult = new BatchRetryResult(); batchRetryResult.setProcessedCount(4); batchRetryResult.setFailedCount(2); batchRetryResult.setIgnoredCount(1); return batchRetryResult; } @Override public void export(SituationsFilterBean situationsFilterBean, OutputStream outputStream) { String situationId = idToSituation.keySet().iterator().next(); PrintWriter printWriter = new PrintWriter(outputStream); try { SituationBean situationBean = get(situationId); printWriter.println(situationBean.getMessage().getContent()); } catch (UiException e) { e.printStackTrace(); } finally { if (null != printWriter) { printWriter.close(); } } } @Override public int delete(SituationsFilterBean situationsFilterBean) throws UiException { return 0; } @Override public SituationResultSetBean getResubmitFailures(String situationId, int page, String sortColumn, boolean ascending) throws UiException { // TODO Auto-generated method stub return null; } }
package com.gome.presto; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PrestoJdbcCli { private static Statement statement; private static Connection conn; static Logger logger = LoggerFactory.getLogger(PrestoJdbcCli.class); public static void main(String[] args) throws Exception { /*List<String> apps = getApplication("2016-05-01"); for(String app:apps){ System.out.println(app); }*/ //String sql="select * from glogs where dt=#{dt} and application=#{application} order by sequence asc limit 10"; String sql = "select * from glogs where # order by sequence asc limit 10"; Map<String,Object> map = new HashMap<String,Object>(); map.put("dt", "2016-05-03"); map.put("application", "t3_log"); //map.put("ip", "10.58.173.83"); //map.put("filename", "/app/stage/pangu-trading_01/logs/app.log"); //map.put("ts", "1462118400000,1462122000000"); //map.put("message", "ERROR"); presto_query(sql,map); } public static Connection createConnection() throws SQLException, ClassNotFoundException { //Class.forName("com.facebook.presto.jdbc.PrestoDriver"); return DriverManager.getConnection("jdbc:presto://10.58.50.249:5050/hive/gm_cloud_logs", "rw_cld_hive_dev", "lK7mN6GtZZDj"); } public static List<String> getApplication(String dt) throws ClassNotFoundException, SQLException{ List<String> apps = new ArrayList<String>(); conn = createConnection(); statement = conn.createStatement(); ResultSet rs = statement.executeQuery("select application,count(1) as count from logs where dt='" + dt + "' group by application") ; /*ResultSetMetaData metadata = rs.getMetaData(); System.out.println(metadata.getColumnCount());*/ while(rs.next()){ if(rs.getString("application") != null && !"null".equals(rs.getString("application"))) apps.add(rs.getString("application")); } return apps; } public static void query(String sql,Map<String,Object> map) throws SQLException, ClassNotFoundException{ conn = createConnection(); statement = conn.createStatement(); for(String key : map.keySet()){ sql = sql.replace("#{" + key + "}", "'" + (String) map.get(key) + "'"); } System.out.println(sql); long begin = System.currentTimeMillis(); ResultSet rs = statement.executeQuery(sql) ; ResultSetMetaData metadata = rs.getMetaData(); System.out.println(metadata.getColumnCount()); long end = System.currentTimeMillis(); System.out.println((end - begin) + " ms "); while(rs.next()){ System.out.println(rs.getString("ip")+ "," + rs.getString("message")); } statement.close(); conn.close(); } public static void presto_query(String sql,Map<String,Object> map) throws SQLException, ClassNotFoundException{ conn = createConnection(); statement = conn.createStatement(); String where = ""; for(String key : map.keySet()){ if(key.equals("ts")){ String ts = (String) map.get(key); where += "ts between '" + ts.split(",")[0] + "' and '" + ts.split(",")[1] + "' and "; }else if (key.equals("message")){ where += key + " like " + "'%" + (String) map.get(key) + "%' and "; }else{ where += key + "=" + "'" + (String) map.get(key) + "' and "; } } if(!where.equals("")) where = where.substring(0, where.length()-4); System.out.println(where); sql = sql.replace("#", where); System.out.println(sql); long begin = System.currentTimeMillis(); ResultSet rs = statement.executeQuery(sql) ; ResultSetMetaData metadata = rs.getMetaData(); System.out.println(metadata.getColumnCount()); long end = System.currentTimeMillis(); System.out.println((end - begin) + " ms "); while(rs.next()){ System.out.println(rs.getString("dt")+ "," + rs.getString("message") + ", " + rs.getString("filename")); //System.out.println(rs.getInt(1)); } statement.close(); conn.close(); } }
package com.paleimitations.schoolsofmagic.common.registries; import com.google.common.collect.Lists; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.item.crafting.Ingredient; import net.minecraft.potion.EffectInstance; import net.minecraft.potion.Effects; import java.util.Arrays; import java.util.List; public class TeaIngredientRegistry { public static List<TeaIngredient> INGREDIENTS = Lists.newArrayList(); public static void register() { INGREDIENTS.add(new TeaIngredient(TeaRegistry.getTea("allium"), Ingredient.of(ItemRegistry.CRUSHED_ALLIUM.get()))); INGREDIENTS.add(new TeaIngredient(TeaRegistry.getTea("blue_orchid"), Ingredient.of(ItemRegistry.CRUSHED_BLUE_ORCHID.get()))); INGREDIENTS.add(new TeaIngredient(TeaRegistry.getTea("cornflower"), Ingredient.of(ItemRegistry.CRUSHED_CORNFLOWER.get()))); INGREDIENTS.add(new TeaIngredient(TeaRegistry.getTea("dandelion"), Ingredient.of(ItemRegistry.CRUSHED_DANDELION.get()))); INGREDIENTS.add(new TeaIngredient(TeaRegistry.getTea("lily_of_the_valley"), Ingredient.of(ItemRegistry.CRUSHED_LILY_OF_THE_VALLY.get()))); INGREDIENTS.add(new TeaIngredient(TeaRegistry.getTea("poppy_seed"), Ingredient.of(ItemRegistry.POPPY_SEEDS.get()))); INGREDIENTS.add(new TeaIngredient(TeaRegistry.getTea("cocoa_bean"), Ingredient.of(Items.COCOA_BEANS))); INGREDIENTS.add(new TeaIngredient(TeaRegistry.getTea("sugar"), Ingredient.of(Items.SUGAR))); } public static TeaIngredient getIngredient(ItemStack stack) { for(TeaIngredient ingredient : INGREDIENTS) { if (ingredient.isIngredient(stack)) return ingredient; } return null; } public static TeaIngredient getIngredient(String name) { for(TeaIngredient ingredient : INGREDIENTS) { if (ingredient.tea.name.equalsIgnoreCase(name)) return ingredient; } return null; } public static class TeaIngredient { public final TeaRegistry.Tea tea; public final Ingredient ingredient; public TeaIngredient(TeaRegistry.Tea tea, Ingredient ingredient) { this.tea = tea; this.ingredient = ingredient; } public Ingredient getIngredient() { return ingredient; } public List<EffectInstance> getEffects() { return tea.effects; } public boolean isIngredient(ItemStack stack) { return ingredient.test(stack); } } }
/* * Copyright 2019 iserge. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cleanlogic.rsc4j.format; import com.google.gson.annotations.Expose; import java.nio.ByteBuffer; /** * Structure of default values for semantic * * @author Serge Silaev aka iSergio <s.serge.b@gmail.com> */ public class RSCSemanticDefault { /** * Total length of structure */ private final static int LENGTH = 32; /** * Ordinal number of object */ private int number; /** * Semantic code */ private int code; /** * Minimal semantic value */ private double min; /** * Default semantic value */ private double def; /** * Maximal semantic value */ private double max; public RSCSemanticDefault() {} public int getLength() { return LENGTH; } public int getNumber() { return number; } public int getCode() { return code; } public double getMin() { return min; } public double getDef() { return def; } public double getMax() { return max; } public void read(ByteBuffer buffer, boolean strict) { // Buffer position before begin read int pos = buffer.position(); this.number = buffer.getInt(); this.code = buffer.getInt(); this.min = buffer.getDouble(); this.def = buffer.getDouble(); this.max = buffer.getDouble(); // Check length and readed data size int _length = buffer.position() - pos; if (this.getLength() != _length) { System.err.println("Something wrong read default semantic. Aspect/Actual:" + this.getLength() + "/" + _length); } // Force set buffer offset to end of semantic record buffer.position(pos + this.getLength()); } }
package lesson12; public class Main { public static void main(String[] args) { Bank usBank = new USBank(22, "USA", Currency.USD, 1000, 2000, 9, 100000); Bank euBank = new EUBank(33, "Poland", Currency.EUR, 100, 2000, 62, 500000); Bank chinaBank = new ChinaBank(44, "China", Currency.USD, 100, 500, 12, 100000); User user1 = new User(1, "Alex", 10000, 20, "Microsoft", 1200, euBank); User user2 = new User(2, "Bob", 12200, 40, "Github", 1400, euBank); User user3 = new User(3, "Kat", 3000, 8, "DW", 600, usBank); User user4 = new User(4, "Susana", 100000, 10, "PepsiCo", 1200, usBank); User user5 = new User(5, "Li", 4500, 2, "RedDragon", 300, chinaBank); User user6 = new User(6, "Cho", 2000, 17, "NiHao", 900, chinaBank); System.out.println(" 1"); BankSystem ukrainianBankSystem1 = new UkrainianBankSystem(); ukrainianBankSystem1.withdraw(user2, 150); System.out.println(user2.getBalance()); System.out.println(""); ukrainianBankSystem1.paySalary(user2); System.out.println(user2.getBalance()); ukrainianBankSystem1.fund(user2,200); System.out.println(user2.getBalance()); ukrainianBankSystem1.transferMoney(user2, user1, 100); System.out.println(user2.getBalance()); System.out.println(user1.getBalance()); System.out.println(" 2"); BankSystem ukrainianBankSystem2 = new UkrainianBankSystem(); ukrainianBankSystem2.withdraw(user3, 150); System.out.println(user3.getBalance()); System.out.println(""); ukrainianBankSystem2.paySalary(user2); System.out.println(user3.getBalance()); ukrainianBankSystem2.fund(user2,200); System.out.println(user3.getBalance()); ukrainianBankSystem2.transferMoney(user3, user4, 100); System.out.println(user3.getBalance()); System.out.println(user4.getBalance()); System.out.println(" 3"); BankSystem ukrainianBankSystem3 = new UkrainianBankSystem(); ukrainianBankSystem3.withdraw(user5, 90); System.out.println(user5.getBalance()); System.out.println(""); ukrainianBankSystem3.paySalary(user5); System.out.println(user5.getBalance()); ukrainianBankSystem3.fund(user5,60); System.out.println(user5.getBalance()); ukrainianBankSystem3.transferMoney(user5, user6, 50); System.out.println(user5.getBalance()); System.out.println(user6.getBalance()); } }
package com.example.user.catchthemonster; /** * Created by user on 6/7/17. */ public class monstrik { int x; int y; }
sout("hello");
package cn.jbit.classandobject; public class AdministratorTest { public static void main(String[] args) { Administrator admin1 = new Administrator(); Administrator admin2 = new Administrator(); admin1.name="admin1"; admin1.password="111111"; admin1.show(); admin2.name="admin2"; admin2.password="222222"; admin2.show(); } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.gcm_driver; import android.content.Intent; import android.os.Bundle; import com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener; import org.chromium.base.ThreadUtils; /** * Receives GCM registration events and messages rebroadcast by MultiplexingGcmListener. */ public class GCMListener extends MultiplexingGcmListener.AbstractListener { /** * Receiver for broadcasts by the multiplexed GCM service. It forwards them to * GCMListener. * * This class is public so that it can be instantiated by the Android runtime. */ public static class Receiver extends MultiplexingGcmListener.AbstractListener.Receiver { @Override protected Class<?> getServiceClass() { return GCMListener.class; } } private static final String TAG = "GCMListener"; // Used as a fallback until GCM always gives us the subtype. // TODO(johnme): Remove this once it does. static final String UNKNOWN_APP_ID = "push#https://www.gcmlistenerfake.com#0"; public GCMListener() { super(TAG); } @Override protected void onRegistered(String registrationId) { // Ignore this, since we register using GoogleCloudMessagingV2. } @Override protected void onUnregistered(String registrationId) { // Ignore this, since we register using GoogleCloudMessagingV2. } @Override protected void onMessage(final Intent intent) { final String bundleSubtype = "subtype"; final String bundleDataForPushApi = "data"; Bundle extras = intent.getExtras(); if (!extras.containsKey(bundleSubtype) && !extras.containsKey(bundleDataForPushApi)) { // TODO(johnme): Once GCM always gives us the subtype, we'll be able to early-out if // there is no subtype extra. For now we have to also allow messages without subtype // if they have the data key which suggests they are for the Push API, but this is // technically a layering violation as this code is for other consumers of GCM too. return; } final String appId = extras.containsKey(bundleSubtype) ? extras.getString(bundleSubtype) : UNKNOWN_APP_ID; ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { GCMDriver.onMessageReceived(getApplicationContext(), appId, intent.getExtras()); } }); } @Override protected void onDeletedMessages(int total) { ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { GCMDriver.onMessagesDeleted(getApplicationContext(), UNKNOWN_APP_ID); } }); } }
package edu.buet.cse.spring.ch07.v5.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import edu.buet.cse.spring.ch07.v5.model.Message; import edu.buet.cse.spring.ch07.v5.service.ChirperService; public class MessageController extends AbstractController { private final ChirperService chirperService; public MessageController(ChirperService chirperService) { this.chirperService = chirperService; } @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) { ModelAndView mv = new ModelAndView("messageList"); List<Message> messages = chirperService.getMessages(); mv.addObject("messages", messages); return mv; } }
package net.minecraft.world; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public enum DimensionType { OVERWORLD(0, "overworld", "", (Class)WorldProviderSurface.class), NETHER(-1, "the_nether", "_nether", (Class)WorldProviderHell.class), THE_END(1, "the_end", "_end", (Class)WorldProviderEnd.class); private final int id; private final String name; private final String suffix; private final Class<? extends WorldProvider> clazz; DimensionType(int idIn, String nameIn, String suffixIn, Class<? extends WorldProvider> clazzIn) { this.id = idIn; this.name = nameIn; this.suffix = suffixIn; this.clazz = clazzIn; } public int getId() { return this.id; } public String getName() { return this.name; } public String getSuffix() { return this.suffix; } public WorldProvider createDimension() { try { Constructor<? extends WorldProvider> constructor = this.clazz.getConstructor(new Class[0]); return constructor.newInstance(new Object[0]); } catch (NoSuchMethodException nosuchmethodexception) { throw new Error("Could not create new dimension", nosuchmethodexception); } catch (InvocationTargetException invocationtargetexception) { throw new Error("Could not create new dimension", invocationtargetexception); } catch (InstantiationException instantiationexception) { throw new Error("Could not create new dimension", instantiationexception); } catch (IllegalAccessException illegalaccessexception) { throw new Error("Could not create new dimension", illegalaccessexception); } } public static DimensionType getById(int id) { byte b; int i; DimensionType[] arrayOfDimensionType; for (i = (arrayOfDimensionType = values()).length, b = 0; b < i; ) { DimensionType dimensiontype = arrayOfDimensionType[b]; if (dimensiontype.getId() == id) return dimensiontype; b++; } throw new IllegalArgumentException("Invalid dimension id " + id); } public static DimensionType func_193417_a(String p_193417_0_) { byte b; int i; DimensionType[] arrayOfDimensionType; for (i = (arrayOfDimensionType = values()).length, b = 0; b < i; ) { DimensionType dimensiontype = arrayOfDimensionType[b]; if (dimensiontype.getName().equals(p_193417_0_)) return dimensiontype; b++; } throw new IllegalArgumentException("Invalid dimension " + p_193417_0_); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\world\DimensionType.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.jk.jkproject.ui.widget.room; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import com.anbetter.log.MLog; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.AbstractDraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.postprocessors.IterativeBoxBlurPostProcessor; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import com.jk.jkproject.R; import com.jk.jkproject.net.im.cores.MessageNotifyCenter; import com.jk.jkproject.net.okhttp.ResponseListener; import com.jk.jkproject.ui.entity.PkSuccessInfo; import com.jk.jkproject.utils.Constants; import cn.iwgang.countdownview.CountdownView; public class PkWaitView extends RelativeLayout implements View.OnClickListener, ResponseListener { private CountdownView countdown; private PkSuccessInfo successInfo; private TextView title, tvUnit, tvDesc; private SimpleDraweeView head; public PkWaitView(Context context) { super(context); init(context); } public PkWaitView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public PkWaitView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } //高斯模糊 public static void showUrlBlur(SimpleDraweeView draweeView, String url, int iterations, int blurRadius) { try { Uri uri = Uri.parse(url); ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri) .setPostprocessor(new IterativeBoxBlurPostProcessor(iterations, blurRadius)) .build(); AbstractDraweeController controller = Fresco.newDraweeControllerBuilder() .setOldController(draweeView.getController()) .setImageRequest(request) .build(); draweeView.setController(controller); } catch (Exception e) { e.printStackTrace(); } } private void init(Context context) { LayoutInflater.from(context).inflate(R.layout.view_live_pk_wait, this, true); countdown = findViewById(R.id.wait_countdown); tvDesc = findViewById(R.id.wait_desc); title = findViewById(R.id.wait_title); tvUnit = findViewById(R.id.wait_unit); head = findViewById(R.id.wait_image); findViewById(R.id.im_close_wait).setOnClickListener(this); } public void setDate(final PkSuccessInfo successInfo) { this.successInfo = successInfo; //随机匹配 if (TextUtils.isEmpty(successInfo.getUid()) || successInfo.isRandom()) { countdown.setVisibility(INVISIBLE); tvUnit.setVisibility(INVISIBLE); title.setText("随机挑战"); tvDesc.setText("匹配中"); if (successInfo != null && successInfo.getHead() != null) { showUrlBlur(head, successInfo.getHead(), 8, 8); } } else {//指定好友匹配 if (successInfo != null && successInfo.getHead() != null) { head.setImageURI(successInfo.getHead()); } tvDesc.setText(successInfo.getNickname()); title.setText("挑战好友"); countdown.setVisibility(VISIBLE); tvUnit.setVisibility(VISIBLE); countdown.customTimeShow(false, false, false, true, false); countdown.start(successInfo.getWait_seconds() * 1000); countdown.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() { @Override public void onEnd(CountdownView cv) { if (getVisibility() == VISIBLE) { // AppApis.startOrEndPk(SPUtils.Impl.getUid(), successInfo.getUid(), "end", PkWaitView.this); setVisibility(GONE); } } }); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.im_close_wait: // AppApis.startOrEndPk(SPUtils.Impl.getUid(), successInfo.getUid(), "end", this); setVisibility(GONE); break; } } @Override public void onSuccess(String url, Object obj) { MLog.e("tag wait ", obj.toString()); Bundle bd = new Bundle(); bd.putInt("method", Constants.OBSERVABLE_ACTION_PK_END_MESSAGE_ROOM_FOR_USER); bd.putString("object", "您取消了pk挑战"); MessageNotifyCenter.getInstance().doNotify(bd); } @Override public void onStartRequest() { } @Override public void onFailure(int code, String url, String error) { } public void setVisible() { if (countdown != null) { countdown.pause(); } } public void destory() { if (countdown != null) { countdown = null; } if (successInfo != null) { successInfo = null; } if (title != null) { title = null; } if (tvUnit != null) { tvUnit = null; } if (tvDesc != null) { tvDesc = null; } if (head != null) { head = null; } } }
package com.tnnowu.android.googlenavigation; import android.annotation.SuppressLint; import android.app.Notification; import android.os.Handler; import android.os.Looper; import android.os.Message; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import java.util.Vector; public class Client implements Runnable { Handler handler; public Handler revHandler; public Client(Handler handler) { this.handler = handler; } public Client(){} private Socket sock; private Thread thread; BufferedReader in; private PrintWriter out; private final static int DEFAULT_PORT = 1234; private final static String HOST = "47.93.199.31"; String cmd; Vector<String>ret; public Vector<String> startConnect(String str) throws Exception { cmd = str; ret = new Vector<>(); // try { // sock = new Socket(HOST, DEFAULT_PORT); // System.out.println("Connection ok"); // in = new BufferedReader( // new InputStreamReader(sock.getInputStream())); // out = new java.io.PrintWriter(sock.getOutputStream()); // } catch(Exception e) { // String tmp = e.getMessage(); // e.printStackTrace(); // System.out.println("Connection failed"); // } thread = new Thread(this); thread.start(); thread.join(); return ret; } // @SuppressLint("HandlerLeak") public void run() { try { sock = new Socket(HOST, DEFAULT_PORT); in = new BufferedReader( new InputStreamReader(sock.getInputStream())); out = new java.io.PrintWriter(sock.getOutputStream()); try { sendMsg(cmd); } catch (IOException e) { e.printStackTrace(); } while (true) { try { String msg = receiveMsg(); if(msg.equals("!!!")) break; ret.add(msg); } catch (IOException e) { e.printStackTrace(); } catch (Exception ei) {} } // new Thread() // { // @Override // public void run() // { // try { // while (true) { // String str = in.readLine(); // Message msg = new Message(); // msg.what = 0x123; // msg.obj = str; // handler.sendMessage(msg); // if (str.equals("!!!")) // break; // } // } // catch (IOException e) { // e.printStackTrace(); // } // } // }.start(); // // Looper.prepare(); // revHandler = new Handler() // { // @Override // public void handleMessage(Message msg) // { // if(msg.what==0x345) // { // try // { // //out.write((msg.obj.toString()+"\r\n").getBytes("utf-8")); // sendMsg(msg.obj.toString()); // } // catch (Exception e){ // String tmp = e.getMessage(); // e.printStackTrace(); // } // } // } // }; // Looper.loop(); } catch (Exception e) { e.printStackTrace(); } } public String receiveMsg() throws IOException { try { String msg = in.readLine(); return msg; } catch(IOException e) { e.printStackTrace(); } return ""; } public void sendMsg(String msg) throws IOException { out.println(msg); out.flush(); } }
package cn.wolfcode.crm.web.controller; import cn.wolfcode.crm.query.ChartQueryObject; import cn.wolfcode.crm.service.IChartService; import cn.wolfcode.crm.util.JsonUtil; import cn.wolfcode.crm.util.MessageUtil; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/chart") public class ChartController { @Autowired private IChartService chartService; @RequestMapping("/list") @RequiresPermissions(value = {"潜在用户报表查询", "chart:list"}, logical = Logical.OR) public String list(Model model, @ModelAttribute("qo") ChartQueryObject qo) { model.addAttribute("charts", chartService.queryCustomerChart(qo)); return "chart/list"; } @RequestMapping("/chartByBar") public String charByBar(Model model, @ModelAttribute("qo") ChartQueryObject qo) { //1、准备报表中头需要的子标题[销售员,年份,月份] model.addAttribute("groupTypeName", MessageUtil.changMsg(qo)); List<Map<String, Object>> maps = chartService.queryCustomerChart(qo); //2、准备报表尾部对应的数值 List<Object> groupByTypes = new ArrayList<>(); for (Map<String, Object> map : maps) { groupByTypes.add(map.get("groupByType")); } //将集合转换为Json数据 model.addAttribute("groupTypes", JsonUtil.toJsonString(groupByTypes)); //3、准备报表尾部对应的数值 List<Object> totalNumbers = new ArrayList<>(); for (Map<String, Object> map : maps) { totalNumbers.add(map.get("totalNumber")); } //将集合转换为Json数据 model.addAttribute("totalNumbers", JsonUtil.toJsonString(totalNumbers)); return "chart/chartByBar"; } @RequestMapping("/chartByPie") public String charByPie(Model model, @ModelAttribute("qo") ChartQueryObject qo) { //1、查询报表头部的子标题,回显 String message = MessageUtil.changMsg(qo); model.addAttribute("groupByTypeName", message); //2、查询报表的目录和查询报表的数据 List<Map<String, Object>> maps = chartService.queryCustomerChart(qo); List<Object> groupByTypes = new ArrayList<>(); List<Map<String, Object>> datas = new ArrayList<>(); for (Map<String, Object> map : maps) { groupByTypes.add(map.get("groupByType")); Map<String, Object> data = new HashMap<>(); data.put("value", map.get("totalNumber")); data.put("name", map.get("groupByType")); datas.add(data); } model.addAttribute("groupByTypes", JsonUtil.toJsonString(groupByTypes)); model.addAttribute("datas", JsonUtil.toJsonString(datas)); return "chart/chartByPie"; } }
/** * */ package com.dotedlabs.app.coffer.factory; /** * @author Sandeep * */ public interface RepositoryProcessor { /** * Get the configuration for the repository * * @return */ public Object getConfig(); }
import java.util.ArrayList; import java.util.Random; public class Test{ public static void main (String [] args){ Random rand = new Random(); ArrayList<Integer> list = new ArrayList<Integer>(); for(int i =0; i<7;i++) list.add(rand.nextInt(25)); for(int i = 0; i<7;i++) System.out.print("\t"+list.get(i)); ArrayList<Integer> newList = BubbleSorter.sort((ArrayList<Integer>) list.clone()); ArrayList<Integer> newListOne = CockTailShaker.sort((ArrayList<Integer>) list.clone()); System.out.println(); for(int i = 0;i<7;i++){ if(i%10 ==0) System.out.println(); System.out.print("\t" + newList.get(i)); }//End for System.out.println(); for(int i = 0; i<7;i++) System.out.print("\t"+list.get(i)); for(int i = 0;i<7;i++){ if(i%10 ==0) System.out.println(); System.out.print("\t" + newListOne.get(i)); }//End for }//End Main }//End Class
package com.kdgm.webservice; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="pGun" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="pAy" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="pYil" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "pGun", "pAy", "pYil" }) @XmlRootElement(name = "YeniDisYazismaYapanlariGetirWs") public class YeniDisYazismaYapanlariGetirWs { protected int pGun; protected int pAy; protected int pYil; /** * Gets the value of the pGun property. * */ public int getPGun() { return pGun; } /** * Sets the value of the pGun property. * */ public void setPGun(int value) { this.pGun = value; } /** * Gets the value of the pAy property. * */ public int getPAy() { return pAy; } /** * Sets the value of the pAy property. * */ public void setPAy(int value) { this.pAy = value; } /** * Gets the value of the pYil property. * */ public int getPYil() { return pYil; } /** * Sets the value of the pYil property. * */ public void setPYil(int value) { this.pYil = value; } }
package com.tencent.mm.modelvoice; class i$a implements Runnable { final /* synthetic */ i epi; private i$a(i iVar) { this.epi = iVar; } /* synthetic */ i$a(i iVar, byte b) { this(iVar); } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public final void run() { /* r12 = this; r0 = -16; android.os.Process.setThreadPriority(r0); Catch:{ Exception -> 0x00ad } r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.f(r0); Catch:{ Exception -> 0x00ad } r1 = 2; r2 = 2; r0 = android.media.AudioTrack.getMinBufferSize(r0, r1, r2); Catch:{ Exception -> 0x00ad } r0 = r0 * 2; r9 = new byte[r0]; Catch:{ Exception -> 0x00ad } r1 = r12.epi; Catch:{ Exception -> 0x00ad } r1 = com.tencent.mm.modelvoice.i.f(r1); Catch:{ Exception -> 0x00ad } r1 = r1 * 20; r1 = r1 / 1000; r10 = (short) r1; Catch:{ Exception -> 0x00ad } r1 = "MicroMsg.SilkPlayer"; r2 = "frameLen: %d, playBufferSize: %d"; r3 = 2; r3 = new java.lang.Object[r3]; Catch:{ Exception -> 0x00ad } r4 = 0; r5 = java.lang.Short.valueOf(r10); Catch:{ Exception -> 0x00ad } r3[r4] = r5; Catch:{ Exception -> 0x00ad } r4 = 1; r0 = java.lang.Integer.valueOf(r0); Catch:{ Exception -> 0x00ad } r3[r4] = r0; Catch:{ Exception -> 0x00ad } com.tencent.mm.sdk.platformtools.x.d(r1, r2, r3); Catch:{ Exception -> 0x00ad } r0 = "MicroMsg.SilkPlayer"; r1 = "Thread start"; com.tencent.mm.sdk.platformtools.x.i(r0, r1); Catch:{ Exception -> 0x00ad } L_0x0043: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.g(r0); Catch:{ Exception -> 0x00ad } r1 = 1; if (r0 == r1) goto L_0x0055; L_0x004c: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.g(r0); Catch:{ Exception -> 0x00ad } r1 = 2; if (r0 != r1) goto L_0x02e4; L_0x0055: r1 = com.tencent.mm.modelvoice.i.TD(); Catch:{ Exception -> 0x00ad } monitor-enter(r1); Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.TE(); Catch:{ all -> 0x0145 } r2 = r12.epi; Catch:{ all -> 0x0145 } r2 = com.tencent.mm.modelvoice.i.h(r2); Catch:{ all -> 0x0145 } if (r0 == r2) goto L_0x0095; L_0x0066: r0 = "MicroMsg.SilkPlayer"; r2 = "[%d] diff id, useDeocder: %d"; r3 = 2; r3 = new java.lang.Object[r3]; Catch:{ all -> 0x0145 } r4 = 0; r5 = r12.epi; Catch:{ all -> 0x0145 } r5 = com.tencent.mm.modelvoice.i.h(r5); Catch:{ all -> 0x0145 } r5 = java.lang.Integer.valueOf(r5); Catch:{ all -> 0x0145 } r3[r4] = r5; Catch:{ all -> 0x0145 } r4 = 1; r5 = com.tencent.mm.modelvoice.i.TE(); Catch:{ all -> 0x0145 } r5 = java.lang.Integer.valueOf(r5); Catch:{ all -> 0x0145 } r3[r4] = r5; Catch:{ all -> 0x0145 } com.tencent.mm.sdk.platformtools.x.i(r0, r2, r3); Catch:{ all -> 0x0145 } r0 = r12.epi; Catch:{ all -> 0x0145 } r2 = r12.epi; Catch:{ all -> 0x0145 } r2 = com.tencent.mm.modelvoice.i.d(r2); Catch:{ all -> 0x0145 } com.tencent.mm.modelvoice.i.a(r0, r2); Catch:{ all -> 0x0145 } L_0x0095: monitor-exit(r1); Catch:{ all -> 0x0145 } L_0x0096: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.i(r0); Catch:{ Exception -> 0x00ad } if (r0 == 0) goto L_0x0148; L_0x009e: r0 = "MicroMsg.SilkPlayer"; r1 = "waitting for switching complete"; com.tencent.mm.sdk.platformtools.x.d(r0, r1); Catch:{ Exception -> 0x00ad } r0 = 20; java.lang.Thread.sleep(r0); Catch:{ Exception -> 0x00ad } goto L_0x0096; L_0x00ad: r0 = move-exception; r1 = com.tencent.mm.plugin.report.service.h.mEJ; r2 = 161; // 0xa1 float:2.26E-43 double:7.95E-322; r4 = 0; r6 = 1; r8 = 0; r1.a(r2, r4, r6, r8); r1 = "MicroMsg.SilkPlayer"; r2 = "exception:%s"; r3 = 1; r3 = new java.lang.Object[r3]; r4 = 0; r0 = com.tencent.mm.sdk.platformtools.bi.i(r0); r3[r4] = r0; com.tencent.mm.sdk.platformtools.x.e(r1, r2, r3); r0 = r12.epi; r0 = com.tencent.mm.modelvoice.i.n(r0); if (r0 == 0) goto L_0x00e1; L_0x00d5: r0 = r12.epi; r0 = com.tencent.mm.modelvoice.i.n(r0); r1 = 0; r2 = 0; r3 = 0; r0.onError(r1, r2, r3); L_0x00e1: r0 = r12.epi; r1 = 0; com.tencent.mm.modelvoice.i.a(r0, r1); L_0x00e7: r1 = com.tencent.mm.modelvoice.i.TD(); monitor-enter(r1); r0 = com.tencent.mm.modelvoice.i.TE(); Catch:{ all -> 0x02f4 } r2 = r12.epi; Catch:{ all -> 0x02f4 } r2 = com.tencent.mm.modelvoice.i.h(r2); Catch:{ all -> 0x02f4 } if (r0 != r2) goto L_0x0117; L_0x00f8: com.tencent.mm.modelvoice.MediaRecorder.SilkDecUnInit(); Catch:{ all -> 0x02f4 } r0 = "MicroMsg.SilkPlayer"; r2 = "[%d] SilkDecUnInit"; r3 = 1; r3 = new java.lang.Object[r3]; Catch:{ all -> 0x02f4 } r4 = 0; r5 = r12.epi; Catch:{ all -> 0x02f4 } r5 = com.tencent.mm.modelvoice.i.h(r5); Catch:{ all -> 0x02f4 } r5 = java.lang.Integer.valueOf(r5); Catch:{ all -> 0x02f4 } r3[r4] = r5; Catch:{ all -> 0x02f4 } com.tencent.mm.sdk.platformtools.x.i(r0, r2, r3); Catch:{ all -> 0x02f4 } com.tencent.mm.modelvoice.i.TF(); Catch:{ all -> 0x02f4 } L_0x0117: monitor-exit(r1); Catch:{ all -> 0x02f4 } r0 = r12.epi; r0 = com.tencent.mm.modelvoice.i.g(r0); r1 = 3; if (r0 == r1) goto L_0x02f7; L_0x0121: r0 = r12.epi; r0 = com.tencent.mm.modelvoice.i.o(r0); if (r0 == 0) goto L_0x0132; L_0x0129: r0 = r12.epi; r0 = com.tencent.mm.modelvoice.i.o(r0); r0.wd(); L_0x0132: r0 = r12.epi; r0 = com.tencent.mm.modelvoice.i.p(r0); if (r0 == 0) goto L_0x0144; L_0x013a: r0 = r12.epi; r0 = com.tencent.mm.modelvoice.i.p(r0); r1 = 0; r0.onCompletion(r1); L_0x0144: return; L_0x0145: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x0145 } throw r0; Catch:{ Exception -> 0x00ad } L_0x0148: r11 = com.tencent.mm.modelvoice.MediaRecorder.SilkDoDec(r9, r10); Catch:{ Exception -> 0x00ad } if (r11 >= 0) goto L_0x01a3; L_0x014e: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r1 = 0; com.tencent.mm.modelvoice.i.a(r0, r1); Catch:{ Exception -> 0x00ad } r1 = com.tencent.mm.plugin.report.service.h.mEJ; Catch:{ Exception -> 0x00ad } r2 = 161; // 0xa1 float:2.26E-43 double:7.95E-322; r4 = 0; r6 = 1; r8 = 0; r1.a(r2, r4, r6, r8); Catch:{ Exception -> 0x00ad } r1 = com.tencent.mm.plugin.report.service.h.mEJ; Catch:{ Exception -> 0x00ad } r2 = 161; // 0xa1 float:2.26E-43 double:7.95E-322; r4 = 4; r6 = 1; r8 = 0; r1.a(r2, r4, r6, r8); Catch:{ Exception -> 0x00ad } r0 = "MicroMsg.SilkPlayer"; r1 = "[%d] SilkDoDec failed: %d"; r2 = 2; r2 = new java.lang.Object[r2]; Catch:{ Exception -> 0x00ad } r3 = 0; r4 = r12.epi; Catch:{ Exception -> 0x00ad } r4 = com.tencent.mm.modelvoice.i.h(r4); Catch:{ Exception -> 0x00ad } r4 = java.lang.Integer.valueOf(r4); Catch:{ Exception -> 0x00ad } r2[r3] = r4; Catch:{ Exception -> 0x00ad } r3 = 1; r4 = java.lang.Integer.valueOf(r11); Catch:{ Exception -> 0x00ad } r2[r3] = r4; Catch:{ Exception -> 0x00ad } com.tencent.mm.sdk.platformtools.x.e(r0, r1, r2); Catch:{ Exception -> 0x00ad } r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.j(r0); Catch:{ Exception -> 0x00ad } if (r0 == 0) goto L_0x0043; L_0x0194: r0 = com.tencent.mm.platformtools.af.exQ; Catch:{ Exception -> 0x00ad } if (r0 == 0) goto L_0x0043; L_0x0198: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.j(r0); Catch:{ Exception -> 0x00ad } r0.wC(); Catch:{ Exception -> 0x00ad } goto L_0x0043; L_0x01a3: r0 = com.tencent.mm.platformtools.af.exQ; Catch:{ Exception -> 0x00ad } if (r0 == 0) goto L_0x01ba; L_0x01a7: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.j(r0); Catch:{ Exception -> 0x00ad } if (r0 == 0) goto L_0x01ba; L_0x01af: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.j(r0); Catch:{ Exception -> 0x00ad } r1 = r10 * 2; r0.w(r9, r1); Catch:{ Exception -> 0x00ad } L_0x01ba: r0 = r12.epi; Catch:{ Exception -> 0x020b } r0 = com.tencent.mm.modelvoice.i.b(r0); Catch:{ Exception -> 0x020b } r1 = 0; r2 = r10 * 2; r0.write(r9, r1, r2); Catch:{ Exception -> 0x020b } L_0x01c6: r0 = r12.epi; Catch:{ Exception -> 0x00ad } com.tencent.mm.modelvoice.i.k(r0); Catch:{ Exception -> 0x00ad } if (r11 != 0) goto L_0x0238; L_0x01cd: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r1 = 0; com.tencent.mm.modelvoice.i.a(r0, r1); Catch:{ Exception -> 0x00ad } r0 = "MicroMsg.SilkPlayer"; r1 = "[%d] play completed"; r2 = 1; r2 = new java.lang.Object[r2]; Catch:{ Exception -> 0x00ad } r3 = 0; r4 = r12.epi; Catch:{ Exception -> 0x00ad } r4 = com.tencent.mm.modelvoice.i.h(r4); Catch:{ Exception -> 0x00ad } r4 = java.lang.Integer.valueOf(r4); Catch:{ Exception -> 0x00ad } r2[r3] = r4; Catch:{ Exception -> 0x00ad } com.tencent.mm.sdk.platformtools.x.i(r0, r1, r2); Catch:{ Exception -> 0x00ad } r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.j(r0); Catch:{ Exception -> 0x00ad } if (r0 == 0) goto L_0x0043; L_0x01f4: r0 = com.tencent.mm.platformtools.af.exQ; Catch:{ Exception -> 0x00ad } if (r0 == 0) goto L_0x0043; L_0x01f8: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.j(r0); Catch:{ Exception -> 0x00ad } r0.wC(); Catch:{ Exception -> 0x00ad } r0 = new com.tencent.mm.modelvoice.i$a$1; Catch:{ Exception -> 0x00ad } r0.<init>(r12); Catch:{ Exception -> 0x00ad } com.tencent.mm.sdk.platformtools.ah.A(r0); Catch:{ Exception -> 0x00ad } goto L_0x0043; L_0x020b: r0 = move-exception; r1 = "MicroMsg.SilkPlayer"; r2 = "write audio track failed: %s"; r3 = 1; r3 = new java.lang.Object[r3]; Catch:{ Exception -> 0x00ad } r4 = 0; r0 = r0.getMessage(); Catch:{ Exception -> 0x00ad } r3[r4] = r0; Catch:{ Exception -> 0x00ad } com.tencent.mm.sdk.platformtools.x.e(r1, r2, r3); Catch:{ Exception -> 0x00ad } r1 = com.tencent.mm.plugin.report.service.h.mEJ; Catch:{ Exception -> 0x00ad } r2 = 161; // 0xa1 float:2.26E-43 double:7.95E-322; r4 = 0; r6 = 1; r8 = 0; r1.a(r2, r4, r6, r8); Catch:{ Exception -> 0x00ad } r1 = com.tencent.mm.plugin.report.service.h.mEJ; Catch:{ Exception -> 0x00ad } r2 = 161; // 0xa1 float:2.26E-43 double:7.95E-322; r4 = 5; r6 = 1; r8 = 0; r1.a(r2, r4, r6, r8); Catch:{ Exception -> 0x00ad } goto L_0x01c6; L_0x0238: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.g(r0); Catch:{ Exception -> 0x00ad } r1 = 2; if (r0 != r1) goto L_0x02b9; L_0x0241: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r1 = com.tencent.mm.modelvoice.i.l(r0); Catch:{ Exception -> 0x00ad } monitor-enter(r1); Catch:{ Exception -> 0x00ad } r0 = "MicroMsg.SilkPlayer"; r2 = "before mOk.notify"; com.tencent.mm.sdk.platformtools.x.v(r0, r2); Catch:{ Exception -> 0x028c } r0 = r12.epi; Catch:{ Exception -> 0x028c } r0 = com.tencent.mm.modelvoice.i.l(r0); Catch:{ Exception -> 0x028c } r0.notify(); Catch:{ Exception -> 0x028c } r0 = "MicroMsg.SilkPlayer"; r2 = "after mOk.notify"; com.tencent.mm.sdk.platformtools.x.v(r0, r2); Catch:{ Exception -> 0x028c } L_0x0263: monitor-exit(r1); Catch:{ all -> 0x02a1 } r0 = r12.epi; Catch:{ Exception -> 0x00ad } r1 = com.tencent.mm.modelvoice.i.m(r0); Catch:{ Exception -> 0x00ad } monitor-enter(r1); Catch:{ Exception -> 0x00ad } r0 = "MicroMsg.SilkPlayer"; r2 = "before mpause.wait"; com.tencent.mm.sdk.platformtools.x.v(r0, r2); Catch:{ Exception -> 0x02a4 } r0 = r12.epi; Catch:{ Exception -> 0x02a4 } r0 = com.tencent.mm.modelvoice.i.m(r0); Catch:{ Exception -> 0x02a4 } r0.wait(); Catch:{ Exception -> 0x02a4 } r0 = "MicroMsg.SilkPlayer"; r2 = "after mpause.wait"; com.tencent.mm.sdk.platformtools.x.v(r0, r2); Catch:{ Exception -> 0x02a4 } L_0x0286: monitor-exit(r1); Catch:{ all -> 0x0289 } goto L_0x0043; L_0x0289: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x0289 } throw r0; Catch:{ Exception -> 0x00ad } L_0x028c: r0 = move-exception; r2 = "MicroMsg.SilkPlayer"; r3 = "exception:%s"; r4 = 1; r4 = new java.lang.Object[r4]; Catch:{ all -> 0x02a1 } r5 = 0; r0 = com.tencent.mm.sdk.platformtools.bi.i(r0); Catch:{ all -> 0x02a1 } r4[r5] = r0; Catch:{ all -> 0x02a1 } com.tencent.mm.sdk.platformtools.x.e(r2, r3, r4); Catch:{ all -> 0x02a1 } goto L_0x0263; L_0x02a1: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x02a1 } throw r0; Catch:{ Exception -> 0x00ad } L_0x02a4: r0 = move-exception; r2 = "MicroMsg.SilkPlayer"; r3 = "exception:%s"; r4 = 1; r4 = new java.lang.Object[r4]; Catch:{ all -> 0x0289 } r5 = 0; r0 = com.tencent.mm.sdk.platformtools.bi.i(r0); Catch:{ all -> 0x0289 } r4[r5] = r0; Catch:{ all -> 0x0289 } com.tencent.mm.sdk.platformtools.x.e(r2, r3, r4); Catch:{ all -> 0x0289 } goto L_0x0286; L_0x02b9: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r1 = com.tencent.mm.modelvoice.i.l(r0); Catch:{ Exception -> 0x00ad } monitor-enter(r1); Catch:{ Exception -> 0x00ad } r0 = r12.epi; Catch:{ Exception -> 0x02cf } r0 = com.tencent.mm.modelvoice.i.l(r0); Catch:{ Exception -> 0x02cf } r0.notify(); Catch:{ Exception -> 0x02cf } L_0x02c9: monitor-exit(r1); Catch:{ all -> 0x02cc } goto L_0x0043; L_0x02cc: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x02cc } throw r0; Catch:{ Exception -> 0x00ad } L_0x02cf: r0 = move-exception; r2 = "MicroMsg.SilkPlayer"; r3 = "exception:%s"; r4 = 1; r4 = new java.lang.Object[r4]; Catch:{ all -> 0x02cc } r5 = 0; r0 = com.tencent.mm.sdk.platformtools.bi.i(r0); Catch:{ all -> 0x02cc } r4[r5] = r0; Catch:{ all -> 0x02cc } com.tencent.mm.sdk.platformtools.x.e(r2, r3, r4); Catch:{ all -> 0x02cc } goto L_0x02c9; L_0x02e4: r0 = r12.epi; Catch:{ Exception -> 0x00ad } r0 = com.tencent.mm.modelvoice.i.g(r0); Catch:{ Exception -> 0x00ad } r1 = 3; if (r0 == r1) goto L_0x00e7; L_0x02ed: r0 = 1000; // 0x3e8 float:1.401E-42 double:4.94E-321; java.lang.Thread.sleep(r0); Catch:{ Exception -> 0x00ad } goto L_0x00e7; L_0x02f4: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x02f4 } throw r0; L_0x02f7: r0 = r12.epi; r0 = com.tencent.mm.modelvoice.i.b(r0); if (r0 == 0) goto L_0x0144; L_0x02ff: r0 = "MicroMsg.SilkPlayer"; r1 = "mAudioTrack.stop()"; com.tencent.mm.sdk.platformtools.x.i(r0, r1); r0 = r12.epi; r0 = com.tencent.mm.modelvoice.i.b(r0); r0.stop(); r0 = r12.epi; r0 = com.tencent.mm.modelvoice.i.b(r0); r0.release(); r0 = r12.epi; com.tencent.mm.modelvoice.i.c(r0); goto L_0x0144; */ throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.modelvoice.i$a.run():void"); } }
package login; import static org.junit.Assert.*; import java.security.NoSuchAlgorithmException; import org.junit.Test; import org.myftp.gattserver.grass.core.login.GrassAuthenticator; /** * http://www.sha1.cz/ * * @author gatt * */ public class Hash { @Test public void testSimple() throws NoSuchAlgorithmException { assertEquals(GrassAuthenticator.bytesToHex(GrassAuthenticator.getSHA1FromString("test")), "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"); } @Test public void testZeroOnStart() throws NoSuchAlgorithmException { assertEquals(GrassAuthenticator.bytesToHex(GrassAuthenticator.getSHA1FromString("teu2%%")), "062b709052089d562995c2a3bf82f223df8f9d40"); } }
import java.util.Collection; import java.util.Iterator; import java.util.Set; public class HashedSet <E> implements Set<E> { Element<E>[] table; int numOfKeys; int numOfBuckets; private class Element<E>{ E key; Element next; public Element(E k, Element n){ key = k; next = n; } } private void initialize(){ numOfBuckets = 2; numOfKeys = 0; table = new Element[numOfBuckets]; } private double loadFactor(){ return numOfKeys/ (double) numOfBuckets; } private int getIndex(E key, int buckets){ int hash = key.hashCode(); hash = (3*hash) + 4; hash %= buckets; return hash; } private void resizeTable(){ Integer newNumOfBuckets = null; if(loadFactor() > 0.5){ newNumOfBuckets = numOfBuckets * 2; }else if(loadFactor() < 0.25){ newNumOfBuckets = numOfBuckets / 2; } if(newNumOfBuckets != null){ Element<E>[] newTable = new Element[newNumOfBuckets]; Iterator <E> myIter = iterator(); while(myIter.hasNext()){ E key = myIter.next(); int index = getIndex(key, newNumOfBuckets); if(newTable[index] != null) { Element newElem = new Element(key, newTable[index]); newTable[index] = newElem; }else{ newTable[index] = new Element(key, null); } } table = newTable; numOfBuckets = newNumOfBuckets; } } public HashedSet(){ initialize(); } @Override public boolean add(E e) { if(contains(e)){ return false; } int index = getIndex(e, numOfBuckets); if(table[index] != null) { Element newElem = new Element(e, table[index]); table[index] = newElem; }else{ table[index] = new Element(e, null); } numOfKeys++; resizeTable(); return true; } @Override public boolean addAll(Collection<? extends E> c) { for(E key: c){ add(key); } return true; } @Override public void clear() { initialize(); } public boolean equals(Object o){ if(!(o instanceof Set)){ return false; } Set oSet = (Set) o; if(oSet.size() != this.size()){ return false; } if(!oSet.containsAll(this)){ return false; } return true; } @Override public boolean contains(Object o) { int index = getIndex((E)o, numOfBuckets); Element e = table[index]; while(e != null){ if(e.key.equals(o)){ return true; } e = e.next; } return false; } @Override public boolean containsAll(Collection<?> c) { boolean doesContainAll = true; for(Object key: c){ if(!contains(key)){ doesContainAll = false; } } return doesContainAll; } @Override public boolean isEmpty() { if(numOfKeys == 0){ return true; }else{ return false; } } @Override public Iterator<E> iterator() { return new HashedSetIterator(); } @Override public boolean remove(Object o) { if(!contains(o)){ return false; } int index = getIndex((E)o, numOfBuckets); Element current = table[index]; if(current.key.equals((o))){ table[index] = table[index].next; }else{ Element previous = null; while(!current.key.equals(o)){ previous = current; current = current.next; } previous.next = current.next; } numOfKeys--; resizeTable(); return true; } @Override public boolean removeAll(Collection<?> c) { boolean setChanged = false; for(Object key: c){ if(remove(key)){ setChanged = true; } } resizeTable(); return setChanged; } @Override public boolean retainAll(Collection<?> c) { boolean setChanged = false; Iterator <E> myIter = iterator(); while(myIter.hasNext()){ if(!c.contains(myIter.next())){ myIter.remove(); setChanged = true; } } resizeTable(); return setChanged; } @Override public int size() { return numOfKeys; } @Override public Object[] toArray() { Object[] retArr = new Object[numOfKeys]; Iterator <E> myIter = iterator(); for(int i = 0; i < numOfKeys; i++){ retArr[i] = myIter.next(); } return retArr; } @Override public <T> T[] toArray(T[] a) { T[] retArr = (T[]) new Object[numOfKeys]; Iterator <E> myIter = iterator(); for(int i = 0; i < numOfKeys; i++){ retArr[i] = (T)myIter.next(); } return retArr; } public String toString(){ String retString = ""; for(int i = 0; i < numOfBuckets; i ++){ retString += "Ind " + i + ": "; Element tempElem = table[i]; while(tempElem != null){ retString += tempElem.key + "->"; tempElem = tempElem.next; } retString += '\n'; } retString += "NumOfBuckets:" + numOfBuckets + " Keys: " + numOfKeys; return retString; } class HashedSetIterator implements Iterator<E>{ int currentIndex; int previousIndex; Element currentElement; Element previousElement; public HashedSetIterator(){ previousElement = null; currentIndex = 0; currentElement = table[currentIndex]; while(currentElement == null && currentIndex < (numOfBuckets-1)){ currentIndex ++; currentElement = table[currentIndex]; } } @Override public boolean hasNext() { if(currentElement == null){ return false; } return true; } @Override public E next() { previousElement = currentElement; previousIndex = currentIndex; currentElement = currentElement.next; while(currentElement == null && currentIndex < (numOfBuckets - 1)){ currentIndex ++; currentElement = table[currentIndex]; } return (E) previousElement.key; } @Override public void remove() { if(previousElement==null){ throw new IllegalStateException(); } if(previousElement == table[previousIndex]){ table[previousIndex] = previousElement.next; }else{ Element tempElem = table[previousIndex]; while(tempElem.next != previousElement){ tempElem = tempElem.next; } tempElem.next = tempElem.next.next; } numOfKeys --; previousElement = null; } } }
/* * FileName: SimpleStringTransform.java * Description: * Company: 南宁超创信息工程有限公司 * Copyright: ChaoChuang (c) 2007 * History: 2007-09-21 (guig) 1.0 Create */ package com.spower.basesystem.excel.importer.transform; import org.springframework.beans.BeanWrapper; import com.spower.basesystem.excel.importer.IDataTransform; /** * @author guig * */ public class SimpleStringTransform implements IDataTransform { /* (non-Javadoc) * @see com.spower.basesystem.excel.importer.IDataTransform#transform(org.springframework.beans.BeanWrapper, java.lang.String, java.lang.Object, java.lang.String, java.lang.StringBuffer) */ public boolean transform(BeanWrapper bean, String fieldName, Object value, String title, StringBuffer errorMessage) { try { bean.setPropertyValue(fieldName, value); } catch (Exception e) { errorMessage.append("转换字段【").append(title).append("】的值时发生错误!请检查填写的内容。"); return false; } return true; } }
/** * <copyright> * </copyright> * * $Id$ */ package edu.tsinghua.lumaqq.ecore.face; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.AbstractEnumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Constant</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see edu.tsinghua.lumaqq.ecore.face.FacePackage#getFaceConstant() * @model * @generated */ public final class FaceConstant extends AbstractEnumerator { /** * The '<em><b>DEFAULT GROUP ID</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>DEFAULT GROUP ID</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #DEFAULT_GROUP_ID_LITERAL * @model * @generated * @ordered */ public static final int DEFAULT_GROUP_ID = 0; /** * The '<em><b>RECEIVED GROUP ID</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>RECEIVED GROUP ID</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #RECEIVED_GROUP_ID_LITERAL * @model * @generated * @ordered */ public static final int RECEIVED_GROUP_ID = 1; /** * The '<em><b>CUSTOM HEAD GROUP ID</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>CUSTOM HEAD GROUP ID</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #CUSTOM_HEAD_GROUP_ID_LITERAL * @model * @generated * @ordered */ public static final int CUSTOM_HEAD_GROUP_ID = 2; /** * The '<em><b>DEFAULT GROUP ID</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #DEFAULT_GROUP_ID * @generated * @ordered */ public static final FaceConstant DEFAULT_GROUP_ID_LITERAL = new FaceConstant(DEFAULT_GROUP_ID, "DEFAULT_GROUP_ID", "DEFAULT_GROUP_ID"); /** * The '<em><b>RECEIVED GROUP ID</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #RECEIVED_GROUP_ID * @generated * @ordered */ public static final FaceConstant RECEIVED_GROUP_ID_LITERAL = new FaceConstant(RECEIVED_GROUP_ID, "RECEIVED_GROUP_ID", "RECEIVED_GROUP_ID"); /** * The '<em><b>CUSTOM HEAD GROUP ID</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #CUSTOM_HEAD_GROUP_ID * @generated * @ordered */ public static final FaceConstant CUSTOM_HEAD_GROUP_ID_LITERAL = new FaceConstant(CUSTOM_HEAD_GROUP_ID, "CUSTOM_HEAD_GROUP_ID", "CUSTOM_HEAD_GROUP_ID"); /** * An array of all the '<em><b>Constant</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final FaceConstant[] VALUES_ARRAY = new FaceConstant[] { DEFAULT_GROUP_ID_LITERAL, RECEIVED_GROUP_ID_LITERAL, CUSTOM_HEAD_GROUP_ID_LITERAL, }; /** * A public read-only list of all the '<em><b>Constant</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Constant</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static FaceConstant get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { FaceConstant result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Constant</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static FaceConstant getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { FaceConstant result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Constant</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static FaceConstant get(int value) { switch (value) { case DEFAULT_GROUP_ID: return DEFAULT_GROUP_ID_LITERAL; case RECEIVED_GROUP_ID: return RECEIVED_GROUP_ID_LITERAL; case CUSTOM_HEAD_GROUP_ID: return CUSTOM_HEAD_GROUP_ID_LITERAL; } return null; } /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private FaceConstant(int value, String name, String literal) { super(value, name, literal); } } //FaceConstant
/**************************************************** * $Project: DinoAge $ * $Date:: Jan 5, 2008 1:36:31 PM $ * $Revision: $ * $Author:: khoanguyen $ * $Comment:: $ **************************************************/ package org.ddth.blogging.yahoo.grabber.handler; import org.ddth.blogging.yahoo.YahooBlogEntry; import org.ddth.blogging.yahoo.YahooBlogUtil; import org.ddth.blogging.yahoo.grabber.YBlogEntryContent; import org.ddth.http.core.content.Content; import org.ddth.http.impl.content.DomTreeContent; import org.w3c.dom.Document; public class YGuestbookContentHandler extends YahooBlogContentHandler { @Override public Content<?> handle(Content<?> content) { DomTreeContent domTreeContent = (DomTreeContent) super.handle(content); Document doc = domTreeContent.getDocument(); YahooBlogEntry yahooGuestbook = YahooBlogUtil.parseGuestbook(doc); YBlogEntryContent guestbookContent = new YBlogEntryContent(domTreeContent, yahooGuestbook); return guestbookContent; } }
package mincutsforpalindromes; public class Solution { public int minCuts(String input) { // Write your solution here. if(input == null || input.length() == 0){ return 0; } int length = input.length(); int [] cut = new int[length]; for(int i = 1; i < length; i++){ cut[i] = cut[i-1]+1; if(ispalindromes(input,0,i)){ cut[i] = 0; } for(int j = i-1; j >= 0; j--){ if(ispalindromes(input,j+1,i)){ cut[i] = Math.min(cut[i],cut[j]+1); } } } return cut[length-1]; } private boolean ispalindromes(String s, int j, int i){ for(int k = 0; k <= (i-j)/2; k++){ if(s.charAt(j+k) != s.charAt(i-k)){ return false; } } return true; } public static void main (String [] args){ Solution s = new Solution(); System.out.println(s.minCuts("abcbd")); } }
import processing.core.*; import processing.data.*; import processing.event.*; import processing.opengl.*; import hypermedia.video.*; import java.util.HashMap; import java.util.ArrayList; import java.io.File; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; public class WebCam_Automata extends PApplet { OpenCV opencv; float x1, y1, x2, y2, x3, y3; // contantes para triangulo equilatero int a = 12; float x = a/2; float y = a * sqrt(3)/3 * sin(radians(30)); float h = a * sqrt(3)/3; int twidth, theight; //Espacio celular int rows = 133; int cols = 70; int[][] space = new int[rows][cols]; int[][] spaceCopy = new int[rows][cols]; //color array logo ADC2 int[] mycolours = { color(0, 170, 232), color(5, 111, 192), color(23, 52, 186), color(25, 25, 87), color(120, 78, 156), color(79, 61, 147), color(52, 67, 150), color(35, 24, 119), color(191, 215, 65), color(145, 198, 55), color(59, 177, 66), color(0, 141, 64), color(254, 197, 11), color(254, 132, 29), color(229, 83, 0), color(223, 55, 23), color(255, 255, 255) } ; public void setup() { size(displayWidth, displayHeight); background(0); opencv = new OpenCV( this ); opencv.capture( rows, cols ); // open video stream } public void draw() { frameRate(10); loadPixels(); opencv.read(); //captura la imagen noStroke(); smooth(); set(0, 0, opencv.image()); if (mousePressed) { //image( opencv.image(), 0, 0 ); loadPixels(); for (int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++){ int loc = i + (j * width) ; //Luminace = 0.299 * Red + 0.587 * Green + 0.114 * Blue int r = PApplet.parseInt((red(pixels[loc])*0.3f + green(pixels[loc])* 0.6f + blue(pixels[loc])* 0.1f)/255 * 16); space[i][j] = r; fill(mycolours[r]); triangleCenter(i+50,j+2); } } } for(int i = 1; i < rows -1; i++){ for(int j = 1 ; j < cols - 1; j++){ spaceCopy[i][j] = greenberg(i,j); fill(mycolours[spaceCopy[i][j]]); triangleCenter(i+50,j+2); } } for(int i = 0 ; i< rows; i++){ for(int j = 0 ; j< cols; j++){ space[i][j] = spaceCopy[i][j]; } } } public void triangleCenter(float i, float j){ // funcion que construye un triangulo en posicion i,j boolean p = i % 2 == 0; boolean q = j % 2 == 0; float dx = i * x; float dy = j * (h+y); // operacion XOR if((p && q) || !(p || q)){ triangle(dx + x, dy+y, dx-x, dy+y, dx, dy-h); } else { triangle(dx - x, dy-2*y, dx+x, dy-2*y, dx, dy+h-y); } } public int greenberg(int i, int j){ // AC de greenberg y hastings int res; if(space[i][j] == 0){ int total = space[i-1][j] + space[i][j-1] + space[i+1][j] + space[i][j+1]; if(total > 1){ res = 1; } else{ res = 0; }; } else { res = (space[i][j] + 1) % 17; }; return res; } static public void main(String[] passedArgs) { String[] appletArgs = new String[] { "--full-screen", "--bgcolor=#666666", "--stop-color=#cccccc", "WebCam_Automata" }; if (passedArgs != null) { PApplet.main(concat(appletArgs, passedArgs)); } else { PApplet.main(appletArgs); } } }
package org.maven.ide.eclipse.authentication; import java.io.File; import java.net.URI; import java.util.HashMap; import java.util.Map; import javax.crypto.spec.PBEKeySpec; import junit.framework.TestCase; import org.eclipse.equinox.security.storage.ISecurePreferences; import org.eclipse.equinox.security.storage.SecurePreferencesFactory; import org.eclipse.equinox.security.storage.provider.IProviderHints; import org.maven.ide.eclipse.authentication.internal.AuthData; import org.maven.ide.eclipse.authentication.internal.SimpleAuthService; public class SimpleAuthServiceTest extends TestCase { // private static final IProgressMonitor monitor = new NullProgressMonitor(); public void testSelectShortUrl() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); assertNull( service.select( "a" ) ); assertNull( service.select( "aa" ) ); assertNull( service.select( "aaa" ) ); } public void testNullUrl() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); String sUri = null; service.save( sUri, "username", "password" ); assertNull( service.select( sUri ) ); } public void testEmptyUrl() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); String sUri = " "; service.save( sUri, "username", "password" ); assertNull( service.select( sUri ) ); URI uri = new URI( "" ); assertNull( service.select( uri ) ); } private ISecurePreferences newSecureStorage() throws Exception { File storageFile = File.createTempFile( "s2authtest", ".properties" ); storageFile.deleteOnExit(); Map<String, Object> secOpts = new HashMap<String, Object>(); secOpts.put( IProviderHints.PROMPT_USER, Boolean.FALSE ); secOpts.put( IProviderHints.DEFAULT_PASSWORD, new PBEKeySpec( new char[] { 't', 'e', 's', 't' } ) ); return SecurePreferencesFactory.open( storageFile.toURI().toURL(), secOpts ); } public void testSaveAndSelectUsernamePassword() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); String url = "http://testSaveAndSelectUsernamePassword"; assertNull( service.select( url ) ); service.save( url, "username", "password" ); IAuthData authData = service.select( url ); assertNotNull( authData ); assertEquals( AuthenticationType.USERNAME_PASSWORD, authData.getAuthenticationType() ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); assertEquals( AnonymousAccessType.NOT_ALLOWED, authData.getAnonymousAccessType() ); } public void testSaveAndSelectUsernamePasswordAnonymousAllowed() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); String url = "http://testSaveAndSelectUsernamePasswordAnonymousAllowed"; assertNull( service.select( url ) ); service.save( url, new AuthData( "username", "password", AnonymousAccessType.ALLOWED ) ); IAuthData authData = service.select( url ); assertNotNull( authData ); assertEquals( AuthenticationType.USERNAME_PASSWORD, authData.getAuthenticationType() ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); assertEquals( AnonymousAccessType.ALLOWED, authData.getAnonymousAccessType() ); } public void testSaveAndSelectCertificate() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); String url = "http://testSaveAndSelectCertificate"; assertNull( service.select( url ) ); service.save( url, new File( "foocertificate" ), "passphrase" ); IAuthData authData = service.select( url ); assertNotNull( authData ); assertEquals( AuthenticationType.CERTIFICATE, authData.getAuthenticationType() ); assertEquals( new File( "foocertificate" ).getAbsolutePath(), authData.getCertificatePath().getAbsolutePath() ); assertEquals( "passphrase", authData.getCertificatePassphrase() ); } public void testSaveAndSelectUsernamePasswordAndCertificate() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); String url = "http://testSaveAndSelectUsernamePasswordAndCertificate"; assertNull( service.select( url ) ); IAuthData authData = new AuthData( "username", "password", new File( "foocertificate" ), "passphrase", AnonymousAccessType.NOT_ALLOWED ); service.save( url, authData ); authData = service.select( url ); assertNotNull( authData ); assertEquals( AuthenticationType.CERTIFICATE_AND_USERNAME_PASSWORD, authData.getAuthenticationType() ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); assertEquals( new File( "foocertificate" ).getAbsolutePath(), authData.getCertificatePath().getAbsolutePath() ); assertEquals( "passphrase", authData.getCertificatePassphrase() ); } public void testSaveAndSelectNoEndSlash() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); service.save( "http://foo/bar", "username", "password" ); IAuthData authData = service.select( "http://foo/bar" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/bar" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/bar/" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); // Get a new SimpleAuthService for the same secure storage service = new SimpleAuthService( secureStorage ); authData = service.select( "http://foo/bar" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/bar" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/bar/" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); } public void testSaveAndSelectWithEndSlash() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); service.save( "http://foo/bar/", "username", "password" ); IAuthData authData = service.select( "http://foo/bar" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/bar" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/bar/" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); // Get a new SimpleAuthService for the same secure storage service = new SimpleAuthService( secureStorage ); authData = service.select( "http://foo/bar" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/bar" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); authData = service.select( "http://foo/bar/bar/" ); assertNotNull( authData ); assertEquals( "username", authData.getUsername() ); assertEquals( "password", authData.getPassword() ); } public void testWindowsStyleFileUrl() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); String url = "file:/c:\\foo"; service.save( url, "username", "password" ); assertNotNull( service.select( url ) ); } public void testScmUrl() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); String url = "scm:git:ssh://localhost:4807/foo"; service.save( url, "username", "password" ); assertNotNull( service.select( url ) ); } public void testInvalidScmUrl() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); String url = "scm:ssh://localhost:4807/foo"; try { service.save( url, "username", "password" ); fail( "Expected InvalidURIException" ); } catch ( InvalidURIException expected ) { if ( !"SCM URI 'scm:ssh://localhost:4807/foo' does not specify SCM type".equals( expected.getMessage() ) ) { throw expected; } } assertNull( service.select( url ) ); } public void testSaveAuthDataOnlyWhenChanged_UsernamePassword() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); String url = "http://SimpleAuthServiceTest/testSaveAuthDataOnlyWhenChanged_UsernamePassword/"; String username = "username"; String password = "password"; AnonymousAccessType anonymousAccessType = AnonymousAccessType.NOT_ALLOWED; IAuthData authData = new AuthData( username, password, anonymousAccessType ); assertTrue( service.save( url, authData ) ); authData = service.select( url ); authData = new AuthData( username, password, anonymousAccessType ); assertFalse( service.save( url, authData ) ); username += "x"; authData = new AuthData( username, password, anonymousAccessType ); assertTrue( service.save( url, authData ) ); password += "x"; authData = new AuthData( username, password, anonymousAccessType ); assertTrue( service.save( url, authData ) ); } public void testSaveAuthDataOnlyWhenChanged_Certificate() throws Exception { ISecurePreferences secureStorage = newSecureStorage(); SimpleAuthService service = new SimpleAuthService( secureStorage ); String url = "http://SimpleAuthServiceTest/testSaveAuthDataOnlyWhenChanged_Certificate/"; File certificate = new File( "foo" ); String passphrase = "passphrase"; IAuthData authData = new AuthData( certificate, passphrase ); assertTrue( service.save( url, authData ) ); authData = service.select( url ); authData = new AuthData( certificate, passphrase ); assertFalse( service.save( url, authData ) ); certificate = new File( "foox" ); authData = new AuthData( certificate, passphrase ); assertTrue( service.save( url, authData ) ); passphrase += "x"; authData = new AuthData( certificate, passphrase ); assertTrue( service.save( url, authData ) ); } }
/* * 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 edu.prueba.co; /** * * @author ESTUDIANTE */ public interface Calcular { double lg=1000; public String conversionLibra(); }
package com.example.androidtest; import android.app.Activity; import android.os.Bundle; /** * Created by linyun on 14-5-5. */ public class UrlSchemeActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
package inheritance; public class circle implements drawable { @Override public void open() { // TODO Auto-generated method stub System.out.println("circle open "); } @Override public void draw() { // TODO Auto-generated method stub System.out.println("circle draw"); } @Override public void close() { // TODO Auto-generated method stub System.out.println("circle close"); } }
import edu.duke.*; /** * Write a description of CommonWords here. * * @author (your name) * @version (a version number or a date) */ public class CommonWords { public String[] getCommon(){ FileResource fr = new FileResource("data/common.txt"); String[] common = new String[20]; int index = 0; for(String word : fr.words()){ common[index] = word; index++; } return common; } public int indexOf(String[] list, String word) { int index = 0; for(String common : list){ if(common.equals(word)){ return index; } index++; } return -1; } public void countWords(FileResource resource, String[] common, int[] counts){ for(String word : resource.words()){ int index = indexOf(common,word); if(index!=-1){ counts[index]++; } } } void countShakespeare(){ String[] listFile = {"caesar.txt","common.txt","errors.txt", "hamlet.txt","likeit.txt","macbeth.txt","romeo.txt"}; String[] common = getCommon(); int[] counts = new int[common.length]; //String[] listFile = {"small.txt"}; for(int k = 0; k < listFile.length; k++){ FileResource resource = new FileResource("data/" + listFile[k]); countWords(resource,common,counts); System.out.println("done with " + listFile[k]); } for(int k = 0; k < counts.length; k++){ System.out.println(common[k] + "\t" + counts[k]); } } }
package com.tb.bughub.order.demo.model; import com.tb.bughub.order.demo.model.MenuItem; import javax.persistence.*; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import java.util.UUID; @Entity @Table(name="ORDER_DEL") public class Order { @Id @Column(name="order_id") private UUID orderId ; @Column(name="user_id") private String userId; @Column(name="restuarant_id") private String restuarantId; @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER , mappedBy = "order") private Set<MenuItem> menuItems = new HashSet<MenuItem>(); @Column(name="order_date", nullable=false, length=200) private Date orderDate; @Column(name="total_price", nullable=false, length=200) private String totalPrice; @Column(name="order_time", nullable=false, length=200) private Timestamp orderTime; @Column(name="ex_delivery_time", nullable=false, length=200) private Timestamp exprectedDeliveryTime; public UUID getOrderId() { return orderId; } public void setOrderId(UUID orderId) { this.orderId = orderId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getRestuarantId() { return restuarantId; } public void setRestuarantId(String restuarantId) { this.restuarantId = restuarantId; } public Set<MenuItem> getMenuItems() { return menuItems; } public void setMenuItems(Set<MenuItem> menuItems) { this.menuItems = menuItems; } public Date getOrderDate() { return orderDate; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } public String getTotalPrice() { return totalPrice; } public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; } public Timestamp getOrderTime() { return orderTime; } public void setOrderTime(Timestamp orderTime) { this.orderTime = orderTime; } public Timestamp getExprectedDeliveryTime() { return exprectedDeliveryTime; } public void setExprectedDeliveryTime(Timestamp exprectedDeliveryTime) { this.exprectedDeliveryTime = exprectedDeliveryTime; } }
package com.bingo.code.example.design.builder.prototype.clonedifferent; /** * �����Ľӿڣ������˿��Կ�¡����ķ��� */ public interface OrderApi { /** * ��ȡ������Ʒ���� * @return �����в�Ʒ���� */ public int getOrderProductNum(); /** * ���ö�����Ʒ���� * @param num ������Ʒ���� */ public void setOrderProductNum(int num); /** * ��¡���� * @return ����ԭ�͵�ʵ�� */ public OrderApi cloneOrder(); }
package io.makeabilitylab.facetrackerble.ble; /** Listens to events related to the device. */ public interface BLEListener { /** Invoked when the device is connected. */ void onBleConnected(); /** Invoked when a connection attempt to the device is not successful. */ void onBleConnectFailed(); /** Invoked when the device is disconnected. */ void onBleDisconnected(); /** Invoked when data is received from the device. */ void onBleDataReceived(byte[] data); /** Invoked when the RSSI for the connected device changes. */ void onBleRssiChanged(int rssi); }
package br.com.smarthouse.controleclimatico.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Table; import br.com.smarthouse.modelgenerics.Ambiente; /** * Entity que modela a Temperatura do Ambiente. * * @author Rafael Casabona * */ @Entity @Table(name = "TEMPERATURA_AMBIENTE") public class TemperaturaAmbiente implements Serializable { /** * */ private static final long serialVersionUID = -4439016722895050607L; @Id @Column(name = "ID_TEMPERATURA_AMBIENTE") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @JoinColumn(name = "ID_AMBIENTE") private Ambiente ambiente; @Column(name = "ID_USUARIO") private Long identificadorUsuario; private Date dataUltimaMedicao; private Double temperatura; @Enumerated(EnumType.ORDINAL) private TipoTemperatura tipoTemperatura; @Enumerated(EnumType.ORDINAL) private QualidadeDoAr qualidadeDoAr; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Ambiente getAmbiente() { return ambiente; } public void setAmbiente(Ambiente ambiente) { this.ambiente = ambiente; } public Long getIdentificadorUsuario() { return identificadorUsuario; } public void setIdentificadorUsuario(Long identificadorUsuario) { this.identificadorUsuario = identificadorUsuario; } public Date getDataUltimaMedicao() { return dataUltimaMedicao; } public void setDataUltimaMedicao(Date dataUltimaMedicao) { this.dataUltimaMedicao = dataUltimaMedicao; } public Double getTemperatura() { return temperatura; } public void setTemperatura(Double temperatura) { this.temperatura = temperatura; } public TipoTemperatura getTipoTemperatura() { return tipoTemperatura; } public void setTipoTemperatura(TipoTemperatura tipoTemperatura) { this.tipoTemperatura = tipoTemperatura; } public QualidadeDoAr getQualidadeDoAr() { return qualidadeDoAr; } public void setQualidadeDoAr(QualidadeDoAr qualidadeDoAr) { this.qualidadeDoAr = qualidadeDoAr; } }
package me.the_red_freak.bptf.commands; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class reset_cmd implements CommandExecutor{ // Utils u = Utils. @SuppressWarnings("deprecation") public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(!(sender instanceof Player)){ System.out.println("Only a player can do this!"); return true; } Player p = (Player) sender; final int rand = new Random().nextInt(15); p.sendMessage("Random int: " + rand); for (Block b : getAllBlocks(new Location(p.getWorld(), -7, 64, 33), new Location(p.getWorld(), -37, 64, 3), p.getWorld())) { if(b.getData() != (byte) rand){ b.setType(Material.AIR); } } return false; } public List<Block> getAllBlocks(Location Pos1, Location Pos2, World w) { List<Block> blocks = new ArrayList<Block>(); int minx = Math.min(Pos1.getBlockX(), Pos2.getBlockX()), miny = Math.min(Pos1.getBlockY(), Pos2.getBlockY()), minz = Math.min(Pos1.getBlockZ(), Pos2.getBlockZ()), maxx = Math.max(Pos1.getBlockX(), Pos2.getBlockX()), maxy = Math.max(Pos1.getBlockY(), Pos2.getBlockY()), maxz = Math.max(Pos1.getBlockZ(), Pos2.getBlockZ()); for (int x = minx; x<=maxx;x++) { for (int y = miny; y<=maxy;y++) { for (int z = minz; z<=maxz;z++) { blocks.add(w.getBlockAt(x, y, z)); } } } return blocks; } }
package com.tencent.mm.plugin.luckymoney.appbrand.a; import com.tencent.mm.protocal.c.ayj; import com.tencent.mm.protocal.c.ayk; import com.tencent.mm.protocal.c.bhp; import com.tencent.mm.sdk.platformtools.x; public final class b extends a<ayj, ayk> { protected final /* synthetic */ bhp bax() { return new ayk(); } public b(String str, String str2, byte[] bArr) { ayj ayj = new ayj(); ayj.bPS = str; ayj.sbb = str2; ayj.sbc = com.tencent.mm.bk.b.bi(bArr); this.kKM = ayj; } protected final void bay() { x.i("MicroMsg.CgiOpenWxaHB", "CgiOpenWxaHB.onCgiStart "); } protected final void baz() { x.i("MicroMsg.CgiOpenWxaHB", "CgiOpenWxaHB.onCgiEnd "); } public final String getUri() { return "/cgi-bin/mmbiz-bin/wxahb/openwxaapphb"; } public final int If() { return 2701; } }
package checkout.desktop.step_definitions; import base.BaseSteps; import cucumber.api.java.en.And; import cucumber.api.java.en.Then; import checkout.desktop.pages.Cart_Page; import org.testng.Assert; public class CartSteps extends BaseSteps { @And("^I move the product to wishlist$") public void moveToWishlist(){ on(Cart_Page.class).clickWishlistIcon(); on(Cart_Page.class).confirmMoveOrRemove(); } @Then("^I should see successful message and the product is not in Cart$") public void checkMoveToWishlistSuccessful(){ Assert.assertTrue(on(Cart_Page.class).checkMoveToWishlistSuccessMessage(), "Verification failed: No success message displays"); Assert.assertFalse(on(Cart_Page.class).checkProductExistInTheCart(), "Verification failed: Product still be on cart"); } @And("^I delete the product$") public void deleteProduct(){ on(Cart_Page.class).clickDeleteIcon(); on(Cart_Page.class).confirmMoveOrRemove(); } @Then("^I should not see the product in Cart$") public void checkProductNotExistInCart(){ Assert.assertFalse(on(Cart_Page.class).checkProductExistInTheCart(), "Verification failed: Cart is not empty"); } @And("^I click Confirm Cart$") public void clickConfirmCart(){ on(Cart_Page.class).clickConfirmCart(); } }
package systemA; import InstrumentationPackage.*; import MessagePackage.*; import Configuration.*; class SecurityController { public static void main(String args[]) { String MsgMgrIP; // Message Manager IP address Message Msg = null; // Message object MessageQueue eq = null; // Message Queue MessageManagerInterface em = null; // Interface object to the message manager boolean isArmed = false; // Heater state: false == off, true == on int Delay = 2500; // The loop delay (2.5 seconds) boolean Done = false; // Loop termination flag ///////////////////////////////////////////////////////////////////////////////// // Get the IP address of the message manager ///////////////////////////////////////////////////////////////////////////////// if ( args.length == 0 ) { // message manager is on the local system System.out.println("\n\nAttempting to register on the local machine..." ); try { // Here we create an message manager interface object. This assumes // that the message manager is on the local machine em = new MessageManagerInterface(); } catch (Exception e) { System.out.println("Error instantiating message manager interface: " + e); } // catch } else { // message manager is not on the local system MsgMgrIP = args[0]; System.out.println("\n\nAttempting to register on the machine:: " + MsgMgrIP ); try { // Here we create an message manager interface object. This assumes // that the message manager is NOT on the local machine em = new MessageManagerInterface( MsgMgrIP ); } catch (Exception e) { System.out.println("Error instantiating message manager interface: " + e); } // catch } // if // Here we check to see if registration worked. If em is null then the // message manager interface was not properly created. if (em != null) { System.out.println("Registered with the message manager." ); /* Now we create the humidity control status and message panel ** We put this panel about 2/3s the way down the terminal, aligned to the left ** of the terminal. The status indicators are placed directly under this panel */ float WinPosX = 0.0f; //This is the X position of the message window in terms //of a percentage of the screen height float WinPosY = 0.60f; //This is the Y position of the message window in terms //of a percentage of the screen height MessageWindow mw = new MessageWindow("Security Controller Status Console", WinPosX, WinPosY); Indicator armedIndicator= new Indicator ("Disarmed", mw.GetX(), mw.GetY()+mw.Height()); mw.WriteMessage("Registered with the message manager." ); try { mw.WriteMessage(" Participant id: " + em.GetMyId() ); mw.WriteMessage(" Registration Time: " + em.GetRegistrationTime() ); } // try catch (Exception e) { System.out.println("Error:: " + e); } // catch /******************************************************************** ** Here we start the main simulation loop *********************************************************************/ while ( !Done ) { try { eq = em.GetMessageQueue(); } // try catch( Exception e ) { mw.WriteMessage("Error getting message queue::" + e ); } // catch int qlen = eq.GetSize(); for ( int i = 0; i < qlen; i++ ) { Msg = eq.GetMessage(); if(Msg.GetMessageId() == Configuration.SECURITY_MONITOR_ID){ if (Msg.GetMessage().equalsIgnoreCase("ARM")){ isArmed = true; mw.WriteMessage("Received security controller ON message" ); }else if (Msg.GetMessage().equalsIgnoreCase("DISARM")){ isArmed = false; mw.WriteMessage("Received security controller OFF message" ); } } else if(Msg.GetMessageId() == Configuration.DOOR_SENSOR_ID){ if(isArmed) postMessage(em, "Door"); mw.WriteMessage("Received Door Alarm" ); } else if(Msg.GetMessageId() == Configuration.WINDOW_SENSOR_ID){ if(isArmed) postMessage(em, "Window"); mw.WriteMessage("Received Window Alarm" ); } else if(Msg.GetMessageId() == Configuration.MOTION_SENSOR_ID){ if(isArmed) postMessage(em, "Motion"); mw.WriteMessage("Received Motion Alarm" ); } else if(Msg.GetMessageId() == 99){ Done = true; mw.WriteMessage("Received End Message" ); try{ em.UnRegister(); }catch (Exception e){ mw.WriteMessage("Error unregistering: " + e); } // catch mw.WriteMessage( "\n\nSimulation Stopped. \n"); armedIndicator.dispose(); } } // for // Update the lamp status if (isArmed){ armedIndicator.SetLampColorAndMessage("SECURITY ON", 1); } else { armedIndicator.SetLampColorAndMessage("SECURITY OFF", 0); } // if try { Thread.sleep( Delay ); } // try catch( Exception e ) { System.out.println( "Sleep error:: " + e ); } // catch } // while } else { System.out.println("Unable to register with the message manager.\n\n" ); } // if } // main static private void postMessage(MessageManagerInterface ei, String m ){ // Here we create the message. Message msg = new Message( Configuration.SECURITY_CONTROLLER_ID, m ); // Here we send the message to the message manager. try{ ei.SendMessage( msg ); } // try catch (Exception e){ System.out.println("Error posting Message:: " + e); } // catch } // PostMessage }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final /** * TDwesd generated by hbm2java */ public class TDwesd implements java.io.Serializable { private TDwesdId id; public TDwesd() { } public TDwesd(TDwesdId id) { this.id = id; } public TDwesdId getId() { return this.id; } public void setId(TDwesdId id) { this.id = id; } }
package com.ajonx.game; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import javax.imageio.ImageIO; import com.ajonx.game.gfx.Sprite; import com.ajonx.game.gfx.SpriteSheet; /* * This class will take a map sprite, convert it into a tile sheet and then generate the * to recreate the file back in the game */ public class MapSpriteToTileMap { public static Scanner scanner = new Scanner(System.in); public static List<int[]> tiles = new ArrayList<>(); public static List<Integer> map = new ArrayList<>(); public static void main(String[] args) throws IOException { System.out.println("Enter the map to breakdown:"); String name = scanner.next(); BufferedImage img = ImageIO.read(new File("res/" + name + ".png")); SpriteSheet sheet = new SpriteSheet(name, 16, 16); int w = img.getWidth(), h = img.getHeight(); int tilex = w / 16; int tiley = h / 16; int[] blank = new int[16 * 16]; tiles.add(blank); // Loops through each tile and if it has not been seen before, add it to the tile sheet // Also adds the index of each tile to the map file in order to recreate it loop: for (int i = 0; i < tilex * tiley; i++) { int[] pixels = sheet.getSprite(i).getPixels(); for (int j = 0; j < tiles.size(); j++) { int[] p = tiles.get(j); if (Arrays.equals(pixels, p)) { map.add(j); continue loop; } } map.add(tiles.size()); tiles.add(pixels); } // Generate the tile sheet from the saved pixel data Sprite tilemap = new Sprite(null, tiles.size() * 16, 16); for (int i = 0; i < tiles.size(); i++) { int[] t = tiles.get(i); for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { tilemap.setPixel(x + i * 16, y, t[x + y * 16]); } } } tilemap.save("/maps/" + name + "/tiles"); System.out.println("What is the name of the map to save:"); String mapname = scanner.nextLine(); List<String> data = new ArrayList<>(); data.add(mapname); data.add(tilex + "," + tiley); int index = 0; for (int i = 0; i < tiley; i++) { String line = ""; for (int j = 0; j < tilex; j++) { if (j > 0) line += ","; String value = Integer.toString(map.get(index++)); if (value.length() == 1) value = "0" + value; line += value; } data.add(line); } Util.writeTextFile("maps/" + name + "/map.map", data); System.out.println("Generated SpriteSheet to res/" + name + "_tiles.png"); } }
package com.jkxy.web.service.impl; import java.util.List; import java.util.Set; import com.jkxy.web.dao.ConsumeDao; import com.jkxy.web.model.Consume; import com.jkxy.web.service.ConsumeService; public class ConsumeServiceImpl implements ConsumeService{ private ConsumeDao consumeDao; public void setConsumeDao(ConsumeDao consumeDao) { this.consumeDao = consumeDao; } @Override public List<Consume> getConsumeAll() { List<Consume> consumes = consumeDao.getConsumeAll(); return consumes; } public void setConsumerecordDao(ConsumeDao consumeDao) { this.consumeDao = consumeDao; } public ConsumeDao getConsumeDao() { return consumeDao; } @Override public List<Consume> getConsumeById(Integer vipId) { List<Consume> consumes = consumeDao.getConsumeById(vipId); return consumes; } }
import java.util.ArrayList; public class TeXConverter implements TextConverter { private ArrayList<TeXText> teXTexts = new ArrayList<>(); @Override public void getConvertedTextFormat() { for (TeXText teXText : teXTexts) { System.out.printf("%s", teXText.getContent()); } System.out.printf("\n"); } @Override public void convertC() { teXTexts.add(new TeXText("c")); } @Override public void convertF() { teXTexts.add(new TeXText("_")); } @Override public void convertP() { teXTexts.add(new TeXText("|")); } }
package pt.ist.sonet.exception; public class PublicationAccessDeniedException extends SonetException { private static final long serialVersionUID = 1L; private int publicationId; public PublicationAccessDeniedException(){} public PublicationAccessDeniedException(int pubId) { this.publicationId = pubId; } public int getpublicationId() { return this.publicationId; } @Override public String toString(){ return ("ERROR: Permission denied accessing publication #" + this.publicationId); } }
package negotiator.boaframework.offeringstrategy.anac2011.valuemodelagent; public class RealValuedecreaseProxy extends ValueDecrease { private double portion; private ValueDecrease worstScale; RealValuedecreaseProxy(ValueDecrease worstScale,double portion) { super(0, 0, 0); this.portion =portion; this.worstScale=worstScale; } @Override public double getDecrease(){ return worstScale.getDecrease()*portion; } public double getReliabilty(){ return worstScale.getReliabilty(); } public double getDeviance(){ return worstScale.getDeviance()*portion; } public int lastSent(){ return worstScale.lastSent(); } public void sent(int bidIndex){ worstScale.sent(bidIndex); } public void updateWithNewValue(double newVal,double newReliability){ //if portion is 0, than this is the best case scenario... //unless I add a way to turn the linear direction of the issue //there is nothing we can learn from newVal, and any other value //but 0 is considered a mistake if(portion>0){ worstScale.updateWithNewValue(newVal/portion, newReliability); } } }
package java8.stream; import org.junit.Test; import java.util.Arrays; import static java.lang.System.out; import static org.junit.Assert.*; /** * Author: fangxueshun * Description: * Date: 2017/10/26 * Time: 23:53 */ public class ParallelStreamOptionsTest { @Test public void outofOrder() throws Exception { ParallelStreamOptions.outofOrder(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9)).forEach(out::println); } }
package engine; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import javax.sound.midi.*; public class PlayMidiAudio { public static void main(String[] args) throws Exception { // Obtains the default Sequencer connected to a default device. Sequencer cMajor = MidiSystem.getSequencer(); // Opens the device, indicating that it should now acquire any // system resources it requires and become operational. cMajor.open(); // create a stream from a file InputStream is = new BufferedInputStream(new FileInputStream(new File("music" + File.separator + "scale_chords_small" + File.separator + "midi" + File.separator + "scale_c_major.mid"))); // Sets the current sequence on which the sequencer operates. // The stream must point to MIDI file data. // Starts playback of the MIDI data in the currently loaded sequence. // sequencer.setTempoInBPM(); long oneQuarterNote = 960; cMajor.setSequence(is); cMajor.setTickPosition(0); cMajor.setLoopStartPoint(0); cMajor.setLoopEndPoint(oneQuarterNote*5); cMajor.setLoopCount(Sequencer.LOOP_CONTINUOUSLY); InputStream eMajorStream = new BufferedInputStream(new FileInputStream(new File("music" + File.separator + "scale_chords_small" + File.separator + "midi" + File.separator + "scale_e_major.mid"))); Sequencer eMajor = MidiSystem.getSequencer(); //eMajor.open(); eMajor.setSequence(eMajorStream); eMajor.setLoopStartPoint(0); eMajor.setLoopEndPoint(oneQuarterNote*5); eMajor.setLoopCount(Sequencer.LOOP_CONTINUOUSLY); InputStream gMajorStream = new BufferedInputStream(new FileInputStream(new File("music" + File.separator + "scale_chords_small" + File.separator + "midi" + File.separator + "scale_g_major.mid"))); Sequencer gMajor = MidiSystem.getSequencer(); gMajor.open(); gMajor.setSequence(gMajorStream); gMajor.setLoopStartPoint(0); gMajor.setLoopEndPoint(oneQuarterNote*5); gMajor.setLoopCount(Sequencer.LOOP_CONTINUOUSLY); System.out.println("Started Sequencer"); Sequencer first = eMajor; Sequencer second = cMajor; Sequencer third = gMajor; System.out.println(first.getTempoFactor()); System.out.println(first.getTempoInBPM()); System.out.println(first.getTempoInMPQ()); first.open(); first.start(); int loops = 0; long prevPos = 0; while(loops < 3){ long curPosition = first.getTickPosition(); if(prevPos > curPosition) { loops++; prevPos = curPosition; System.out.println(loops); if(true) if(loops == 1){ second.start(); } else if (loops == 2){ third.start(); } } else { prevPos = curPosition; } } //continue playing to the end of the file first.setLoopCount(0); second.setLoopCount(0); third.setLoopCount(0); first.setTickPosition(first.getLoopEndPoint()); second.setTickPosition(second.getLoopEndPoint()); third.setTickPosition(third.getLoopEndPoint()); while(first.getTickPosition() < oneQuarterNote * 8){ //while less than 8 eight notes played, continue playing } //stop playback //can change to stop System.out.println("Stopping the midi"); // cMajor.close(); // eMajor.close(); // gMajor.close(); cMajor.stop(); eMajor.stop(); gMajor.stop(); } }
package test_strutturali; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.Calendar; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import sistema.*; public class SalaTest { Sala s; static Calendar date; static Spettacolo spettacolo; static Film mockedFilm; @BeforeClass public static void setUpBeforeClass() throws Exception { date = Calendar.getInstance(); date.set(2018, 6, 1, 10, 00); date.add(Calendar.DAY_OF_MONTH, 5); mockedFilm = mock(Film.class); when(mockedFilm.getDurata()).thenReturn(50); spettacolo = new Spettacolo(mockedFilm, date, 10.0f); } @Before public void setUp() throws Exception { Cinema mockedCinema = mock(Cinema.class); when(mockedCinema.getId()).thenReturn(1); s = new Sala("Sala A", 10, 10, 10, mockedCinema); } @Test public void testConstructor() { assertNotNull(s); assertEquals("Sala A", s.getNome()); assertEquals(10*10, s.getCapacity()); assertEquals(10, s.getTempoAttrezzaggio()); assertEquals(1, s.getCinemaId()); } @Test public void testSetAndGetId() { s.setId(5); assertEquals(5, s.getId()); } @Test public void testAddShowAndVerifyAvailability() { s.setId(5); assertTrue(s.verifyAvailability(spettacolo, 2)); assertFalse(s.addShow(spettacolo, 2)); spettacolo.setSala(s); // Add a show at 10.00 assertTrue(s.addShow(spettacolo, 2)); Calendar newDate = (Calendar) date.clone(); newDate.set(Calendar.HOUR_OF_DAY, 12); Spettacolo newSpettacolo = new Spettacolo(mockedFilm, newDate, 10.0f); assertTrue(s.verifyAvailability(newSpettacolo, 2)); newSpettacolo.setSala(s); // Add a show at 12.00 assertTrue(s.addShow(newSpettacolo, 2)); // Try to add a show at 12.00 // It returns false because there is already a show at the same hour and minutes assertFalse(s.addShow(newSpettacolo, 2)); newDate.add(Calendar.MINUTE, 30); newSpettacolo = new Spettacolo(mockedFilm, newDate, 10.0f); newSpettacolo.setSala(s); // Try to add a show at 12.30 (the duration of the show is 60 min) // It returns false because newSpettacolo starts when the previous show is // not already finished assertFalse(s.verifyAvailability(newSpettacolo, 2)); newDate.set(Calendar.HOUR_OF_DAY, 18); newDate.set(Calendar.MINUTE, 0); newSpettacolo = new Spettacolo(mockedFilm, newDate, 10.0f); newSpettacolo.setSala(s); // Add a show at 18.00 assertTrue(s.addShow(newSpettacolo, 2)); newDate.set(Calendar.HOUR_OF_DAY, 17); newDate.set(Calendar.MINUTE, 30); newSpettacolo = new Spettacolo(mockedFilm, newDate, 10.0f); // Try to add a show at 17.30 (the duration of the show is 60 min) // It returns false because newSpettacolo ends when the previous show is // already started assertFalse(s.verifyAvailability(newSpettacolo, 2)); newDate.set(Calendar.HOUR_OF_DAY, 12); newDate.set(Calendar.MINUTE, 30); newSpettacolo = new Spettacolo(mockedFilm, newDate, 10.0f); // Try to add a show at 12.30 (the duration of the show is 60 min) // It returns false because newSpettacolo ends when the previous show is // already started assertFalse(s.verifyAvailability(newSpettacolo, 2)); newDate.set(Calendar.HOUR_OF_DAY, 16); newDate.set(Calendar.MINUTE, 0); newSpettacolo = new Spettacolo(mockedFilm, newDate, 10.0f); newSpettacolo.setSala(s); // Add a show at 16.00 assertTrue(s.addShow(newSpettacolo, 2)); } @Test public void testPrint() { s.print(); assertFalse(s.printAllShows()); s.setId(5); Spettacolo show = new Spettacolo(mockedFilm, date, 10.0f); show.setSala(s); // Add a show at 10.00 assertTrue(s.addShow(show, 2)); assertTrue(s.printAllShows()); } }
package com.storytime.client.skill.defense; public class ProtectDefense extends WordDefense { public String submissionToProtect = ""; private String type = "BLOCK_DEFENSE"; public String getSubmissionToProtect() { return submissionToProtect; } public void setSubmissionToProtect(String submissionToProtect) { this.submissionToProtect = submissionToProtect; } @Override public String getType() { return type; } }
package com.tencent.mm.plugin.account.bind.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; class BindQQUI$4 implements OnMenuItemClickListener { final /* synthetic */ BindQQUI eHn; BindQQUI$4(BindQQUI bindQQUI) { this.eHn = bindQQUI; } public final boolean onMenuItemClick(MenuItem menuItem) { this.eHn.YC(); this.eHn.finish(); return true; } }
public class CorporateCustomer extends Customer { private int rate; public CorporateCustomer(String ID,String name,String phone,int rate) { super(ID,name,phone); this.rate = rate; } public int getrate() { return rate; } public void setrate(int rate) { this.rate = rate; } public double getDiscount(double tot_charge) //calculating the discount { double discount_made; double discount = 0.0; discount_made = tot_charge * (rate/100); discount = tot_charge - discount_made; return discount; } public void print() { System.out.println(); super.print(); System.out.println("Rate :" +this.getrate()); } }
package uk.co.kgits.sitedata; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; /** * Wx object comprises a number of Parm objects * @author OFadero * */ @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) public class Wx { private List<Param> param = new ArrayList<Param>(); @XmlElement(name = "Param", required = true) public List<Param> getParam() { return param; } public void setParam(List<Param> param) { this.param = param; } public String toString(){ StringBuilder strBuilder = new StringBuilder(); for(Param p: param){ strBuilder.append(p + " "); } return strBuilder.toString(); } }
package com.lec.ex02; public class TestMain { public static void main(String[] args) { // 추상클래스 객체 못만들어. 추상메소드때문에 . 무조건override해야하기때문에 // Super s = new Super(); 불가 Child c1 = new Child(); c1.method1(); c1.method2(); c1.method3(); // c1은child형 변수여서 가능 Super c2 = new Child(); c2.method1(); c2.method2(); // c2.method3(); 은 불가능. (c2변수가 Super타입이므로 Super의 것만 가능 /method3은child파일에서 불로언거.child extends Super이기때문) } }
package com.elkattanman.farmFxml.controllers.bars; import com.elkattanman.farmFxml.controllers.AboutController; import com.elkattanman.farmFxml.controllers.MainController; import com.elkattanman.farmFxml.controllers.borns.BornsFrameController; import com.elkattanman.farmFxml.controllers.buy.BuyFrameController; import com.elkattanman.farmFxml.controllers.death.DeathFrameController; import com.elkattanman.farmFxml.controllers.feed.FeedFrameController; import com.elkattanman.farmFxml.controllers.reserve.ReserveFrameController; import com.elkattanman.farmFxml.controllers.sale.SaleFrameController; import com.elkattanman.farmFxml.controllers.settings.CapitalController; import com.elkattanman.farmFxml.controllers.settings.SettingsController; import com.elkattanman.farmFxml.controllers.spending.SpendingFrameController; import com.elkattanman.farmFxml.controllers.treatment.TreatmentFrameController; import com.elkattanman.farmFxml.controllers.types.TypesFrameController; import com.elkattanman.farmFxml.util.AssistantUtil; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.MenuBar; import net.rgielen.fxweaver.core.FxWeaver; import net.rgielen.fxweaver.core.FxmlView; import org.springframework.stereotype.Component; import java.net.URL; import java.util.ResourceBundle; @Component @FxmlView("/FXML/bars/menuBar.fxml") public class MenuBarController implements Initializable { private final FxWeaver fxWeaver; @FXML private MenuBar menuBar; public MenuBarController(FxWeaver fxWeaver) { this.fxWeaver = fxWeaver; } @Override public void initialize(URL url, ResourceBundle resourceBundle) { } public void goToTypes() { AssistantUtil.loadWindow(AssistantUtil.getStage(menuBar), fxWeaver.loadView(TypesFrameController.class)); } public void goToBuy() { AssistantUtil.loadWindow(AssistantUtil.getStage(menuBar), fxWeaver.loadView(BuyFrameController.class)); } public void goToSale() { AssistantUtil.loadWindow(AssistantUtil.getStage(menuBar),fxWeaver.loadView(SaleFrameController.class)); } public void goToBorns() { AssistantUtil.loadWindow(AssistantUtil.getStage(menuBar),fxWeaver.loadView(BornsFrameController.class)); } public void goToDeath() { AssistantUtil.loadWindow(AssistantUtil.getStage(menuBar),fxWeaver.loadView(DeathFrameController.class)); } public void goToTreatment(ActionEvent actionEvent) { AssistantUtil.loadWindow(AssistantUtil.getStage(menuBar),fxWeaver.loadView(TreatmentFrameController.class)); } public void goToReserve(ActionEvent actionEvent) { AssistantUtil.loadWindow(AssistantUtil.getStage(menuBar),fxWeaver.loadView(ReserveFrameController.class)); } public void goToSpending(ActionEvent actionEvent) { AssistantUtil.loadWindow(AssistantUtil.getStage(menuBar),fxWeaver.loadView(SpendingFrameController.class)); } public void goToFeed(ActionEvent actionEvent) { AssistantUtil.loadWindow(AssistantUtil.getStage(menuBar),fxWeaver.loadView(FeedFrameController.class)); } public void goSettings(ActionEvent actionEvent) { AssistantUtil.loadWindow(null,fxWeaver.loadView(SettingsController.class)); } public void goHelp(ActionEvent actionEvent) { AssistantUtil.loadWindow(null,fxWeaver.loadView(AboutController.class)); } public void goToHome(ActionEvent actionEvent) { AssistantUtil.loadWindow(AssistantUtil.getStage(menuBar),fxWeaver.loadView(MainController.class)); } public void goCapital(ActionEvent actionEvent) { AssistantUtil.loadWindow(null,fxWeaver.loadView(CapitalController.class)); } }
package com.tencent.mm.ui.chatting.viewitems; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.tencent.mm.ak.e; import com.tencent.mm.ak.f; import com.tencent.mm.ak.o; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.model.q; import com.tencent.mm.modelstat.a$a; import com.tencent.mm.modelstat.b; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.bl; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import com.tencent.mm.storage.bd; import com.tencent.mm.ui.base.s; import com.tencent.mm.ui.chatting.b.b.w; import com.tencent.mm.ui.chatting.c.a; import com.tencent.mm.ui.chatting.gallery.ImageGalleryUI; import com.tencent.mm.ui.chatting.t.d; import com.tencent.mm.y.g; import java.util.Map; public class z$c extends d { private b udl; public z$c(a aVar, b bVar) { super(aVar); this.udl = bVar; } public final void a(View view, a aVar, bd bdVar) { e eVar; Map z; g.a go; au auVar = (au) view.getTag(); b.ehL.z(auVar.bXQ); bd bdVar2 = auVar.bXQ; com.tencent.mm.modelstat.a.a(bdVar2, a$a.Click); int[] iArr = new int[2]; int i = 0; int i2 = 0; if (view != null) { view.getLocationInWindow(iArr); i = view.getWidth(); i2 = view.getHeight(); } if (bdVar2.field_isSend == 1) { e br = o.Pf().br(bdVar2.field_msgId); if (br.dTK != 0) { eVar = br; z = bl.z(bdVar2.field_content, "msg"); if (z != null) { bi.getLong((String) z.get(".msg.img.$hdlength"), 0); } au.HU(); if (!c.isSDCardAvailable()) { s.gH(this.tKy.tTq.getContext()); } else if (bdVar2.field_isSend == 1) { if (com.tencent.mm.a.e.cn(o.Pf().o(f.c(eVar), "", ""))) { a(this.tKy, bdVar2, eVar.dTS, eVar.bYu, auVar.userName, auVar.chatroomName, iArr, i, i2, false); } else { if (com.tencent.mm.a.e.cn(o.Pf().o(eVar.dTL, "", ""))) { a(this.tKy, bdVar2, eVar.dTS, eVar.bYu, auVar.userName, auVar.chatroomName, iArr, i, i2, false); } else { a(bdVar2.field_msgId, bdVar2.field_msgSvrId, auVar.userName, auVar.chatroomName, iArr, i, i2); } } } else if (eVar.OM()) { String str; a aVar2; String str2 = eVar.dTL; if (eVar.ON()) { e a = f.a(eVar); if (a != null && a.dTK > 0 && a.OM() && com.tencent.mm.a.e.cn(o.Pf().o(a.dTL, "", ""))) { str = a.dTL; aVar2 = this.tKy; o.Pf().o(str, "", ""); a(aVar2, bdVar2, eVar.dTS, eVar.bYu, auVar.userName, auVar.chatroomName, iArr, i, i2, false); } } str = str2; aVar2 = this.tKy; o.Pf().o(str, "", ""); a(aVar2, bdVar2, eVar.dTS, eVar.bYu, auVar.userName, auVar.chatroomName, iArr, i, i2, false); } else { if (eVar.status == -1) { x.i("MicroMsg.DesignerClickListener", "retry downloadImg, %d", new Object[]{Long.valueOf(eVar.dTK)}); eVar.setStatus(0); eVar.bWA = 256; o.Pf().a(Long.valueOf(eVar.dTK), eVar); } a(bdVar2.field_msgId, bdVar2.field_msgSvrId, auVar.userName, auVar.chatroomName, iArr, i, i2); } go = g.a.go(bdVar.field_content); if (go != null && !bi.oW(go.appId) && this.udl != null) { com.tencent.mm.pluginsdk.model.app.f bl = com.tencent.mm.pluginsdk.model.app.g.bl(go.appId, false); if (bl != null && bl.aaq()) { b.a(aVar, go, this.udl instanceof z.a ? b.d(aVar, bdVar) : q.GF(), bl, bdVar.field_msgSvrId); return; } return; } return; } } eVar = o.Pf().bq(bdVar2.field_msgSvrId); z = bl.z(bdVar2.field_content, "msg"); if (z != null) { bi.getLong((String) z.get(".msg.img.$hdlength"), 0); } au.HU(); if (!c.isSDCardAvailable()) { s.gH(this.tKy.tTq.getContext()); } else if (bdVar2.field_isSend == 1) { if (com.tencent.mm.a.e.cn(o.Pf().o(f.c(eVar), "", ""))) { a(this.tKy, bdVar2, eVar.dTS, eVar.bYu, auVar.userName, auVar.chatroomName, iArr, i, i2, false); } else { if (com.tencent.mm.a.e.cn(o.Pf().o(eVar.dTL, "", ""))) { a(this.tKy, bdVar2, eVar.dTS, eVar.bYu, auVar.userName, auVar.chatroomName, iArr, i, i2, false); } else { a(bdVar2.field_msgId, bdVar2.field_msgSvrId, auVar.userName, auVar.chatroomName, iArr, i, i2); } } } else if (eVar.OM()) { String str3; a aVar22; String str22 = eVar.dTL; if (eVar.ON()) { e a2 = f.a(eVar); if (a2 != null && a2.dTK > 0 && a2.OM() && com.tencent.mm.a.e.cn(o.Pf().o(a2.dTL, "", ""))) { str3 = a2.dTL; aVar22 = this.tKy; o.Pf().o(str3, "", ""); a(aVar22, bdVar2, eVar.dTS, eVar.bYu, auVar.userName, auVar.chatroomName, iArr, i, i2, false); } } str3 = str22; aVar22 = this.tKy; o.Pf().o(str3, "", ""); a(aVar22, bdVar2, eVar.dTS, eVar.bYu, auVar.userName, auVar.chatroomName, iArr, i, i2, false); } else { if (eVar.status == -1) { x.i("MicroMsg.DesignerClickListener", "retry downloadImg, %d", new Object[]{Long.valueOf(eVar.dTK)}); eVar.setStatus(0); eVar.bWA = 256; o.Pf().a(Long.valueOf(eVar.dTK), eVar); } a(bdVar2.field_msgId, bdVar2.field_msgSvrId, auVar.userName, auVar.chatroomName, iArr, i, i2); } go = g.a.go(bdVar.field_content); if (go != null) { } } private void a(long j, long j2, String str, String str2, int[] iArr, int i, int i2) { String str3; int i3; Bundle bundle; Intent intent = new Intent(this.tKy.tTq.getContext(), ImageGalleryUI.class); intent.putExtra("img_gallery_msg_id", j); intent.putExtra("show_search_chat_content_result", ((w) this.tKy.O(w.class)).cvQ()); intent.putExtra("img_gallery_msg_svr_id", j2); intent.putExtra("key_is_biz_chat", ((com.tencent.mm.ui.chatting.b.b.c) this.tKy.O(com.tencent.mm.ui.chatting.b.b.c.class)).cur()); intent.putExtra("key_biz_chat_id", ((com.tencent.mm.ui.chatting.b.b.c) this.tKy.O(com.tencent.mm.ui.chatting.b.b.c.class)).cuC()); intent.putExtra("img_gallery_talker", str); intent.putExtra("img_gallery_chatroom_name", str2); intent.putExtra("img_gallery_left", iArr[0]); intent.putExtra("img_gallery_top", iArr[1]); intent.putExtra("img_gallery_width", i); intent.putExtra("img_gallery_height", i2); intent.putExtra("img_gallery_enter_from_chatting_ui", ((w) this.tKy.O(w.class)).cvL()); intent.putExtra("img_gallery_enter_from_appbrand_service_chatting_ui", ab.gr(str)); String talkerUserName = this.tKy.getTalkerUserName(); Bundle bundle2 = new Bundle(); if (this.tKy.cwr()) { str3 = "stat_scene"; i3 = 2; bundle = bundle2; } else { str3 = "stat_scene"; if (com.tencent.mm.model.s.hf(talkerUserName)) { i3 = 7; bundle = bundle2; } else { i3 = 1; bundle = bundle2; } } bundle.putInt(str3, i3); bundle2.putString("stat_msg_id", "msg_" + Long.toString(j2)); bundle2.putString("stat_chat_talker_username", talkerUserName); bundle2.putString("stat_send_msg_user", str); intent.putExtra("_stat_obj", bundle2); this.tKy.startActivity(intent); this.tKy.tTq.overridePendingTransition(0, 0); } public static void a(a aVar, bd bdVar, long j, long j2, String str, String str2, int[] iArr, int i, int i2, boolean z) { String str3; int i3; Bundle bundle; Intent intent = new Intent(aVar.tTq.getContext(), ImageGalleryUI.class); intent.putExtra("img_gallery_msg_id", j); intent.putExtra("img_gallery_msg_svr_id", j2); intent.putExtra("show_search_chat_content_result", ((w) aVar.O(w.class)).cvQ()); intent.putExtra("key_is_biz_chat", ((com.tencent.mm.ui.chatting.b.b.c) aVar.O(com.tencent.mm.ui.chatting.b.b.c.class)).cur()); intent.putExtra("key_biz_chat_id", ((com.tencent.mm.ui.chatting.b.b.c) aVar.O(com.tencent.mm.ui.chatting.b.b.c.class)).cuC()); intent.putExtra("img_gallery_talker", str); intent.putExtra("img_gallery_chatroom_name", str2); intent.putExtra("img_gallery_left", iArr[0]); intent.putExtra("img_gallery_top", iArr[1]); intent.putExtra("img_gallery_width", i); intent.putExtra("img_gallery_height", i2); intent.putExtra("img_gallery_enter_from_chatting_ui", ((w) aVar.O(w.class)).cvL()); intent.putExtra("img_gallery_enter_PhotoEditUI", z); intent.putExtra("img_gallery_enter_from_appbrand_service_chatting_ui", ab.gr(str)); String talkerUserName = aVar.getTalkerUserName(); if (bdVar.field_isSend == 1) { str = aVar.cwp(); } Bundle bundle2 = new Bundle(); if (com.tencent.mm.model.s.fq(aVar.getTalkerUserName())) { str3 = "stat_scene"; i3 = 2; bundle = bundle2; } else { str3 = "stat_scene"; if (com.tencent.mm.model.s.hf(talkerUserName)) { i3 = 7; bundle = bundle2; } else { i3 = 1; bundle = bundle2; } } bundle.putInt(str3, i3); bundle2.putString("stat_msg_id", "msg_" + Long.toString(j2)); bundle2.putString("stat_chat_talker_username", talkerUserName); bundle2.putString("stat_send_msg_user", str); intent.putExtra("_stat_obj", bundle2); aVar.tTq.startActivity(intent); aVar.tTq.overridePendingTransition(0, 0); } }
package com.tencent.mm.plugin.card.ui; import android.content.Intent; import android.text.TextUtils; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import com.tencent.mm.plugin.card.d.b; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.protocal.c.la; import com.tencent.mm.sdk.platformtools.x; class CardShopUI$1 implements OnItemClickListener { final /* synthetic */ CardShopUI hGu; final /* synthetic */ Intent val$intent; CardShopUI$1(CardShopUI cardShopUI, Intent intent) { this.hGu = cardShopUI; this.val$intent = intent; } public final void onItemClick(AdapterView<?> adapterView, View view, int i, long j) { if (i == 0) { x.v("MicroMsg.CardShopUI", "onItemClick pos is 0, click headerview"); return; } if (i > 0) { i--; } la laVar = (la) CardShopUI.a(this.hGu).get(i); if (!TextUtils.isEmpty(laVar.rnv) && !TextUtils.isEmpty(laVar.rnw)) { b.e(CardShopUI.b(this.hGu), laVar.rnv, laVar.rnw, 1052, this.val$intent.getIntExtra("key_from_appbrand_type", 0)); } else if (!TextUtils.isEmpty(laVar.hwI)) { b.a(this.hGu, laVar.hwI, 1); h.mEJ.h(11941, new Object[]{Integer.valueOf(4), CardShopUI.c(this.hGu).awq(), CardShopUI.c(this.hGu).awr(), "", laVar.name}); } } }
package com.pineapple.mobilecraft.tumcca.activity; import android.app.ActionBar; import android.app.Activity; import android.content.pm.ActivityInfo; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.MenuItem; import android.view.Window; import com.pineapple.mobilecraft.R; /** * Created by yihao on 10/6/15. */ public class TumccaBaseActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.tumcca_activity_style); requestWindowFeature(Window.FEATURE_ACTION_BAR); ActionBar actionBar = getActionBar(); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayHomeAsUpEnabled(true); //actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.button_normal_red))); actionBar.setIcon(null); actionBar.setBackgroundDrawable(new ColorDrawable(0xffffff)); super.onCreate(savedInstanceState); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if(id == android.R.id.home){ finish(); } return super.onOptionsItemSelected(item); } }
package com.codingblocks.todolist; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { EditText et ; Button btn; ListView lv; ArrayList<String> lst = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et = findViewById(R.id.et); btn = findViewById(R.id.btn); lv = findViewById(R.id.lv); // Adapter listAdapter = new Adapter(); final ArrayAdapter<String> lvAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, lst); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String str = et.getText().toString(); if(!str.isEmpty()) { lst.add(str); et.setText(""); System.out.println(lst); // Adapter listAdapter = new Adapter(); // listAdapter.notifyDataSetChanged(); lvAdapter.notifyDataSetChanged(); } } }); //lv.setAdapter(listAdapter); lv.setAdapter(lvAdapter); } // class Adapter extends BaseAdapter // { // // @Override // public int getCount() { // return lst.size(); // } // // @Override // public String getItem(int position) { // return lst.get(position); // } // // @Override // public long getItemId(int position) { // return 0; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) // { // ListViewHolder holder; // // if(convertView == null) // { // convertView = getLayoutInflater().inflate( // R.layout.list_view_content, // parent, // false // ); // // holder = new ListViewHolder(convertView); // convertView.setTag(holder); // } // else // { // holder = (ListViewHolder) convertView.getTag(); // } // // String item = getItem(position); // // holder.tvNum.setText(position+1); // holder.tvTask.setText(item); // // return convertView; // } // } // // class ListViewHolder // { // TextView tvNum, tvTask; // // public ListViewHolder(View convertView) { // this.tvNum = convertView.findViewById(R.id.tvNum); // this.tvTask = convertView.findViewById(R.id.tvTask); // } // } }
package org.kawanfw.sql.api.client.android.execute.update; import java.sql.SQLException; public interface OnUpdatesCompleteListener { void onUpdatesComplete(int[] results, SQLException e); }
package com.tencent.mm.plugin.account.friend.ui; public enum i$b { ; static { eNH = 1; eNI = 2; eNJ = 3; eNK = new int[]{eNH, eNI, eNJ}; } }
package com.example.ecommerce.api.v1.dto; import com.example.ecommerce.entity.OrderStatus; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class OrderDto { private String code; private OrderStatus orderStatus; }
package thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Created by ZSL on 2017/8/17. */ public class SelfExecutorDemo { public static class MyTask implements Runnable{ private String name; public MyTask(String name){ this.name=name; } @Override public void run() { System.out.println(name+":正在执行,线程id"+Thread.currentThread().getId()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static void main(String[] args) { ExecutorService executor=new ThreadPoolExecutor(5,5,0, TimeUnit.SECONDS,new LinkedBlockingDeque<Runnable>()){ @Override protected void beforeExecute(Thread t, Runnable r) { System.out.println("准备执行:"+((MyTask)r).getName()); } @Override protected void afterExecute(Runnable r, Throwable t) { System.out.println("执行结束:"+((MyTask)r).getName()); } @Override protected void terminated() { System.out.println("线程池退出"); } }; for (int i = 0; i < 10; i++) { executor.execute(new MyTask("线程"+i)); } executor.shutdown(); System.out.println(Runtime.getRuntime().availableProcessors()); } }
package LeetCode.ArraysAndStrings; import java.util.*; public class SubdomainVisitCount { public List<String> subdomainVisits(String[] cpdomains){ List<String> res = new ArrayList<>(); HashMap<String, Integer> map = new HashMap<>(); for(String s : cpdomains){ String[] str = s.split("\\s"); String[] split = str[1].split("\\."); String k = ""; for(int i = split.length-1; i >= 0; i--){ k = k == "" ? split[i]+k : split[i]+"."+k; map.put(k, map.getOrDefault(k, 0) + Integer.parseInt(str[0])); } } for(Map.Entry<String, Integer> entry : map.entrySet()){ res.add("" + entry.getValue() + " " + entry.getKey()); } return res; } public static void main(String[] args){ String[] str = {"900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"}; SubdomainVisitCount s = new SubdomainVisitCount(); List<String> res = s.subdomainVisits(str); for(String r : res) { System.out.println(r); } } }
package com.tencent.mm.wallet_core.c; import android.widget.Toast; import com.tencent.mm.ab.b; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.network.k; import com.tencent.mm.network.q; import com.tencent.mm.plugin.wxpay.a.i; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity; import java.lang.ref.WeakReference; import junit.framework.Assert; public abstract class h extends l implements k { private static final String uXd = ad.getResources().getString(i.wallet_unknown_err); private WeakReference<MMActivity> YC; protected String Yy; public b diG; public e diJ; protected int errCode = 0; protected int errType = 0; public boolean hUU = true; public boolean hUV = false; public int uXe = 0; public String uXf; public abstract void b(int i, int i2, String str, q qVar); public abstract void f(q qVar); public final void m(MMActivity mMActivity) { this.YC = new WeakReference(mMActivity); } public boolean aBQ() { return true; } public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { if (i2 == 0 && i3 == 0) { this.hUU = false; } if (!this.hUU) { f(qVar); if (this.uXe != 0) { this.hUV = true; } } this.errCode = i3; this.errType = i2; this.Yy = str; x.i("MicroMsg.NetSceneNewPayBase", "errType: %s, errCode: %s, errMsg: %s, retCode: %s, retMsg: %s", new Object[]{Integer.valueOf(i2), Integer.valueOf(i3), str, Integer.valueOf(this.uXe), this.uXf}); b(i2, i3, str, qVar); if (this.YC != null) { MMActivity mMActivity = (MMActivity) this.YC.get(); if (mMActivity == null) { return; } if (this.hUU) { x.w("MicroMsg.NetSceneNewPayBase", "show net error alert"); com.tencent.mm.ui.base.h.a(mMActivity, uXd, null, false, new 1(this, mMActivity)); } else if (this.hUV && !bi.oW(this.uXf) && aBQ()) { x.w("MicroMsg.NetSceneNewPayBase", "show resp error toast"); Toast.makeText(mMActivity, this.uXf, 1).show(); } } } public int a(com.tencent.mm.network.e eVar, e eVar2) { this.diJ = eVar2; Assert.assertNotNull("rr can't be null!", this.diG); return a(eVar, this.diG, this); } public final h a(a aVar) { if (!(this.hUU || this.hUV)) { aVar.g(this.errCode, this.errType, this.Yy, this); } return this; } public final h b(a aVar) { if (this.hUV) { aVar.g(this.errCode, this.errType, this.Yy, this); } return this; } public final h c(a aVar) { if (this.hUU) { aVar.g(this.errCode, this.errType, this.Yy, this); } return this; } }
package midterm; import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class DeleteTutor */ @WebServlet("/Midterm/DeleteTutor") public class DeleteTutor extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DeleteTutor() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("email"); ArrayList<Tutor> tutors = (ArrayList<Tutor>) getServletContext().getAttribute("tutors"); for(Tutor tutor : tutors) { if(tutor.getEmail().contains(email)) { tutors.remove(tutor); break; } } response.sendRedirect("Admin"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
public class Password { public boolean result; private boolean checkPsw (String psw) { return result; }; private void login(boolean result) { }; }