text
stringlengths 10
2.72M
|
|---|
package com.wp.finki.ukim.mk.catalogware;
import org.slf4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.slf4j.LoggerFactory.*;
@Controller
@SpringBootApplication
@EnableWebMvc
public class CatalogwareApplication {
public static void main(String[] args) {
SpringApplication.run(CatalogwareApplication.class, args);
}
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
}
|
package repls04;
import java. util.*;
public class RemoveDublic {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(uniqueChars(in.next()));
}
public static String uniqueChars(String str) {
//TODO: write your code
String word ="";
for(int i = 0; i < str.length();i++) {
if (!word.contains(str.charAt(i)+"")) {
word += str.charAt(i);
}
}
return word;
}
}
|
package com.qd.mystudy.agent;
/**
* Created by liqingdong911 on 2014/10/22.
*/
public class MyDummy {
public void print1(){
System.out.println("print1 5");
}
}
|
package com.apmv1.webservices;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
/**
* Created by Beto on 10/07/2015.
*/
public class InsertActivity extends AppCompatActivity
implements DatePickerFragment.OnDateSelectedListener,
ConfirmDialogFragment.ConfirmDialogListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getSupportActionBar() != null)
getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_done);
// Creación del fragmento de inserción
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new InsertFragment(), "InsertFragment")
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_form, menu);
return true;
}
@Override
public void onDateSelected(int year, int month, int day) {
InsertFragment insertFragment = (InsertFragment)
getSupportFragmentManager().findFragmentByTag("InsertFragment");
if (insertFragment != null) {
insertFragment.actualizarFecha(year, month, day);
}
}
@Override
public void onDialogPositiveClick(DialogFragment dialog) {
InsertFragment insertFragment = (InsertFragment)
getSupportFragmentManager().findFragmentByTag("InsertFragment");
if (insertFragment != null) {
finish(); // Finalizar actividad descartando cambios
}
}
@Override
public void onDialogNegativeClick(DialogFragment dialog) {
InsertFragment insertFragment = (InsertFragment)
getSupportFragmentManager().findFragmentByTag("InsertFragment");
if (insertFragment != null) {
// Nada por el momento
}
}
}
|
package sim.ordemcompra;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class OrdemCompraDAOHibernate implements OrdemCompraDAO {
private Session session;
@Override
public void emitir(OrdemCompra ordemCompra) {
this.session.save(ordemCompra);
}
@Override
public void excluir(OrdemCompra ordemCompra) {
this.session.delete(ordemCompra);
}
@Override
public void atualizar(OrdemCompra ordemCompra) {
this.session.update(ordemCompra);
}
@Override
public OrdemCompra carregar(Integer codigo) {
return (OrdemCompra) this.session.get(OrdemCompra.class, codigo);
}
public OrdemCompra carregarPorPedido(Integer numeroPedido) {
String hql = "select oc from OrdemCompra oc where oc.pedido.codigo = :numero";
Query q = this.session.createQuery(hql);
q.setInteger("numero", numeroPedido);
return (OrdemCompra) q.uniqueResult();
}
@Override
public List<OrdemCompra> listar() {
return this.session.createCriteria(OrdemCompra.class).list();
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
}
|
package com.sample.school.vo;
import java.util.Date;
public class Course {
private int no;
private String title;
private Dept dept;
private Subject subject;
private Prof prof;
private int studentCount;
private boolean registerable;
private Date registeredDate;
public Course() {
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
public Prof getProf() {
return prof;
}
public void setProf(Prof prof) {
this.prof = prof;
}
public int getStudentCount() {
return studentCount;
}
public void setStudentCount(int studentCount) {
this.studentCount = studentCount;
}
public boolean isRegisterable() {
return registerable;
}
public void setRegisterable(boolean registerable) {
this.registerable = registerable;
}
public Date getRegisteredDate() {
return registeredDate;
}
public void setRegisteredDate(Date registeredDate) {
this.registeredDate = registeredDate;
}
}
|
package com.smxknife.softmarket;
import com.smxknife.softmarket.util.WeChatUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = BootApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration
public class WeChatUtilTest {
@Value("${wechat.token}")
String token;
@Test
public void checkSignatureTest() {
String signature = "61202fc706ff6c29be6eebbdfd76293b544dd466";
String timestamp = "1520398553";
String notice = "613396428";
String echostr = "17026579936650983677";
assert WeChatUtil.checkSignature(signature, timestamp, notice, token) == true;
}
}
|
package com.github.jerrysearch.tns.server.summary;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import com.github.jerrysearch.tns.protocol.rpc.event.LogEvent;
/**
* 各种数据汇总
*
* @author jerry
*
*/
public class Summary {
/**
* 初始容量100
*/
private final LinkedBlockingQueue<LogEvent> queue = new LinkedBlockingQueue<LogEvent>(100);
public void appendLogEvent(LogEvent event) {
boolean sucess = this.queue.offer(event);
if (sucess) {
return;
} else {
this.queue.clear(); // 暴力清除
this.queue.offer(event);
}
}
public List<LogEvent> takeAllLogEvent() {
List<LogEvent> list = new LinkedList<LogEvent>();
while (true) {
LogEvent event = this.queue.poll();
if (null == event) {
break;
} else {
list.add(event);
}
}
return list;
}
private Summary() {
};
private static class proxy {
private static Summary summary = new Summary();
}
public static Summary getInstance() {
return proxy.summary;
}
}
|
package prj.betfair.api.betting.datatypes;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import prj.betfair.api.betting.datatypes.Order;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonDeserialize(builder = Order.Builder.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order {
private final String status;
private final String persistenceType;
private final double bspLiability;
private final String orderType;
private final double price;
private final double sizeVoided;
private final double avgPriceMatched;
private final double sizeCancelled;
private final double sizeLapsed;
private final double sizeRemaining;
private final Date placedDate;
private final String betId;
private final String side;
private final double sizeMatched;
private final double size;
public Order(Builder builder) {
this.status = builder.status;
this.persistenceType = builder.persistenceType;
this.bspLiability = builder.bspLiability;
this.orderType = builder.orderType;
this.price = builder.price;
this.sizeVoided = builder.sizeVoided;
this.avgPriceMatched = builder.avgPriceMatched;
this.sizeCancelled = builder.sizeCancelled;
this.sizeLapsed = builder.sizeLapsed;
this.sizeRemaining = builder.sizeRemaining;
this.placedDate = builder.placedDate;
this.betId = builder.betId;
this.side = builder.side;
this.sizeMatched = builder.sizeMatched;
this.size = builder.size;
}
/**
* @return betId
*/
public String getBetId() {
return this.betId;
}
/**
* @return orderType BSP Order type.
*/
public String getOrderType() {
return this.orderType;
}
/**
* @return status Either EXECUTABLE (an unmatched amount remains) or EXECUTION_COMPLETE (no
* unmatched amount remains).
*/
public String getStatus() {
return this.status;
}
/**
* @return persistenceType What to do with the order at turn-in-play
*/
public String getPersistenceType() {
return this.persistenceType;
}
/**
* @return side
*/
public String getSide() {
return this.side;
}
/**
* @return price The price of the bet.
*/
public double getPrice() {
return this.price;
}
/**
* @return size The size of the bet.
*/
public double getSize() {
return this.size;
}
/**
* @return bspLiability Not to be confused with size. This is the liability of a given BSP bet.
*/
public double getBspLiability() {
return this.bspLiability;
}
/**
* @return placedDate The date, to the second, the bet was placed.
*/
public Date getPlacedDate() {
return this.placedDate;
}
/**
* @return avgPriceMatched The average price matched at. Voided match fragments are removed from
* this average calculation.
*/
public double getAvgPriceMatched() {
return this.avgPriceMatched;
}
/**
* @return sizeMatched The current amount of this bet that was matched.
*/
public double getSizeMatched() {
return this.sizeMatched;
}
/**
* @return sizeRemaining The current amount of this bet that is unmatched.
*/
public double getSizeRemaining() {
return this.sizeRemaining;
}
/**
* @return sizeLapsed The current amount of this bet that was lapsed.
*/
public double getSizeLapsed() {
return this.sizeLapsed;
}
/**
* @return sizeCancelled The current amount of this bet that was cancelled.
*/
public double getSizeCancelled() {
return this.sizeCancelled;
}
/**
* @return sizeVoided The current amount of this bet that was voided.
*/
public double getSizeVoided() {
return this.sizeVoided;
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Builder {
private String status;
private String persistenceType;
private double bspLiability;
private String orderType;
private double price;
private double sizeVoided;
private double avgPriceMatched;
private double sizeCancelled;
private double sizeLapsed;
private double sizeRemaining;
private Date placedDate;
private String betId;
private String side;
private double sizeMatched;
private double size;
/**
* @param status : Either EXECUTABLE (an unmatched amount remains) or EXECUTION_COMPLETE (no
* unmatched amount remains).
* @param persistenceType : What to do with the order at turn-in-play
* @param bspLiability : Not to be confused with size. This is the liability of a given BSP bet.
* @param orderType : BSP Order type.
* @param price : The price of the bet.
* @param placedDate : The date, to the second, the bet was placed.
* @param betId
* @param side
* @param size : The size of the bet.
*/
public Builder(@JsonProperty("status") String status,
@JsonProperty("persistenceType") String persistenceType,
@JsonProperty("bspLiability") double bspLiability,
@JsonProperty("orderType") String orderType, @JsonProperty("price") double price,
@JsonProperty("placedDate") Date placedDate, @JsonProperty("betId") String betId,
@JsonProperty("side") String side, @JsonProperty("size") double size) {
this.status = status;
this.persistenceType = persistenceType;
this.bspLiability = bspLiability;
this.orderType = orderType;
this.price = price;
this.placedDate = placedDate;
this.betId = betId;
this.side = side;
this.size = size;
}
/**
* Use this function to set avgPriceMatched
*
* @param avgPriceMatched The average price matched at. Voided match fragments are removed from
* this average calculation.
* @return Builder
*/
public Builder withAvgPriceMatched(double avgPriceMatched) {
this.avgPriceMatched = avgPriceMatched;
return this;
}
/**
* Use this function to set sizeMatched
*
* @param sizeMatched The current amount of this bet that was matched.
* @return Builder
*/
public Builder withSizeMatched(double sizeMatched) {
this.sizeMatched = sizeMatched;
return this;
}
/**
* Use this function to set sizeRemaining
*
* @param sizeRemaining The current amount of this bet that is unmatched.
* @return Builder
*/
public Builder withSizeRemaining(double sizeRemaining) {
this.sizeRemaining = sizeRemaining;
return this;
}
/**
* Use this function to set sizeLapsed
*
* @param sizeLapsed The current amount of this bet that was lapsed.
* @return Builder
*/
public Builder withSizeLapsed(double sizeLapsed) {
this.sizeLapsed = sizeLapsed;
return this;
}
/**
* Use this function to set sizeCancelled
*
* @param sizeCancelled The current amount of this bet that was cancelled.
* @return Builder
*/
public Builder withSizeCancelled(double sizeCancelled) {
this.sizeCancelled = sizeCancelled;
return this;
}
/**
* Use this function to set sizeVoided
*
* @param sizeVoided The current amount of this bet that was voided.
* @return Builder
*/
public Builder withSizeVoided(double sizeVoided) {
this.sizeVoided = sizeVoided;
return this;
}
public Order build() {
return new Order(this);
}
}
}
|
public class Lands extends Rentable{
public Lands(String land_name, int cost, boolean is_free, String owner_name, int rent_amount,int location) {
super(land_name,cost,is_free,owner_name,rent_amount,location);
}
public int setRent_amount(int cost) {
if(cost>3000) {
return (cost*35)/100;
}
else if (cost>2000) {
return (cost*30)/100;
}
else {
return (cost*40)/100;
}
}
public static void create_land(String name,int cost, int location ) {
Rentable x = new Lands(name,cost,true,null,0,location);
Rentable.rentables[location] = x;
}
}
|
package tws.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tws.mapper.EmployeeMapper;
import tws.model.Employee;
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeMapper employeeMapper;
@PostMapping
public void addEmployee(@RequestBody Employee employee) {
employeeMapper.insertEmployee(employee);
}
@GetMapping("")
public ResponseEntity<List<Employee>>getAllEmployee(){
return ResponseEntity.ok(employeeMapper.searchEmployee());
}
@PutMapping("/{id}")
public void updateEmployee(@PathVariable int id,@RequestBody Employee employee){
employeeMapper.updateEmployee(id, employee);
}
@DeleteMapping("/{id}")
public void deleteEmployee(@PathVariable int id) {
employeeMapper.deleteEmployee(id);
}
}
|
package com.klj.springtest.extend.algorithms.sorts;
public class QuickSort<T extends Comparable<T>> {
public static <T extends Comparable<T>> T[] sort(T[] unsorted){
quickSort(unsorted, 0, unsorted.length-1);
return unsorted;
}
private static <T extends Comparable<T>> void quickSort(T[] unsorted, int left, int right){
if(left > right){
return;
}
int i = left;
int j = right;
T temp = unsorted[left];
while(i < j){
if(unsorted[i].compareTo(temp) < 0){
i ++;
}
if(unsorted[j].compareTo(temp) > 0){
j --;
}
if(i < j){
T t = unsorted[i];
unsorted[j] = unsorted[i];
unsorted[i] = t;
}
}
unsorted[left] = unsorted[i];
unsorted[i] = temp;
quickSort(unsorted, left, j-1);
quickSort(unsorted, i+1, right);
}
}
|
package bootcamp.testng;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DepandsOn {
@BeforeMethod
public void setup() {
System.out.println("bm: depends on");
}
@Test
public void login() {
System.out.println("Perform login operation");
// Assert.assertTrue(false);
}
@Test(dependsOnMethods = "login")
public void verifyHomePage() {
System.out.println("Verify text on homepage");
}
@AfterMethod
public void teardown() {
System.out.println("am: depends on");
}
}
|
package com.gsonkeno.hot.kafka;
import org.apache.kafka.clients.producer.ProducerRecord;
/**生产者生产记录(消息)包装器
* Created by gaosong on 2017-05-13.
*/
public class ProducerRecordWrapper {
//ProducerRecord构造器五大要素
private String topicName;
private Integer partition;
private Long timestamp;
private String key;
private String value;
private ProducerRecordWrapper(Builder builder) {
this.topicName = builder.topName;
this.partition = builder.partition;
this.timestamp = builder.timestamp;
this.key = builder.key;
this.value = builder.value;
}
public ProducerRecord getRecord(){
return new ProducerRecord(topicName,partition,timestamp,key,value);
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String topName;
private Integer partition;
private Long timestamp;
private String key;
private String value;
private Builder() {
}
public ProducerRecordWrapper build() {
return new ProducerRecordWrapper(this);
}
public Builder topicName(String topName) {
this.topName = topName;
return this;
}
public Builder partition(int partition) {
this.partition = partition;
return this;
}
public Builder timestamp(long timestamp) {
this.timestamp = timestamp;
return this;
}
public Builder key(String key) {
this.key = key;
return this;
}
public Builder value(String value) {
this.value = value;
return this;
}
}
}
|
package com.onwardpath.georeach.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.MDC;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.sql.SQLException;
import java.util.Map;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.onwardpath.georeach.model.User;
import com.onwardpath.georeach.repository.ConfigRepository;
import com.onwardpath.georeach.repository.ExperienceRepository;
import com.onwardpath.georeach.util.Database;
import org.apache.log4j.MDC;
@SuppressWarnings("serial")
public class ConfigController extends HttpServlet {
private ConfigRepository configRepository;
private ExperienceRepository expController;
/**
* @see HttpServlet#HttpServlet()
*/
public ConfigController() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pageName = request.getParameter("pageName");
RequestDispatcher view = request.getRequestDispatcher("?view=pages/"+pageName);
view.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
configRepository = new ConfigRepository();
String pageName = request.getParameter("pageName");
System.out.println(Database.getTimestamp()+" @ConfigController.doPost>pageName: "+pageName);
HttpSession session = request.getSession();
int org_id = (Integer)session.getAttribute("org_id");
int user_id = (Integer)session.getAttribute("user_id");
User user = (User) session.getAttribute("user");
String orgname = user.getOrganization_domain();
MDC.put("user", user_id);
MDC.put("org", orgname);
try {
if (configRepository != null) {
if (pageName.startsWith("experience-create-enable")) {
int experience_id = Integer.parseInt(request.getParameter("experience_id"));
String experience_name = request.getParameter("experience_name");
String experience_type = request.getParameter("experience_type");
if(experience_type.equals("block"))
{
String block_url=(String)session.getAttribute("block_url");
ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, String> map = mapper.readValue(block_url, Map.class);
System.out.println(map);
for (Map.Entry<String, String> entry : map.entrySet()) {
int index = Integer.parseInt(entry.getKey());
String url = entry.getValue();
System.out.println("index = " + index + ", URL = " + url);
String array1[]= url.split("-");
String array2= array1[0];
String array3= array1[1];
configRepository.save(experience_id, array2, user_id);
}
/* Update Schedule startdate and endate for experience table */
//System.out.println("Startdate in config controler ::"+request.getParameter("startdate"));
expController = new ExperienceRepository();
if(request.getParameter("status")!=null && request.getParameter("status") !="") {
expController.update(experience_id, 3, "status",request.getParameter("status"));
if(request.getParameter("startdate") != null && request.getParameter("startdate") !="") {
expController.update(experience_id, 4, "schedule_start",request.getParameter("startdate"));
}
if(request.getParameter("enddate") != null && request.getParameter("enddate") !="") {
expController.update(experience_id, 5, "schedule_end",request.getParameter("enddate"));
}
if(request.getParameter("timezoneval") != null && request.getParameter("timezoneval") !="") {
expController.update(experience_id, 6, "timezone_id",request.getParameter("timezoneval"));
}
}
System.out.println(Database.getTimestamp()+"Page configuration for <b>"+experience_name+"</b> saved succesfully.#n="+experience_name+"#e="+experience_id+"#o="+org_id+"#t="+experience_type);
session.setAttribute("message", "Page configuration for <b>"+experience_name+"</b> saved succesfully.#n="+experience_name+"#e="+experience_id+"#o="+org_id+"#t="+experience_type);
}
else
{
String configDetails = request.getParameter("urlList");
ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, String> map = mapper.readValue(configDetails, Map.class);
System.out.println(map);
for (Map.Entry<String, String> entry : map.entrySet()) {
int index = Integer.parseInt(entry.getKey());
String url = entry.getValue();
System.out.println("index = " + index + ", URL = " + url);
configRepository.save(experience_id, url, user_id);
}
/* Update Schedule startdate and endate for experience table */
//System.out.println("Startdate in config controler ::"+request.getParameter("startdate"));
expController = new ExperienceRepository();
if(request.getParameter("status")!=null && request.getParameter("status") !="") {
expController.update(experience_id, 3, "status",request.getParameter("status"));
if(request.getParameter("startdate") != null && request.getParameter("startdate") !="") {
expController.update(experience_id, 4, "schedule_start",request.getParameter("startdate"));
}
if(request.getParameter("enddate") != null && request.getParameter("enddate") !="") {
expController.update(experience_id, 5, "schedule_end",request.getParameter("enddate"));
}
if(request.getParameter("timezoneval") != null && request.getParameter("timezoneval") !="") {
expController.update(experience_id, 6, "timezone_id",request.getParameter("timezoneval"));
}
}
System.out.println(Database.getTimestamp()+"Page configuration for <b>"+experience_name+"</b> saved succesfully.#n="+experience_name+"#e="+experience_id+"#o="+org_id+"#t="+experience_type);
session.setAttribute("message", "Page configuration for <b>"+experience_name+"</b> saved succesfully.#n="+experience_name+"#e="+experience_id+"#o="+org_id+"#t="+experience_type);
}
}
}
} catch (SQLException e) {
session.setAttribute("message", "Error: "+e.getMessage()+". Please try later or contact the administrator.");
}
RequestDispatcher view = request.getRequestDispatcher("?view=pages/"+pageName);
view.forward(request, response);
}
}
|
package com.cloudogu.smeagol.repository.infrastructure;
import com.cloudogu.smeagol.ScmHttpClient;
import com.cloudogu.smeagol.repository.domain.Branch;
import com.cloudogu.smeagol.repository.domain.BranchRepository;
import com.cloudogu.smeagol.repository.domain.Name;
import com.cloudogu.smeagol.repository.domain.RepositoryId;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ScmBranchRepository implements BranchRepository {
private ScmHttpClient scmHttpClient;
@Autowired
public ScmBranchRepository(ScmHttpClient scmHttpClient) {
this.scmHttpClient = scmHttpClient;
}
@Override
public Iterable<Branch> findByRepositoryId(RepositoryId repositoryId) {
String url = String.format("/api/rest/repositories/%s/branches.json", repositoryId);
BranchesDTO dto = scmHttpClient.get(url, BranchesDTO.class).get();
return dto.branch.stream()
.map(b -> new Branch(repositoryId, Name.valueOf(b.name)))
.collect(Collectors.toList());
}
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
private static class BranchesDTO {
private List<BranchDTO> branch;
}
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
private static class BranchDTO {
private String name;
}
}
|
package euclideanAlgorithm;
public class Application {
public static void main (String[] args) {
new Nwd();
Nwd.evaluate(123422312,32354364);
}
}
|
/**
*
*/
package main;
import java.text.DecimalFormat;
import java.util.GregorianCalendar;
/**
* @author Julian Kuerby
*
*/
@SuppressWarnings("serial")
public class RFC3339Calendar extends GregorianCalendar {
public RFC3339Calendar() {
super();
}
public RFC3339Calendar(int year, int month, int dayOfMonth) {
super(year, month, dayOfMonth);
}
public RFC3339Calendar(int year, int month, int dayOfMonth, int hourOfDay, int minute) {
super(year, month, dayOfMonth, hourOfDay, minute);
}
public RFC3339Calendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second) {
super(year, month, dayOfMonth, hourOfDay, minute, second);
}
public String toString() {
return get(YEAR) + "-" + formatInt(get(MONTH)+1) + "-" + formatInt(get(DAY_OF_MONTH)) + "T" + formatInt(get(HOUR_OF_DAY)) + ":" + formatInt(get(MINUTE)) + ":" + formatInt(get(SECOND)) /*+ "." formatInt(get(MILLISECOND))*/ + "Z";
}
public String getRFC3339Date() {
return get(YEAR) + "-" + formatInt(get(MONTH)+1) + "-" + formatInt(get(DAY_OF_MONTH)) + "T00:00:00Z";
}
public String getDate() {
return get(YEAR) + "-" + formatInt(get(MONTH)+1) + "-" + formatInt(get(DAY_OF_MONTH));
}
public String getTimeOfDay() {
return formatInt(get(HOUR_OF_DAY)) + ":" + formatInt(get(MINUTE)) + ":" + formatInt(get(SECOND));
}
public static RFC3339Calendar parseDate(String date) {
if(! date.matches("\\d{4}-\\d{2}-\\d{2}")) {
throw new IllegalArgumentException("Illegal Date-Format");
}
int year = Integer.parseInt(date.substring(0, 4)); // 2012-09-12
int month = Integer.parseInt(date.substring(5, 7))-1;
int dayOfMonth = Integer.parseInt(date.substring(8));
return new RFC3339Calendar(year, month, dayOfMonth);
}
private String formatInt(int i) {
DecimalFormat df = new DecimalFormat("00");
return df.format(i);
}
@Override
public RFC3339Calendar clone() {
return (RFC3339Calendar) super.clone();
}
}
|
package pl.finsys.mvcRest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath:mvc-dispatcher-servlet.xml"})
public class RestControllerTest {
private MockMvc mockMvc;
@Autowired private WebApplicationContext wac;
@Before
public void setup() throws Exception {
this.mockMvc = webAppContextSetup(this.wac).alwaysExpect(status().isOk()).build();
}
@Test
public void testXML() throws Exception {
this.mockMvc.perform(get("/book/Spring").header("Accept", "application/xml"))
.andExpect(content().contentType("application/xml"));
}
@Test
public void testJson() throws Exception {
this.mockMvc.perform(get("/book/Spring").header("Accept", "application/json"))
.andExpect(content().contentType("application/json"));
}
}
|
package geh.sort.heap;
import java.util.Arrays;
import junit.framework.TestCase;
public class HeapTest extends TestCase {
Heap<Integer> heap;
@Override
protected void setUp() throws Exception {
}
public void testAddHeap() {
Integer[] arr = new Integer[10];
for (int i = 0; i < 10; i++) {
arr[i] = i + 1;
}
System.out.println("initiate arr : " + Arrays.toString(arr));
heap = new Heap<Integer>(arr, Heap.ASC);
System.out.println("heap arr : " + heap);
heap.heapSort();
System.out.println("heap sort arr : " + heap);
}
}
|
package com.tencent.mm.plugin.appbrand.launching;
import com.tencent.mm.plugin.appbrand.launching.i.a;
import java.util.Locale;
final class i$a$a {
String gfG;
String gfH;
i$a$a() {
}
final i$a$a m(String str, Object... objArr) {
this.gfG = String.format(Locale.US, str, objArr);
return this;
}
final i$a$a n(String str, Object... objArr) {
this.gfH = String.format(Locale.US, str, objArr);
return this;
}
final a akF() {
return new a(this.gfH, this.gfG);
}
}
|
package com.tencent.mm.plugin.appbrand.widget.input;
import com.tencent.mm.plugin.appbrand.jsapi.o.c;
import com.tencent.mm.plugin.appbrand.jsapi.o.c.f;
import com.tencent.mm.sdk.platformtools.x;
class ac$2 implements Runnable {
final /* synthetic */ ac gJf;
ac$2(ac acVar) {
this.gJf = acVar;
}
public final void run() {
if (this.gJf.gJc) {
f bL = c.bL(this.gJf.gIY);
if (this.gJf.gJa == null || Math.abs(this.gJf.gJa.x - bL.x) > 1.0f || Math.abs(this.gJf.gJa.y - bL.y) > 1.0f) {
x.v(this.gJf.TAG, "check long press timeout, but view has moved.");
} else if (this.gJf.gJb != null) {
this.gJf.gJc = false;
this.gJf.gIY.removeCallbacks(this.gJf.gJd);
}
}
}
}
|
/*
* 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 tbpane;
import java.math.BigDecimal;
/**
*
* @author edgargarcia
*/
public class empleado {
private String id,nombre,apellidop,apellidom,idfar,sucursal,telefono,numero,calle,colonia,ciudad,estado,cp;
public empleado(String id,String nombre,String apellidop,String apellidom,String idfar,String sucursal,String telefono,String numero, String calle,String colonia, String ciudad,String estado,String cp){
this.id=id;
this.nombre=nombre;
this.apellidop=apellidop;
this.apellidom=apellidom;
this.idfar=idfar;
this.sucursal=sucursal;
this.telefono=telefono;
this.numero=numero;
this.calle=calle;
this.colonia=colonia;
this.ciudad=ciudad;
this.estado=estado;
this.cp=cp;
}
public empleado(String string, String string0, String string1, String string2, String string3, int aInt, BigDecimal bigDecimal, int aInt0) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public empleado(String string, String string0, String string1, String string2, String string3, String string4, String string5, String string6, String string7) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public String getid(){
return id;
}
public void setid(String id){
this.id=id;
}
public String getnombre(){
return nombre;
}
public void setnombre(String nombre){
this.nombre=nombre;
}
public String getapellidop(){
return apellidop;
}
public void setapellidop(String apellidop){
this.apellidop=apellidop;
}
public String getapellidom(){
return apellidom;
}
public void setapellidom(String apellidom){
this.apellidom=apellidom;
}
public String getidfar(){
return idfar;
}
public void setidfar(String idfar){
this.idfar=idfar;
}
public String getsucursal(){
return sucursal;
}
public void setsucursal(String sucursal){
this.sucursal=sucursal;
}
public String gettelefono(){
return telefono;
}
public void settelefono(String telefono){
this.telefono=telefono;
}
public String getnumero(){
return numero;
}
public void setnumero(String numero){
this.numero=numero;
}
public String getcalle(){
return calle;
}
public void setcalle(String calle){
this.calle=calle;
}
public String getcolonia(){
return colonia;
}
public void setcolonia(String colonia){
this.colonia=colonia;
}
public String getciudad(){
return ciudad;
}
public void setciudad(String ciudad){
this.ciudad=ciudad;
}
public String getestado(){
return estado;
}
public void setestado(String estado){
this.estado=estado;
}
public String getcp(){
return cp;
}
public void setcp(String cp){
this.cp=cp;
}
}
|
package com.licyun.model;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
/**
* Created by 李呈云
* Description:
* 2016/9/27.
*/
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected int id;
@Column(name = "TYPE", nullable = false)
protected int type;
@Column(name = "NAME")
private String name;
@NotEmpty
@Column(name = "EMAIL", nullable = false)
private String email;
@NotEmpty
@Column(name = "PASSWD", nullable = false)
private String passwd;
@Column(name = "IMGURL", nullable = true)
private String imgUrl;
public User(){}
public User(int id, String name, String email, String passwd){
this.name = name;
this.id = id;
this.email = email;
this.passwd = passwd;
}
public User(int id, String name, String email, String passwd, int type){
this.name = name;
this.id = id;
this.email = email;
this.passwd = passwd;
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) { this.id = id; }
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}
|
package com.example.wattson.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.wattson.R;
public class SettingsAdapter extends RecyclerView.Adapter<SettingsAdapter.MyViewHolder> {
private String[] m_label;
private String[] m_values;
Context context;
public SettingsAdapter(Context ct, String[] label, String[] values){
context = ct;
m_label = label;
m_values = values;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.setting_plain_card, parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.labelText.setText(m_label[position]);
if(!m_values[position].equals("-1")){
holder.valueText.setText(m_values[position]);
}
}
@Override
public int getItemCount() {
return m_label.length;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
private TextView labelText;
private TextView valueText;
public MyViewHolder(@NonNull View view){
super(view);
labelText = view.findViewById(R.id.textViewSettingLabel);
valueText = view.findViewById(R.id.textViewSettingSecondary);
}
}
}
|
package Algorithm;
public class a5 {
// 动态规划
// public static String longestPalindrome(String s) {
// if (s.length()<2)return s;
// int len = s.length();
// boolean[][] dp=new boolean[len][len];
// for (int i=0;i<len;i++){
// dp[i][i]=true;
// }
// int max=0;
// int begin=0;
// for (int j=1;j<len;j++){
// for (int i=0;i<j;i++){
// if (s.charAt(i)!=s.charAt(j)){
// dp[i][j]=false;
// }else {
// if (j-i-1<2)dp[i][j]=true;
// else {
// dp[i][j]=dp[i+1][j-1];
// }
// }
// if (dp[i][j]&&j-i+1>max){
// max=j-i+1;
// begin=i;
// }
// }
// }
// return s.substring(begin,begin+max);
// }
public static String longestPalindrome(String s){
if (s==null)return "";
int len=s.length();
if (len<2)return s;
int maxlen=0;
int begin=1;
for (int i=0;i<s.length();i++){
int len1=helper(s,i,i);
int len2=helper(s,i,i+1);
int temp=Math.max(len1,len2);
if (temp>maxlen){
maxlen=temp;
begin=i-(temp-1)/2;
}
}
return s.substring(begin,begin+maxlen);
}
private static int helper(String s, int left,int right){
while(left>=0&&right<s.length()&&s.charAt(left)==s.charAt(right)){
left--;
right++;
}
return right-left-1;
}
public static void main(String[] args) {
String s="xxabccbadd";
System.out.println(longestPalindrome(s));
}
}
|
package VSMFeatureMatrices;
import jeigen.SparseMatrixLil;
public class VSMSparseMatrix extends SparseMatrixLil implements
java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -4599852225519300490L;
/**
*
* @param rows
* @param cols
*/
public VSMSparseMatrix(int rows, int cols) {
super(rows, cols);
}
}
|
/*****************************************************************************************
* @project : MissingU 프로젝트 1차
* @title : MissingU 공통변수
* @description : MissingU 서버단에서 사용되는 공통변수
* @author : CSH
* ------------------------------------------------------------
* @history :
*****************************************************************************************/
package kr.ko.nexmain.server.MissingU.common;
/***************************************************************************
Constants
=========
MissingU 서버단에서 사용되는 공통변수
*******************************************************************************/
public interface Constants {
interface TSTORE {
public static final String APP_ID_MISSINGU = "OA00384638";
public static final boolean DEBUG_MODE = true;
public static final String RECEIPTS_VARIFICATION_URL = "https://iap.tstore.co.kr/digitalsignconfirm.iap";
public static final String RECEIPTS_VARIFICATION_URL_DEBUG = "https://iapdev.tstore.co.kr/digitalsignconfirm.iap";
public static final String PRODUCT_ID_10000_POINT = "0910007257";
public static final String PRODUCT_ID_24000_POINT = "0910007259";
public static final String PRODUCT_ID_36000_POINT = "0910007260";
}
/**********************************************
C2DM 관련 정보
==============
***********************************************/
interface C2DM {
public static final String C2DM_SENDER_ID = "missinguc2dm@gmail.com";
public static final String C2DM_SENDER_PW = "altlddb0314";
public static final String C2DM_AUTH_TOKEN = "DQAAAL8AAAAshTCEUtpdyfYerw4kZFu8VwNZ_JcEIt_rDAGUIcSV8V7uIMdAgTn1C58ZlZBdMR5jXpHIU7YYtzt0JG7TgQATrRAiWS0eyIqFsc56O00ITKm--6yXTe_MPDpmHwAc0dGEuI5-tIWSLvh0j0Kvk6G7fUwB9WcKg9QS_5zlZqIKsFb0lmKJjMAj_PsIautkDsRLPo14MZPW24my9oJ74EXdO9kxeJb-M0AJClhLCPxTKSb_fhDBONJ9Rqfv7BgSFfw";
}
interface GCM {
public static final String GCM_PROJECT_CODE = "677882472313";
public static final String API_SERVER_KEY = "AIzaSyDz5Lsz2WQMLtCyf7WKd58HEkR2KRZkOaM";
}
interface GoogleBilling {
public static final String LICENSE_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg4Ezun7ud/7mEBzvDNy4gSW7F/4SyXOPMtWhFheTPohfe7CqngjwBXGilZ4TbPIqu9tC6lBYTkNcytIQA/QCuE1ireJ0GficsZiUu/jQvTeou/Cq336B3GGWJ0CEv9cLxDHwhh+ZOQAR46E6UtVQL+QKr4WCyEmpg7Gf+08F3AqeJBlYKcaNyHMIV/7SZkRVlk8VcbVlJBkfuJrehbmYfbdi8gQxfkpBBcLlWB3sPSfYz0Fw6cKO9V2V5syD1VWyVOcsBPIWYYh8IG9/5iVAiJiL/LFndmf7gGMQq6CkhSCK+WCZb8Cw5Eo4ZU4ThUqrIifdJAnWkL4dyGbTMOOOtwIDAQAB";
}
/**********************************************
서비스 리턴 코드
==============
***********************************************/
interface ReturnCode {
public static final String SUCCESS = "0";
public static final String PARAM_ERROR = "1";
public static final String LOGIC_ERROR = "2";
public static final String SYSTEM_ERROR = "3";
public static final String AUTH_ERROR = "4";
public static final String OTHER_ERROR = "9";
}
/**********************************************
C2DM 메세지 타입
==============
***********************************************/
interface ActionType {
public static final String MSG = "msg"; //쪽지 메세지
public static final String CHAT_MSG = "chatMsg"; //실시간채팅 메세지
public static final String ROOM_IN_MSG = "roomInMsg"; //실시간채팅 입장시 보내지는 메세지
public static final String ROOM_OUT_MSG = "roomOutMsg"; //실시간채팅 퇴장시 보내지는 메세지
public static final String KICK_OUT_MSG = "kickOutMsg"; //강제 퇴장시 보내지는 메세지
public static final String TALK_MSG = "talkMsg"; //톡투미 댓글 알림 메세지
public static final String WINK_MSG = "winkMsg"; //윙크 수신알림 메세지
public static final String PASS_MSG = "passMsg"; //임시 패스워드 발급 메세지
public static final String GIFT_MSG = "giftMsg"; //윙크 수신알림 메세지
}
/**********************************************
회원 상태
==============
***********************************************/
interface MemberStatus {
public static final String ACTIVE = "A";
public static final String PROCESSING = "P";
public static final String CANCEL = "C";
}
interface FileExt {
public static final String JPEG = "jpg";
}
interface UploadFileUsageType {
public static final String MAIN_PHOTO = "mainPhoto";
public static final String SUB_PHOTO_01 = "subPhoto01";
public static final String SUB_PHOTO_02 = "subPhoto02";
public static final String SUB_PHOTO_03 = "subPhoto03";
public static final String SUB_PHOTO_04 = "subPhoto04";
public static final String SUB_PHOTO_05 = "subPhoto05";
public static final String SUB_PHOTO_06 = "subPhoto06";
public static final String SUB_PHOTO_07 = "subPhoto07";
public static final String SUB_PHOTO_08 = "subPhoto08";
}
interface MemberAttrName {
public static final String MAIN_PHOTO = "mainPhoto";
public static final String SUB_PHOTO_01 = "subPhoto01";
public static final String SUB_PHOTO_02 = "subPhoto02";
public static final String SUB_PHOTO_03 = "subPhoto03";
public static final String SUB_PHOTO_04 = "subPhoto04";
public static final String SUB_PHOTO_05 = "subPhoto05";
public static final String SUB_PHOTO_06 = "subPhoto06";
public static final String SUB_PHOTO_07 = "subPhoto07";
public static final String SUB_PHOTO_08 = "subPhoto08";
public static final String LAST_READ_NOTICE_ID = "lastReadNoticeId";
public static final String ONESELF_CERTIFICATION = "oneselfCertification";
public static final String LAST_LOGIN_DAY = "lastLoginDay";
public static final String PASS_EXPIRE_DAY = "passExpireDay";
}
interface ItemGroup {
public static final String POINT = "G00"; //포인트
public static final String MULTIPLE_USE_TICKET = "G01"; //정액권
public static final String WINK = "G02"; //윙크
public static final String GIFT = "G03"; //선물
}
interface ItemCode {
public static final String POINT = "T00000"; //포인트
public static final String PASS_1W = "T01001"; //정액권(1주일)
public static final String PASS_1M = "T01002"; //정액권(1달)
public static final String WINK = "T02001"; //윙크
public static final String GIFT_FLOWER = "T03001"; //꽃다발
}
interface CheckPlus {
public static final String SITE_CODE = "G1519";
public static final String SITE_PASSWD = "D5JD6GNBB2TB";
public static final String SUCCESS_RTN_URL = "/missingu/theshop/checkplus_success.html";
public static final String ERROR_RTN_URL = "/missingu/theshop/checkplus_error.html";
}
interface DaouPay {
public static final String CPID = "CTS10200";
public static final String SUCCESS_MSG = "SUCCESS";
public static final String FAIL_MSG = "FAIL";
public static final String HOMEURL = "/missingu/pay/orderComplete.html";
public static final String FAILURL = "/missingu/theshop/pointCharge.html";
public static final String CLOSEURL = "/missingu/theshop/pointCharge.html";
}
interface RequestURI {
public static final String CREATE_ROOM = "/missingu/chat/createRoom.html"; //채팅방 개설
public static final String ROOM_IN = "/missingu/chat/roomIn.html"; //채팅방 입장
public static final String SEND_MSG = "/missingu/msgbox/sendMsg.html"; //쪽지 보내기
public static final String OPEN_MSG = "/missingu/msgbox/openMsg.html"; //쪽지 개봉
public static final String SAVE_TALK = "/missingu/talktome/saveTalk.html"; //톡투미 글쓰기
public static final String SAVE_TALK_REPLY = "/missingu/talktome/saveTalkReply.html"; //톡투미 댓글달기
public static final String SEND_WINK = "/missingu/friends/sendWink.html"; //윙크 보내기
public static final String SEND_GIFT = "/missingu/friends/sendGift.html"; //윙크 보내기
public static final String LACK_OF_POINT_ERROR = "/missingu/common/lackOfPointError.html"; //포인트 부족
public static final String CONFIRM_TO_USE_POINT = "/missingu/common/confirmUsingPoint.html";//포인트 사용 컨펌
}
interface SexCode {
public static final String MALE = "G01001"; //남자
public static final String FEMALE = "G01002"; //여자
}
interface BloodTypeCode {
public static final String A = "B01001"; //남자
public static final String B = "B01002"; //남자
public static final String O = "B01003"; //남자
public static final String AB = "B01004"; //남자
}
interface EventTypeCd {
public static final String INCOME = "I"; //수입
public static final String OUTCOME = "O"; //지출
}
interface LunarSolarCd {
public static final String SOLAR = "A00101"; //양력
public static final String LUNAR = "A00102"; //음력(편달)
public static final String LUNAR_LEAP = "A00103"; //음력(윤달)
}
interface emailType {
public static final String MEMBERSHIP_JOIN_CONFIRM = "ET00001"; //회원가입 완료
public static final String TEMP_PASSWORD = "ET00002"; //임시 패스워드 발급
}
/**********************************************
궁합 천간코드
==============
***********************************************/
interface ChunganCd {
public static final String GAB = "C01"; //갑
public static final String EUL = "C02"; //을
public static final String BYOUNG = "C03"; //병
public static final String JUNG = "C04"; //정
public static final String MU = "C05"; //무
public static final String GI = "C06"; //기
public static final String KYUNG = "C07"; //경
public static final String SHIN = "C08"; //신
public static final String IM = "C09"; //임
public static final String GAE = "C10"; //계
}
/**********************************************
궁합 지지코드
==============
***********************************************/
interface JijiCd {
public static final String JA = "A01"; //자
public static final String CHOOK = "A02"; //축
public static final String IN = "A03"; //인
public static final String MYO = "A04"; //묘
public static final String JIN = "A05"; //진
public static final String SA = "A06"; //사
public static final String OH = "A07"; //오
public static final String ME = "A08"; //미
public static final String SHIN = "A09"; //신
public static final String YOO = "A10"; //유
public static final String SOOL = "A11"; //술
public static final String HAE = "A12"; //해
}
/**********************************************
궁합 타입
==============
***********************************************/
interface HarmonyType {
public static final String INNER = "inner"; //속궁합
public static final String OUTER = "outer"; //겉궁합
public static final String BLOOD = "blood"; //혈액형궁합
public static final String SIGN = "sign"; //띠궁합
}
/**********************************************
오행 코드
==============
***********************************************/
interface FiveElement {
public static final String MOK = "E01"; //목
public static final String WHA = "E02"; //화
public static final String TOU = "E03"; //토
public static final String GUM = "E04"; //금
public static final String SU = "E05"; //수
}
/**********************************************
MissingU Common Constant
==============
***********************************************/
public static final String AES_KEY = "0OKM9IJN8UHB7YGV";
public static final String IV_PARAMETER = "0OKM9IJN8UHB7YGV";
public static final byte[] AES_KEY_SYNC = new byte[] { 0x39, 0x4d, 0x38, 0x49, 0x37, 0x53, 0x36, 0x53, 0x35, 0x49, 0x34, 0x4e, 0x33, 0x47, 0x32, 0x55 };
public static final byte[] IV_PARAMETER_SYNC = new byte[] { 0x4d, 0x39, 0x49, 0x30, 0x53, 0x31, 0x53, 0x32, 0x49, 0x33, 0x4e, 0x34, 0x47, 0x35, 0x55, 0x36 };
public static final String YES = "Y";
public static final String NO = "N";
public static final String URL_SUFFIX = "Url";
//public static final String APK_SAVE_PATH = "/opt/lampp/tomcat60/files/apk/";
//public static final String APPLICATION_ROOT_PATH = "/opt/lampp/tomcat60/webapps/ROOT";
public static final String PR_IMAGE_SAVE_PATH = "/files/profile";
public static final String TALK_IMG_SAVE_PATH = "/files/talktome";
public static final String MANTOMAN_IMG_SAVE_PATH = "/files/mantoman";
public static final String MISSIONMATCH_IMG_SAVE_PATH = "/files/mission";
public static final String ORIGINAL_IMAGE_SUFFIX = "org";
public static final String BIG_IMAGE_SUFFIX = "big";
}
|
package ca.mohawk.jdw.shifty.companyapi.model;
/*
I, Josh Maione, 000320309 certify that this material is my original work.
No other person's work has been used without due acknowledgement.
I have not made my work available to anyone else.
Module: company-api
Developed By: Josh Maione (000320309)
*/
public interface Model {
long id();
}
|
package com.cnk.travelogix.sapintegrations.chargeable.itemcharging.data;
import javax.xml.bind.annotation.XmlElement;
public class ChargingOutputContextData
{
@XmlElement(defaultValue = "true")
protected Boolean chargeableItemExported;
/**
* Gets the value of the chargeableItemExported property.
*
* @return possible object is {@link Boolean }
*
*/
public Boolean isChargeableItemExported()
{
return chargeableItemExported;
}
/**
* Sets the value of the chargeableItemExported property.
*
* @param value
* allowed object is {@link Boolean }
*
*/
public void setChargeableItemExported(final Boolean value)
{
this.chargeableItemExported = value;
}
}
|
package MultidimensionalArrays;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MatrixRotation {
public static void main(String[] args) throws IOException {
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
int angle = Integer.parseInt(buffer.readLine().replaceAll("[A-Za-z()]+", "")) % 360;
String input;
int maxLength = -1;
List<String> inputLines = new ArrayList<>();
while (!"END".equals(input = buffer.readLine())) {
inputLines.add(input);
if (input.length() > maxLength) {
maxLength = input.length();
}
}
char[][] matrix = new char[inputLines.size()][maxLength];
for (int i = 0; i < inputLines.size(); i++) {
for (int j = 0; j < maxLength; j++) {
if (j < inputLines.get(i).length()) {
matrix[i][j] = inputLines.get(i).charAt(j);
}else {
matrix[i][j] = ' ';
}
}
}
matrix = matrixRotation(matrix, angle);
for (char[] chars : matrix) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.print(chars[j]);
}
System.out.println();
}
}
private static char[][] matrixRotation(char[][] matrix, int angle) {
char[][] rotatedMatrix = new char[matrix[0].length][matrix.length];
int rows = rotatedMatrix.length;
int cols = rotatedMatrix[0].length;
switch (angle) {
case 90:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
rotatedMatrix[i][j] = matrix[rotatedMatrix[0].length - 1 - j][i];
}
}
break;
case 180:
rotatedMatrix = new char[matrix.length][matrix[0].length];
rows = rotatedMatrix.length;
cols = rotatedMatrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
rotatedMatrix[i][j] = matrix[matrix.length - 1 - i][matrix[0].length - 1 - j];
}
}
break;
case 270:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
rotatedMatrix[i][j] = matrix[j][matrix[0].length - 1 - i];
}
}
break;
default:
rotatedMatrix = matrix;
break;
}
return rotatedMatrix;
}
}
|
package com.xiaoxiao.search.pojo;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_final_blogs
* @date:2019/12/13:15:07
* @author:shinelon
* @Describe: 检索数据的实体类
*/
@Data
public class SolrArticleDocument implements Serializable
{
/**
* 必要属性 是在Solr检索器内的ID
*/
private String id;
private Long article_id;
private Long user_id;
private Long article_views;
private Long article_comment_count;
private Long article_like_count;
private Long article_bk_sorts_id;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date article_date;
private String article_bk_first_img;
private String article_recommend;
private String user_profile_photo;
private String user_nickname;
private String article_title;
private String article_desc;
private String article_type;
}
|
package com.wonders.task.htxx.dao.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.wonders.task.htxx.dao.DwContractAssignStatsDao;
import com.wonders.task.htxx.model.bo.DwContractAssignStats;
@Repository("dwContractAssignStatsDao")
public class DwContractAssignStatsDaoImpl implements DwContractAssignStatsDao {
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
@Resource(name="hibernateTemplate")
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
@Override
public DwContractAssignStats findByContractTypeAndAssignTypeAndControlDate(String contractType, String assignType,String controlDate, String companyId) {
String hql ="from DwContractAssignStats t where t.contractType='"+contractType+"' and t.assignType='"+assignType+"'" +
" and t.controlDate='"+controlDate+"'";
if(companyId!=null && !"".equals(companyId)){
hql += " and t.controlCompanyId='"+companyId+"'";
}
List<DwContractAssignStats> list = hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(hql).setMaxResults(1).list();
if(list==null || list.size()<1) return null ;
return list.get(0);
}
@Override
public void saveOrUpdateAll(List<DwContractAssignStats> dwContractAssignStatusList) {
this.getHibernateTemplate().saveOrUpdateAll(dwContractAssignStatusList);
}
}
|
package com.tencent.mm.ui.contact;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.bg.d;
import com.tencent.mm.sdk.platformtools.x;
class k$4 implements OnClickListener {
final /* synthetic */ k ujC;
k$4(k kVar) {
this.ujC = kVar;
}
public final void onClick(View view) {
x.d("MicroMsg.FMessageContactView", "initNoNew, goto FMessageConversationUI");
d.b(k.d(this.ujC), "subapp", ".ui.friend.FMessageConversationUI", new Intent());
}
}
|
package com.tt.miniapp.navigate2;
import android.text.TextUtils;
import com.tt.miniapphost.entity.AppInfoEntity;
import com.tt.miniapphost.util.JsonBuilder;
import org.json.JSONObject;
public class Nav2Util {
private static JSONObject buildReferer(AppInfoEntity paramAppInfoEntity) {
String str;
if (paramAppInfoEntity == null) {
paramAppInfoEntity = null;
} else {
str = paramAppInfoEntity.refererInfo;
}
return (new JsonBuilder(str)).build();
}
public static JSONObject getReferer(AppInfoEntity paramAppInfoEntity) {
JSONObject jSONObject = buildReferer(paramAppInfoEntity);
if (jSONObject.has("__origin_wg_or_app"))
jSONObject.remove("__origin_wg_or_app");
return jSONObject;
}
public static void initRefererInfo(AppInfoEntity paramAppInfoEntity, String paramString) {
boolean bool = TextUtils.equals(paramAppInfoEntity.launchFrom, "in_mp");
JSONObject jSONObject = null;
if (!bool && !TextUtils.equals(paramAppInfoEntity.launchFrom, "back_mp")) {
paramAppInfoEntity.refererInfo = null;
return;
}
paramAppInfoEntity.refererInfo = paramString;
if (!TextUtils.isEmpty(paramString)) {
String str1;
JSONObject jSONObject1 = (new JsonBuilder(paramString)).build();
String str2 = jSONObject1.optString("appId");
if (!TextUtils.isEmpty(str2))
paramAppInfoEntity.bizLocation = str2;
JSONObject jSONObject2 = jSONObject1.optJSONObject("extraData");
jSONObject1 = jSONObject;
if (jSONObject2 != null)
str1 = jSONObject2.optString("location");
if (!TextUtils.isEmpty(str1))
paramAppInfoEntity.location = str1;
}
}
public static boolean isOriginWhiteGame(AppInfoEntity paramAppInfoEntity) {
return (paramAppInfoEntity == null) ? false : buildReferer(paramAppInfoEntity).optBoolean("__origin_wg_or_app", false);
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\navigate2\Nav2Util.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package eg.ipvii.fotp.items;
import com.teamwizardry.librarianlib.features.base.item.ItemMod;
import eg.ipvii.fotp.FotPMod;
import net.minecraft.item.ItemStack;
public class ItemMortarandPestle extends ItemMod {
protected String name;
public ItemMortarandPestle(String name) {
super(name);
this.name = name;
setCreativeTab(FotPMod.FotPCreativeTab);
this.maxStackSize = 1;
}
@Override
public ItemStack getContainerItem(ItemStack stack) {
return stack.copy();
}
}
|
package xframe.example.pattern.observer;
public class Main {
public static void main(String[] args) {
Observable subject = new ContreteObservable();
Observer observer1 = new ContreteObserver();
Observer observer2 = new ContreteObserver();
Observer observer3 = new ContreteObserver();
subject.add(observer1);
subject.add(observer2);
subject.add(observer3);
subject.setChanged();
subject.notifyObservers(null);
System.out.println(observer1.toString());
System.out.println(observer2.toString());
System.out.println(observer3.toString());
}
}
|
package WorldMPowered;
public class SchoolInterface {
public static void main(String[] args) {
}
}
|
package com.ysyt.bean;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.constants.CommonConstants;
import com.ysyt.wrapper.AmenitiesWrapper;
@Entity
@Table(name = "attribute_master", schema = CommonConstants.SCHEMA)
public class AttributesMaster extends AmenitiesWrapper implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id", columnDefinition = "serial")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="title")
private String title;
@Column(name="description")
private String description;
@Column(name="is_amenities")
private Boolean isAmenities;
@Column(name="is_deleted",nullable = false ,insertable=false, columnDefinition = "boolean default false")
private Boolean isDeleted;
@Column(name="parent_id")
private Long parentId;
@Column(name="logo_path")
private Long logoPath;
@OneToOne(fetch = FetchType.EAGER,targetEntity = Uploads.class, cascade = CascadeType.ALL)
@JoinColumn(name = "logo_path", referencedColumnName = "id",insertable=false ,updatable=false)
private Uploads logoDetails;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getIsAmenities() {
return isAmenities;
}
public void setIsAmenities(Boolean isAmenities) {
this.isAmenities = isAmenities;
}
public Boolean getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Boolean isDeleted) {
this.isDeleted = isDeleted;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public Long getLogoPath() {
return logoPath;
}
public void setLogoPath(Long logoPath) {
this.logoPath = logoPath;
}
public Uploads getLogoDetails() {
return logoDetails;
}
public void setLogoDetails(Uploads logoDetails) {
this.logoDetails = logoDetails;
}
}
|
package com.mundo.core.util;
import org.junit.Test;
/**
* JsonUtilTest
*
* @author maodh
* @since 2018/1/6
*/
public class JsonUtilTest {
@Test
public void toMap() {
System.out.println(JsonUtil.toMap("{\"key\":\"value\"}").getClass());
}
@Test
public void toList() {
System.out.println(JsonUtil.toList("[1,2]").getClass());
}
@Test
public void toSet() {
System.out.println(JsonUtil.toSet("[1,2]").getClass());
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package polarpelican.graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
*
* @author parker
*/
public class Cursor implements Renderable {
final BufferedImage myCursor;
public Cursor() throws IOException
{
myCursor = ImageIO.read(new File("Cursor.png"));
}
@Override
public void render(Graphics2D g, int x, int y) {
g.drawImage(myCursor, x, y, null);
}
}
|
import java.util.TreeMap;
public class replacemap {
public static void main(String[] args) {
TreeMap<String, Integer> mt = new TreeMap<String, Integer>();
mt.put("b",04);
mt.put("i",14);
mt.put("n",24);
mt.put("d",34);
mt.put("u",44);
mt.replace("u",54);
System.out.println(mt);
}
}
|
package com.pro.mongo.service.impl;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import com.mongodb.client.result.DeleteResult;
import com.pro.mongo.service.GuestbookService;
import com.pro.mongo.vo.GuestbookVO;
import com.pro.mongo.vo.MongoUserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
@RequiredArgsConstructor
public class GuestbookServiceImpl implements GuestbookService {
private final MongoTemplate mongo;
@Override
public List<String> userList(String id) {
Query query = new Query(Criteria.where("user_id").ne(id));
List<Map> userList = mongo.find(query, Map.class, "users");
List<String> result = new ArrayList<String>();
result.add(id);
for(Map user : userList) {
result.add((String)user.get("user_id"));
}
return result;
}
@Override
public List<GuestbookVO> guestbookList(String id) {
Query query = new Query(Criteria.where("owner").is(id));
query.with(Sort.by(Sort.Direction.DESC, "_id"));
List<GuestbookVO> result = mongo.find(query ,GuestbookVO.class, "guestbook");
for(GuestbookVO guestbook : result) {
guestbook.setObjectId((guestbook.get_id()).toString());
}
return result;
}
@Override
public int addGuestbook(String sender, Map<String, Object> params) {
GuestbookVO vo = new GuestbookVO();
vo.set_id(new ObjectId());
vo.setObjectId(vo.get_id().toString());
vo.setOwner((String) params.get("owner"));
vo.setSend_user(sender);
vo.setSend_content((String) params.get("send_content"));
vo.setSend_dttm(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
GuestbookVO result = mongo.insert(vo, "guestbook");
return result.getObjectId().length();
}
@Override
public Map<String, Object> addGuestbookComments(String sender, Map<String, Object> params) {
params.put("send_user", sender);
params.put("send_dttm", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
Query query = new Query(Criteria.where("_id").is(new ObjectId( (String) params.get("objid") )));
params.put("objid", new ObjectId().toString());
Update update = new Update().addToSet("comments", params);
GuestbookVO result = mongo.findAndModify(query, update, GuestbookVO.class, "guestbook");
params.put("result", result);
return params;
}
@Override
public DeleteResult deleteGuestbook(String params){
Query query = new Query(Criteria.where("_id").is(new ObjectId(params)));
DeleteResult msg = mongo.remove(query, "guestbook");
return msg;
}
}
|
public class POOBase2
{
public static void main( String[] args )
{
// L'objectif :
// Créer un tableau 't' de 5 personnes
// Trier ce tableau par codePostal
// déclaration : TYPE_VARIABLE NOM_VARIABLE
// TYPE_VARIABLE : tableau de Personne: Personne[]
// Personne[] t = new Personne[5];
// t[0] = new Personne( "titi", "titi", 44000 );
// t[1] = new Personne( "areazarez", "titi", 44022 );
// t[2] = new Personne( "mnlknhmlnk", "titi", 41100 );
// t[3] = new Personne( "fsfzzz", "titi", 44007 );
// t[4] = new Personne( "VFEZFE", "titi", 14000 );
// en utilisant la syntaxe suivante
// int[] ti = new int[] { 12, 14, 6, 2, 9, 123 };
Personne[] t = new Personne[] {
new Personne( "titi", "titi", 44100 ),
new Personne( "areazarez", "titi", 44022 ),
new Personne( "mnlknhmlnk", "titi", 41100 ),
new Personne( "fsfzzz", "titi", 44007 ),
new Personne( "VFEZFE", "titi", 14000 )
};
t = trier( t );
for( int i = 0; i < t.length; i++ )
t[i].affichePersonne();
}
static Personne[] trier( Personne[] tableau )
{
if( tableau.length <= 1 )
return tableau;
// couper tableau en deux
int indexMoitie = tableau.length / 2;
Personne[] moitieUn = extraire( tableau, 0, indexMoitie );
Personne[] moitieDeux = extraire( tableau, indexMoitie, tableau.length );
// trier chaque moitie
moitieUn = trier( moitieUn );
moitieDeux = trier( moitieDeux );
// raseembler les deux moitié
return rassembler( moitieUn, moitieDeux );
}
static Personne[] rassembler( Personne[] moitieUn, Personne[] moitieDeux )
{
int i1 = 0;
int i2 = 0;
Personne[] resultat = new Personne[moitieUn.length + moitieDeux.length];
for( int iR = 0; iR < resultat.length; iR++ )
{
if( i2 == moitieDeux.length
|| (i1 < moitieUn.length
&& moitieUn[i1].getCodePostal() < moitieDeux[i2].getCodePostal()) )
{
resultat[iR] = moitieUn[i1++];
}
else
{
resultat[iR] = moitieDeux[i2++];
}
}
return resultat;
}
static Personne[] extraire( Personne[] tableau, int debut, int fin )
{
int taille = fin - debut;
Personne[] resultat = new Personne[taille];
for( int i = 0; i < taille; i++ )
resultat[i] = tableau[i + debut];
return resultat;
}
}
|
package com.muaki.muakibooks;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
private static String LOGTAG = "MuakiMain";
private InitTask initTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTask = new InitTask();
initTask.execute(this);
}
private void metodoParaBaixarZip() {
String path ="http://www.muaki.com/muakibooks/vintemegas.zip";
String targetFileName = "/muakibooks/contodavaca/contodavaca.zip";
boolean eof = false;
Log.i(MainActivity.LOGTAG,"yuju tamos aqui ");
File directory = new File(Environment.getExternalStorageDirectory()
+ File.separator + "muakibooks" + File.separator + "contodavaca");
directory.mkdirs();
try {
FileOutputStream destinationFile = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ targetFileName);
URL u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
destinationFile.write(buffer,0, len1);
}
destinationFile.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
protected class InitTask extends AsyncTask<Context, Integer, String> {
@Override
protected String doInBackground(Context... arg0) {
metodoParaBaixarZip();
return null;
}
}
}
|
//Problem:543. Diameter of Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
if(root == null)
return 0;
findDia(root);
return max-1;
}
int findDia(TreeNode node)
{
if(node == null)
return 0;
int left = 1 + findDia(node.left);
int right = 1 + findDia(node.right);
int m = left + right - 1;
if(m > max)
{
max = m;
}
return left > right ? left : right;
}
}
|
package blockchain.block;
import blockchain.block.data_points.InsufficientFundsException;
import blockchain.block.data_points.StorageContract;
import blockchain.block.data_points.TokenTransaction;
import blockchain.block.mining.BlockBuilder;
import blockchain.ledger_file.ChainAnalyzer;
import blockchain.ledger_file.LedgerReader;
import blockchain.ledger_file.LedgerWriterReaderTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.nio.file.Paths;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
public class BlockBuilderTest {
private static final String minerID = "User1";
private static final String filePath = "CoinTransaction.dat";
private static LedgerReader ledgerReader;
private static final int blockCount = 5;
@BeforeAll
static void setup() {
// Generate and save 5 random blocks mined by userOne
ledgerReader = new LedgerReader(Paths.get(filePath));
LedgerWriterReaderTest.saveRandomBlocks(Paths.get(filePath), blockCount, minerID);
}
@Test // Tests that an empty block can be built and mined correctly
public void emptyBlockBuildTest() {
LedgerReader reader = new LedgerReader(LedgerWriterReaderTest.getEmptyPath());
Block block = new BlockBuilder(reader).build("1");
assertTrue(ChainAnalyzer.isBlockValid(block, reader));
}
@Test
// Tests that a transaction cannot be added when the user does not have sufficient funds
void transactionInsufficientFundsTest() {
BlockBuilder blockBuilder = new BlockBuilder(ledgerReader);
// Create transaction from user who doesn't have sufficient funds
TokenTransaction transaction = new TokenTransaction(minerID, minerID, BlockBuilder.miningReward * blockCount + 1.0);
Executable insufficientFundsTransaction = () -> blockBuilder.addData(transaction);
// Attempt to add the invalid transaction
assertThrows(InsufficientFundsException.class, insufficientFundsTransaction);
}
@Test
// Tests that a transaction can be added when the user does have sufficient funds
void transactionSufficientFundsTest() {
BlockBuilder blockBuilder = new BlockBuilder(ledgerReader);
// Create transaction from user who has sufficient funds
TokenTransaction transaction = new TokenTransaction(minerID, "2", BlockBuilder.miningReward * blockCount);
try {
// Add transaction to builder
blockBuilder.addData(transaction);
} catch (InsufficientFundsException e) {
// Fail if an InsufficientFundsException is thrown
e.printStackTrace();
fail("User with sufficient funds could not complete transaction");
}
}
@Test
// Tests that a contract cannot be added when the user does not have sufficient funds
void contractInsufficientFundsTest() {
BlockBuilder blockBuilder = new BlockBuilder(ledgerReader);
// Create transaction from user who doesn't have sufficient funds
StorageContract contract = new StorageContract("file.format", minerID, minerID,
0, BlockBuilder.miningReward * blockCount + 1.0);
// Attempt to add the invalid transaction
Executable insufficientFundsTransaction = () -> blockBuilder.addData(contract);
assertThrows(InsufficientFundsException.class, insufficientFundsTransaction);
}
@Test
// Tests that a contract can be added when the user does have sufficient funds
void contractSufficientFundsTest() {
BlockBuilder blockBuilder = new BlockBuilder(ledgerReader);
// Create transaction with reward corresponding to user one's funds
StorageContract contract = new StorageContract("file.format", minerID, minerID,
0, BlockBuilder.miningReward * blockCount);
try {
// Add contract to builder
blockBuilder.addData(contract);
} catch (InsufficientFundsException e) {
// Fail if an InsufficientFundsException is thrown
e.printStackTrace();
fail("User with sufficient funds could not complete transaction");
}
}
}
|
package com.test;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
public class MySQLLite2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
//建立資料庫
//SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase("/data/data/com.freejavaman/mydb.db", null);
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase("/sdcard/mydb.db", null);
//查詢所有資料
Cursor cursor = db.query("passenger", null, null, null, null, null, null);
//db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
//移到第一筆資料
Log.v("sql", "cursor.getCount():" + cursor.getCount());
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(1);
String addr = cursor.getString(2);
//顯示在Log之中
Log.v("sql", "name:" + name + ", addr:" + addr);
} while (cursor.moveToNext());
}//if (cursor.moveToFirst()) ends
} catch (Exception e) {
Log.e("sql", "error(2):" + e);
}
}
}
|
module randomshuffling {
}
|
package br.com.unialfa.ia.core.heuristic.impl;
import br.com.unialfa.ia.core.heuristic.IBuscaCega;
import br.com.unialfa.ia.core.model.Grafo;
import br.com.unialfa.ia.core.model.Vertice;
public class BuscaEmLargura implements IBuscaCega {
@Override
public Grafo processarGrafo(Grafo grafo, Vertice origem) {
// TODO Auto-generated method stub
return null;
}
}
|
package com.socialbooks.jra.repository;
import com.socialbooks.jra.domain.Autor;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AutoresRepository extends JpaRepository<Autor, Long> {
Long existsAutorsByLivros_Autor_Id (long id);
boolean existsByLivros_AutorId(long id);
}
|
package com.github.arsentiy67.usereditor.userdetails;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
public class UserDetailsExt extends User {
private static final long serialVersionUID = -8315535273249007840L;
private Integer userId;
private String userTimeZone;
public UserDetailsExt(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired,
accountNonLocked, authorities);
}
public UserDetailsExt(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities, String userTimeZone, Integer userId) {
this(username, password, enabled, accountNonExpired, credentialsNonExpired,
accountNonLocked, authorities);
setUserTimeZone(userTimeZone);
setUserId(userId);
}
public String getUserTimeZone() {
return userTimeZone;
}
public void setUserTimeZone(String userTimeZone) {
this.userTimeZone = userTimeZone;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
}
|
package io.beaniejoy.bootapiserver.service;
import io.beaniejoy.bootapiserver.model.Movie;
import io.beaniejoy.bootapiserver.repository.MovieRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class MovieService {
private final MovieRepository movieRepository;
public void setMovie(String id, String movie) {
movieRepository.setMovie(id, movie);
}
public String getMovie(String id) {
return movieRepository.getMovie(id);
}
}
|
/*
* YNAB API Endpoints
* Our API uses a REST based design, leverages the JSON data format, and relies upon HTTPS for transport. We respond with meaningful HTTP response codes and if an error occurs, we include error details in the response body. API Documentation is at https://api.youneedabudget.com
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package ynab.client.api;
import ynab.client.invoker.ApiException;
import ynab.client.model.ErrorResponse;
import ynab.client.model.ScheduledTransactionResponse;
import ynab.client.model.ScheduledTransactionsResponse;
import java.util.List;
import org.junit.Test;
import org.junit.Ignore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for ScheduledTransactionsApi
*/
@Ignore
public class ScheduledTransactionsApiTest {
private final ScheduledTransactionsApi api = new ScheduledTransactionsApi();
/**
* Single scheduled transaction
*
* Returns a single scheduled transaction
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getScheduledTransactionByIdTest() throws ApiException {
String budgetId = null;
String scheduledTransactionId = null;
ScheduledTransactionResponse response = api.getScheduledTransactionById(budgetId, scheduledTransactionId);
// TODO: test validations
}
/**
* List scheduled transactions
*
* Returns all scheduled transactions
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getScheduledTransactionsTest() throws ApiException {
String budgetId = null;
ScheduledTransactionsResponse response = api.getScheduledTransactions(budgetId);
// TODO: test validations
}
}
|
package com.simha.SpringJPADemoForQueryResults;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
class Employees {
private int id;
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
private String name;
private String address;
public Employees(int id, String name, String address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
}
public class OptionalTest {
public static Employees findEmploye(List<Employees> listemp, String name) throws Exception {
return listemp.stream().filter(emp->emp.getName().equals(name)).findAny().orElseThrow(()->new Exception("name not found in our DB"));
}
public static void main(String[] args) throws Exception {
Employees emp = new Employees(102, "james", "Hyd");
Employees emp1 = new Employees(102, "Steve", "Hyd");
List<Employees> listOfEmp = new ArrayList<Employees>();
listOfEmp.add(emp);
listOfEmp.add(emp1);
Employees employee = findEmploye(listOfEmp, "james");
System.out.println(employee);
/*Optional<Object> opt = Optional.empty();
System.out.println(opt);
Optional<String> opts = Optional.ofNullable(emp.getName());
// System.out.println(opts.get());
Optional<String> optEmp = Optional.of(emp.getName());
// System.out.println(optEmp.get());
*/
}
}
|
package me.brunosantana.notes.filesystem;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileSystemHandler {
public boolean checkIfFileExists(String path) {
return Files.exists(Paths.get(path));
}
}
|
package com.mango.leo.zsproject.industrialservice.createrequirements.carditems;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.mango.leo.zsproject.R;
import com.mango.leo.zsproject.industrialservice.createrequirements.BusinessPlanActivity;
import com.mango.leo.zsproject.industrialservice.createrequirements.carditems.basecard.BaseCardActivity;
import com.mango.leo.zsproject.industrialservice.createrequirements.carditems.bean.CardFirstItemBean;
import com.mango.leo.zsproject.industrialservice.createrequirements.carditems.presenter.UpdateItemPresenter;
import com.mango.leo.zsproject.industrialservice.createrequirements.carditems.presenter.UpdateItemPresenterImpl;
import com.mango.leo.zsproject.industrialservice.createrequirements.carditems.view.UpdateItemView;
import com.mango.leo.zsproject.utils.AppUtils;
import com.mango.leo.zsproject.utils.DateUtil;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class CardFirstItemActivity extends BaseCardActivity implements UpdateItemView {
@Bind(R.id.imageView1_back)
ImageView imageView1Back;
@Bind(R.id.item_title)
EditText itemTitle;
@Bind(R.id.item_content)
EditText itemContent;
/* @Bind(R.id.recycler)
RecyclerView recyclerView;*/
@Bind(R.id.button1_save)
Button button1Save;
@Bind(R.id.item_danweiName)
EditText itemDanweiName;
@Bind(R.id.item_money)
EditText itemMoney;
@Bind(R.id.textView_num)
TextView textViewNum;
/* private int themeId;
GridImageAdapter adapter;
private List<LocalMedia> selectList = new ArrayList<>();*/
private CardFirstItemBean cardFirstItemBean;
// private List<LocalMedia> itemImagesPath = new ArrayList<>();
private UpdateItemPresenter updateItemPresenter;
public static final int TYPE1 = 1;
private CardFirstItemBean bean1;
private int num = 200;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_first_item);
ButterKnife.bind(this);
//themeId = R.style.picture_default_style;
//initAddImage();
editeNum();
updateItemPresenter = new UpdateItemPresenterImpl(this);
cardFirstItemBean = new CardFirstItemBean();
EventBus.getDefault().register(this);
Log.v("ffffffff","----1"+getIntent().getBooleanExtra("DemandManagementFragment", false));
}
private void editeNum() {
itemContent.addTextChangedListener(new TextWatcher() {
private CharSequence temp;
private int selectionStart;
private int selectionEnd;
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
temp = charSequence;
}
@Override
public void afterTextChanged(Editable editable) {
int number = num - editable.length();
textViewNum.setText("剩余" + number + "字");
selectionStart = itemContent.getSelectionStart();
selectionEnd = itemContent.getSelectionEnd();
if (temp.length() > num) {
editable.delete(selectionStart - 1, selectionEnd);
int tempSelection = selectionEnd;
itemContent.setText(editable);
itemContent.setSelection(tempSelection);//设置光标在最后
}
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void card1EventBus(CardFirstItemBean bean) {
bean1 = bean;
itemTitle.setText(bean.getItemName());
itemDanweiName.setText(bean.getDepartmentName());
itemMoney.setText(bean.getMoney());
itemContent.setText(bean.getItemContent());
/* adapter.setList(bean.getItemImagePath());
if (bean.getItemImagePath() != null) {
selectList = bean.getItemImagePath();
}*/
//cardFirstItemBean.setProjectId(bean.getProjectId());
}
private void initDate() {
cardFirstItemBean.setItemName(itemTitle.getText().toString());
cardFirstItemBean.setDepartmentName(itemDanweiName.getText().toString());
cardFirstItemBean.setMoney(itemMoney.getText().toString());
cardFirstItemBean.setItemContent(itemContent.getText().toString());
cardFirstItemBean.setTime(DateUtil.getCurDate("yyyy-MM-dd"));
/* if (selectList != null) {
cardFirstItemBean.setItemImagePath(selectList);
}*/
}
/* private void initAddImage() {
FullyGridLayoutManager manager = new FullyGridLayoutManager(CardFirstItemActivity.this, 4, GridLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(manager);
adapter = new GridImageAdapter(CardFirstItemActivity.this, onAddPicClickListener);
adapter.setList(selectList);
adapter.setSelectMax(5);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position, View v) {
if (selectList.size() > 0) {
LocalMedia media = selectList.get(position);
String pictureType = media.getPictureType();
int mediaType = PictureMimeType.pictureToVideo(pictureType);
switch (mediaType) {
case 1:
// 预览图片 可自定长按保存路径
//PictureSelector.create(MainActivity.this).themeStyle(themeId).externalPicturePreview(position, "/custom_file", selectList);
PictureSelector.create(CardFirstItemActivity.this).themeStyle(themeId).openExternalPreview(position, selectList);
break;
case 2:
// 预览视频
PictureSelector.create(CardFirstItemActivity.this).externalPictureVideo(media.getPath());
break;
case 3:
// 预览音频
PictureSelector.create(CardFirstItemActivity.this).externalPictureAudio(media.getPath());
break;
}
}
}
});
}
private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
@Override
public void onAddPicClick() {
// 进入相册 以下是例子:不需要的api可以不写
PictureSelector.create(CardFirstItemActivity.this)
.openGallery(PictureMimeType.ofAll())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
.theme(themeId)// 主题样式设置 具体参考 values/styles 用法:R.style.picture.white.style
.maxSelectNum(5)// 最大图片选择数量
.minSelectNum(1)// 最小选择数量
.imageSpanCount(4)// 每行显示个数
.selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
.previewImage(false)// 是否可预览图片
.previewVideo(false)// 是否可预览视频
.enablePreviewAudio(false) // 是否可播放音频
.isCamera(true)// 是否显示拍照按钮
.isZoomAnim(true)// 图片列表点击 缩放效果 默认true
//.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
//.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
.enableCrop(false)// 是否裁剪
.compress(false)// 是否压缩
.synOrAsy(true)//同步true或异步false 压缩 默认同步
//.compressSavePath(getPath())//压缩图片保存地址
//.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
.glideOverride(160, 160)// glide 加载宽高,越小图片列表越流畅,但会影响列表图片浏览的清晰度
.withAspectRatio(3, 4)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
.hideBottomControls(false)// 是否显示uCrop工具栏,默认不显示
.isGif(false)// 是否显示gif图片
.freeStyleCropEnabled(false)// 裁剪框是否可拖拽
.circleDimmedLayer(false)// 是否圆形裁剪
.showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
.showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
.openClickSound(false)// 是否开启点击声音
.selectionMedia(selectList)// 是否传入已选图片
//.isDragFrame(false)// 是否可拖动裁剪框(固定)
// .videoMaxSecond(15)
// .videoMinSecond(10)
//.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
//.cropCompressQuality(90)// 裁剪压缩质量 默认100
.minimumCompressSize(100)// 小于100kb的图片不压缩
//.cropWH()// 裁剪宽高比,设置如果大于图片本身宽高则无效
//.rotateEnabled(true) // 裁剪是否可旋转图片
//.scaleEnabled(true)// 裁剪是否可放大缩小图片
//.videoQuality()// 视频录制质量 0 or 1
//.videoSecond()//显示多少秒以内的视频or音频也可适用
//.recordVideoSecond()//录制视频秒数 默认60s
.forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
}
};*/
@OnClick({R.id.imageView1_back, R.id.textView_delete1, R.id.button1_save})
public void onViewClicked(View view) {
Intent intent = null;
switch (view.getId()) {
case R.id.imageView1_back:
Log.v("ffffffff","-o"+getIntent().getBooleanExtra("DemandManagementFragment", false));
if (getIntent().getBooleanExtra("DemandManagementFragment", false)) {
finish();
} else {
Log.v("ffffffff","----1");
intent = new Intent(this, BusinessPlanActivity.class);
startActivity(intent);
}
finish();
break;
case R.id.textView_delete1:
//updateItemPresenter.visitUpdateItem(this, TYPE1, bean1);//更新后台数据
//intent = new Intent(this, BusinessPlanActivity.class);
//startActivity(intent);
//finish();
itemTitle.setText("");
itemDanweiName.setText("");
itemMoney.setText("");
itemContent.setText("");
break;
case R.id.button1_save:
initDate();
// Log.v("yyyyy","*****cardFirstItemBean*****"+cardFirstItemBean.getItemImagePath().get(0).getPath());
if (!TextUtils.isEmpty(itemMoney.getText().toString()) && !TextUtils.isEmpty(itemTitle.getText().toString()) && !TextUtils.isEmpty(itemContent.getText().toString()) && cardFirstItemBean != null) {
updateItemPresenter.visitUpdateItem(this, TYPE1, cardFirstItemBean);//更新后台数据
} else {
AppUtils.showSnackar(button1Save, "必填项不能为空!");
}
break;
}
}
/* @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case PictureConfig.CHOOSE_REQUEST:
// 图片选择结果回调
selectList = PictureSelector.obtainMultipleResult(data);
// 例如 LocalMedia 里面返回三种path
// 1.media.getPath(); 为原图path
// 2.media.getCutPath();为裁剪后path,需判断media.isCut();是否为true
// 3.media.getCompressPath();为压缩后path,需判断media.isCompressed();是否为true
// 如果裁剪并压缩了,已取压缩路径为准,因为是先裁剪后压缩的
adapter.setList(selectList);
adapter.notifyDataSetChanged();
break;
}
}
}*/
@Override
public void showUpdateStateView(final String string) {
if (string == "SAVE SUCCESS" || string == "UPDATE SUCCESS"){
runOnUiThread(new Runnable() {
@Override
public void run() {
AppUtils.showToast(getApplicationContext(), string);
saveOk();
}
});
}
if (string == "SAVE FAILURE" || string == "UPDATE FAILURE"){
runOnUiThread(new Runnable() {
@Override
public void run() {
AppUtils.showToast(getApplicationContext(), string);
saveErrorDialog();
}
});
}
}
public void saveOk(){
EventBus.getDefault().postSticky(cardFirstItemBean);
Intent intent = new Intent(this, BusinessPlanActivity.class);
startActivity(intent);
finish();
}
private void saveErrorDialog() {
final AlertDialog.Builder alert = new AlertDialog.Builder(CardFirstItemActivity.this);
alert.setTitle("项目基础描述");
alert.setMessage("保存失败,请检查网络是否连接?");
alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.create().show();
}
@Override
public void showUpdateFailMsg(final String string) {
runOnUiThread(new Runnable() {
@Override
public void run() {
AppUtils.showToast(getApplicationContext(), string);
saveErrorDialog();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
ButterKnife.unbind(this);
EventBus.getDefault().unregister(this);
}
/**
* 监听Back键按下事件,方法2:
* 注意:
* 返回值表示:是否能完全处理该事件
* 在此处返回false,所以会继续传播该事件.
* 在具体项目中此处的返回值视情况而定.
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
if (getIntent().getBooleanExtra("DemandManagementFragment", false)) {
//finish();
} else {
Log.v("ffffffff","----1");
Intent intent = new Intent(this, BusinessPlanActivity.class);
startActivity(intent);
}
finish();
return false;
}else {
return super.onKeyDown(keyCode, event);
}
}
}
|
package com.example.shopping.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.envers.Audited;
import org.hibernate.envers.RelationTargetAuditMode;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@EntityListeners(AuditingEntityListener.class)
@Audited
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
@Column(unique = true)
private String email;
private String password;
@CreatedDate
private LocalDateTime createdDate;
@CreatedBy
private String createdBy;
@LastModifiedDate
private LocalDateTime lastModifiedDate;
@LastModifiedBy
private String lastModifiedBy;
@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
@ManyToMany(cascade = { CascadeType.MERGE, CascadeType.PERSIST }, fetch = FetchType.LAZY)
@JoinTable(name = "user_roles", joinColumns = { @JoinColumn(name = "user_id")},
inverseJoinColumns = @JoinColumn(name = "role_id"))
@JsonIgnore
private List<Role> roles;
}
|
/*
* Copyright (c) 2019 Snowflake Computing Inc. All rights reserved.
*/
package net.snowflake.client.core;
import static net.snowflake.client.core.SFException.errorResourceBundleManager;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.snowflake.client.jdbc.ErrorCode;
import net.snowflake.client.jdbc.SnowflakeConnectionV1;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Assert;
import org.junit.Test;
public class IncidentIT extends BaseIncidentTest {
// Copied from StringLimiter in GS
private static int countLines(String input) {
if (input == null || input.isEmpty()) {
return 0;
}
int lines = 1;
Matcher m = Pattern.compile("(\r\n)|(\r)|(\n)").matcher(input);
while (m.find()) {
lines++;
}
return lines;
}
/** Create an incident from pieces, explicit signature */
@Test
public void SimpleIncidentCreationTestExplicit() {
// Constants
String jobId = "ji";
String requestId = "ri";
String raiser =
"net.snowflake.client.core.IncidentIT$"
+ "CreateIncidentTests.SimpleIncidentCreationTestExpliciit";
String errorMessage = "error Message";
String errorStackTrace = "this is a stack element\nthis is another " + "element";
Incident incident =
new Incident(new SFSession(), jobId, requestId, errorMessage, errorStackTrace, raiser);
Assert.assertEquals(jobId, incident.jobId);
Assert.assertEquals(requestId, incident.requestId);
Assert.assertTrue(incident.signature.startsWith(errorMessage + " at " + raiser));
Assert.assertEquals(errorMessage, incident.errorMessage);
Assert.assertEquals(errorStackTrace, incident.errorStackTrace);
Assert.assertNotNull(incident.osName);
Assert.assertNotNull(incident.osVersion);
Assert.assertNotNull(incident.timestamp);
Assert.assertEquals(Event.EventType.INCIDENT, incident.getType());
}
/** Create an incident from a dummy RuntimeException */
@Test
@SuppressWarnings("ThrowableNotThrown")
public void SimpleIncidentCreationTestRuntimeException() {
// Constants
String jobId = "ji";
String requestId = "ri";
String errorMessage = "This is a test exception";
ErrorCode ec = ErrorCode.INTERNAL_ERROR;
SFException exc = new SFException(ec, errorMessage);
Incident incident = new Incident(new SFSession(), exc, jobId, requestId);
Assert.assertEquals("jdbc", incident.driverName);
Assert.assertNotNull(incident.driverVersion);
Assert.assertNotNull(incident.signature);
Assert.assertEquals(
errorResourceBundleManager.getLocalizedMessage(
String.valueOf(ec.getMessageCode()), errorMessage),
incident.errorMessage);
Assert.assertTrue(countLines(incident.errorStackTrace) > 1);
Assert.assertNotNull(incident.osName);
Assert.assertNotNull(incident.osVersion);
Assert.assertNotNull(incident.timestamp);
Assert.assertEquals(jobId, incident.jobId);
Assert.assertEquals(requestId, incident.requestId);
Assert.assertEquals(Event.EventType.INCIDENT, incident.getType());
}
/** Create an incident from a dummy RuntimeException */
@Test
@SuppressWarnings("ThrowableNotThrown")
public void VerifyUniqueUUIDTest() {
// Constants
String jobId = "ji";
String requestId = "ri";
String errorMessage = "This is a test exception";
SFException exc = new SFException(ErrorCode.INTERNAL_ERROR, errorMessage);
Incident incident1 = new Incident(new SFSession(), exc, jobId, requestId);
Incident incident2 = new Incident(new SFSession(), exc, jobId, requestId);
Assert.assertNotEquals(incident1.uuid, incident2.uuid);
}
/** Tests for triggering a client incident on GS */
@Test
public void simpleFlushTest() throws SQLException {
String jobId = "ji";
String requestId = "ri";
String errorMessage = RandomStringUtils.randomAlphabetic(5);
SFException exc = new SFException(ErrorCode.INTERNAL_ERROR, errorMessage);
String expected_signature =
errorMessage
+ ". at net.snowflake.client.core"
+ ".IncidentIT.simpleFlushTest(IncidentIT.java:";
Connection connection = getConnection();
Incident incident =
new Incident(
connection.unwrap(SnowflakeConnectionV1.class).getSfSession(), exc, jobId, requestId);
incident.trigger();
verifyIncidentRegisteredInGS(expected_signature, 1);
connection.close();
}
/** See if dump file is created by client */
@Test
public void testDumpFileCreated() throws Throwable {
String errorMessage = "testDumpFile" + RandomStringUtils.randomAlphabetic(5);
SFException exc = new SFException(ErrorCode.INTERNAL_ERROR, errorMessage);
Connection connection = getConnection();
Incident incident =
new Incident(
connection.unwrap(SnowflakeConnectionV1.class).getSfSession(), exc, "ji", "ri");
incident.trigger();
String dumpFile = findDmpFile(incident.signature);
File file = new File(dumpFile);
Assert.assertTrue(file.isFile());
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains(incident.signature)) {
scanner.close();
cleanUpDmpFile(dumpFile);
return;
}
}
Assert.fail("must find the signature");
}
/** Helper function to get dump file for an incident from GS */
private String findDmpFile(String signature) throws Throwable {
Connection connection = getConnection();
Statement statement = connection.createStatement();
String dpoScanString =
"select $1:\"WAIncidentDPO:primary\":\"summary\""
+ "from table(dposcan('{\"slices\" : [{\"name\" : \"WAIncidentDPO:primary\"}]}')) dpo "
+ "where $1:\"WAIncidentDPO:primary\":\"sourceErrorSignature\" = '"
+ signature
+ "'";
statement.execute(dpoScanString);
ResultSet resultSet = statement.getResultSet();
Assert.assertTrue(resultSet.next());
String summary = resultSet.getString(1);
connection.close();
ObjectMapper mapper = new ObjectMapper();
summary = (summary.substring(1, summary.length() - 1)).replace("\\", "");
JsonNode result = mapper.readValue(summary, JsonNode.class);
return result.path("dumpFile").asText();
}
/** Helper to clean up dump file */
private void cleanUpDmpFile(String dumpFile) {
// check if the file name format is what we expected
String regex = ".*/logs/gs_.*dmp";
Assert.assertTrue(dumpFile.matches(regex));
File file = new File(dumpFile);
Assert.assertTrue(file.isFile());
Assert.assertTrue(file.delete());
}
/** */
@Test
public void fullTriggerIncident() throws SQLException {
SFException exc =
new SFException(
ErrorCode.IO_ERROR,
"Mark Screwed something up again" + RandomStringUtils.randomAlphabetic(3));
Connection connection = getConnection();
SFSession session = connection.unwrap(SnowflakeConnectionV1.class).getSfSession();
Incident incident = new Incident(session, exc, null, null);
String signature = incident.signature;
try {
// This is how incidents should be raised from now on
throw (SFException) IncidentUtil.generateIncidentV2WithException(session, exc, null, null);
} catch (SFException ex) {
verifyIncidentRegisteredInGS(signature, 1);
} finally {
connection.close();
}
}
}
|
package com.jvmless.threecardgame.domain.player;
public interface PlayerRepository {
Player find(PlayerId playerId);
void save(Player player);
long countAll();
}
|
package yand.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yand.mapper.EmailMapper;
import yand.service.EmailService;
/**
*
* @author YanD
* 邮件处理逻辑
*/
@Service
public class EmailServiceImpl implements EmailService{
@Autowired
private EmailMapper emailMapper;
public List<Map<String, Object>> queryEmailList(String accept) {
// TODO Auto-generated method stub
return emailMapper.queryEmailList(accept);
}
}
|
// Leetcode problem number: 230. Kth Smallest Element in a BST
// Idea: Inorder traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class kBST {
public void doInorderTraversal(TreeNode root,List<Integer> qt)
{
if(root == null)
return;
doInorderTraversal(root.left,qt);
qt.add(root.val);
doInorderTraversal(root.right,qt);
}
public int kthSmallest(TreeNode root, int k)
{
List<Integer> qt = new ArrayList<Integer>();
doInorderTraversal(root,qt);
return qt.get(k-1);
}
}
|
package program1;
/**
*Provides properties and methods for the PresidentMDrvr class
*
*/
public class PresidentMDrvr
{
private Presidents[] myPresidents; //reference to array
private int numPresidents; // number of data items
/**
* Creates an object instance of the PresidentMDrvr class and initializes Presidents.
* @param maxSize The maximum number of presidents stored.
*/
public PresidentMDrvr(int maxSize)
{
myPresidents = new Presidents[maxSize];
numPresidents = 0;
} //end PresidentMDrvr()
/**
* Adds a president to the array
* @param president The president to add.
*/
public void add(Presidents president)
{
myPresidents[numPresidents++] = president;
} //end add()
/**
* Displays list of presidents and attributes.
*/
public void displayPresidents()
{
for (int i =0; i<myPresidents.length; i++)
System.out.println(myPresidents[i].toString());
} //end displayPresidents()
/**
* Sorts array by president name using bubble sort algorithm.
*/
public void sortByName()
{
for (int y=0; y<myPresidents.length;y++)
for(int x=0; x< myPresidents.length-1;x++)
if(myPresidents[x].getName().compareToIgnoreCase(myPresidents[x+1].getName()) > 0)
swap(x, x+1);
} // end sortByName()
/**
* Sorts array by president number(ascending) using bubble sort algorithm.
*/
public void sortByNumber()
{
for (int y=0; y<myPresidents.length;y++)
for(int x=0; x< myPresidents.length-1;x++)
if(myPresidents[x].getNumber() > myPresidents[x+1].getNumber())
swap(x, x+1);
} // end sortByNumber()
/**
* Swaps values between the two specified locations in an array.
* @param pos1 Position of first value to swap.
* @param pos2 position of second value to swap.
*/
private void swap(int pos1, int pos2)
{
Presidents temp = myPresidents[pos1];
myPresidents[pos1] = myPresidents[pos2];
myPresidents[pos2] = temp;
} // end swap()
/**
* Algorithm checks every position until it finds target value.
* @param search The string value to be searched.
*/
public void sequentialSearch(String search){
int count = 0;
boolean found = false;
for (int i=0; i<myPresidents.length; i++)
if(myPresidents[i].getParty().equals(search)){
count++;
found = true;
}
if (found == true)
System.out.format("%-20s\t\t%-30s%-30s%n", search, "Found", count);
else
System.out.format("%-20s\t\t%-30s%-30s%n", search, "Not Found", "- ");
} // end sequentialSearch()
/**
* Algorithm finds the position of the target value within a sorted array.
* @param searchKey The data representing array to be searched.
* @param currentTarget The position in the array.
* @return
*/
public int binarySearch(String[] searchKey, int currentTarget){
String searchString = searchKey[currentTarget];
int lowerBound = 0;
int upperBound = myPresidents.length-1;
int curIn;
int count = 0;
sortByName();
while(true)
{
curIn = (lowerBound + upperBound)/2;
if(myPresidents[curIn].getName().compareTo(searchString)==0){
count++;
System.out.format("%-20s\t\t%-30s%-30s%n", searchString, "Found", count);
return curIn;
}
else if(lowerBound > upperBound){
System.out.format("%-20s\t\t%-30s%-30s%n", searchString, "Not Found", count);
return curIn;
}
else
{
if((myPresidents[curIn].getName().compareTo(searchString)) < 0) {
lowerBound = curIn + 1;
}
else
upperBound = curIn - 1;
}// end else divide range
count++;
}
} // end binarySearch()
} // end PresidentMDrvr class
|
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.test.failurehandler.action;
import jdk.test.failurehandler.HtmlSection;
import jdk.test.failurehandler.value.InvalidValueException;
import jdk.test.failurehandler.value.SubValues;
import jdk.test.failurehandler.value.Value;
import jdk.test.failurehandler.value.ValueHandler;
import jdk.test.failurehandler.value.DefaultValue;
import java.io.PrintWriter;
import java.util.Properties;
public class SimpleAction implements Action {
/* package-private */ final String[] sections;
@Value(name = "javaOnly")
@DefaultValue(value = "false")
private boolean javaOnly = false;
@Value (name = "app")
private String app = null;
@Value (name = "args")
@DefaultValue (value = "")
/* package-private */ String[] args = new String[]{};
@SubValues(prefix = "params")
private final ActionParameters params;
public SimpleAction(String id, Properties properties)
throws InvalidValueException {
this(id, id, properties);
}
public SimpleAction(String name, String id, Properties properties)
throws InvalidValueException {
sections = name.split("\\.");
this.params = new ActionParameters();
ValueHandler.apply(this, properties, id);
}
public ProcessBuilder prepareProcess(PrintWriter log, ActionHelper helper) {
ProcessBuilder process = helper.prepareProcess(log, app, args);
if (process != null) {
process.redirectErrorStream(true);
}
return process;
}
@Override
public boolean isJavaOnly() {
return javaOnly;
}
@Override
public HtmlSection getSection(HtmlSection section) {
return section.createChildren(sections);
}
@Override
public ActionParameters getParameters() {
return params;
}
}
|
package de.madjosz.adventofcode.y2016;
import static org.junit.jupiter.api.Assertions.assertEquals;
import de.madjosz.adventofcode.AdventOfCodeUtil;
import java.util.List;
import org.junit.jupiter.api.Test;
class Day12Test {
@Test
void day12() {
List<String> lines = AdventOfCodeUtil.readLines(2016, 12);
Day12 day12 = new Day12(lines);
assertEquals(318009, day12.a1());
assertEquals(9227663, day12.a2());
}
@Test
void day12_exampleinput() {
List<String> lines = AdventOfCodeUtil.readLines(2016, 12, "test");
Day12 day12 = new Day12(lines);
assertEquals(42, day12.a1());
assertEquals(42, day12.a2());
}
}
|
import collect.UserDataGather;
import utils.DbUtil;
import java.sql.Connection;
/**
* Created by lrkin on 2016/11/15.
*/
public class ExecuteUserInfoSpider {
public static void main(String[] args) throws Exception {
// int start = 0, count = 1, j = 6;
// for (int i = 0; i < j; i++) {
//
// }
try {
Connection conn = DbUtil.getConn();
UserDataGather.getMoreUserList(conn, 1000, 1000);
} catch (Exception e) {
e.printStackTrace();
main(args);
}
}
}
|
package com.mydemo.webtest.specs;
import com.microsoft.playwright.*;
import com.mydemo.webtest.browser.BrowserConfig;
import com.mydemo.webtest.browser.BrowserManager;
import com.mydemo.webtest.pages.LoginPage;
import com.mydemo.webtest.pages.SignUpPage;
import com.mydemo.webtest.testng.BaseTest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.annotations.Test;
import java.nio.file.Paths;
import java.util.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
public class AppTest extends BaseTest {
private static final Logger LOGGER = LogManager.getLogger();
@Test
public void anotherTestPropertyFile() throws Exception {
LOGGER.info("Another test method logging test");
assertThat(constants.getEnvName(), containsString("act"));
}
@Test
public void demoPlaywright() throws Exception {
Playwright playwright = Playwright.create();
List<BrowserType> browserTypes = Arrays.asList(
// playwright.chromium()
playwright.webkit()
// playwright.firefox()
);
for (BrowserType browserType : browserTypes) {
Browser browser = browserType.launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext context = browser.newContext(
new Browser.NewContextOptions().setViewportSize(1280, 720));
Page page = context.newPage();
page.navigate("https://google.com");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot-" + browserType.name() + ".png")));
browser.close();
}
playwright.close();
}
@Test
public void samplePlaywrightTest() throws Exception {
Playwright playwright = Playwright.create();
BrowserType browserType = playwright.chromium();
BrowserType.LaunchOptions options = new BrowserType.LaunchOptions();
Browser.NewContextOptions contextOptions = new Browser.NewContextOptions();
// contextOptions.setRecordHar().withPath(Paths.get("test.har"));
contextOptions.setIgnoreHTTPSErrors(true);
// options.withSlowMo(10000);
options.setChromiumSandbox(false);
options.setHeadless(false);
Browser browser = browserType.launch(options);
BrowserContext browserContext = browser.newContext(contextOptions);
Page page = browserContext.newPage();
page.route("**", route -> {
// System.out.println("[URL] => [" + route.request().url() + "]");
// System.out.println("[Request headers] => [" + route.request().headers() + "]");
// System.out.println("[Request postDate] => [" + route.request().postData() + "]");
LOGGER.info("[URL] => [{}]", route.request().url());
// LOGGER.info("Request headers] => [{}]", route.request().headers());
// LOGGER.info("Request postDate] => [{}]", route.request().postData());
route.resume();
});
page.navigate("https://10.204.55.187:9443");
page.fill("#login-input-email", "redowl@redowl.com");
page.fill("#login-input-password", "redowl");
page.click("text='Sign In'");
// Deferred<Response> response = page.waitForResponse("**/*");
// System.out.println("***URL*** => " + response.get().url());
// LOGGER.info("***Response headers***] => [{}]", response.get().headers());
// System.out.println(new String(response.get().body(), StandardCharsets.UTF_8));
browserContext.close();
browser.close();
playwright.close();
}
static <K,V> Map<K, V> mapOf(Object... entries) {
Map result = new HashMap();
for (int i = 0; i + 1 < entries.length; i += 2) {
result.put(entries[i], entries[i + 1]);
}
return result;
}
@Test
public void testBrowserInit() throws Exception {
BrowserConfig.localPage = new BrowserManager().initializePlaywright();
BrowserConfig.localPage.navigate("https://google.com");
BrowserConfig.localPage.navigate(constants.getEnvUrl());
// Thread.sleep(5000);
LoginPage loginPage = new LoginPage();
loginPage.logIn("Katharina_Bernier", "s3cret");
}
@Test
public void testSignUp() throws Exception {
BrowserConfig.localPage = new BrowserManager().initializePlaywright();
BrowserConfig.localPage.navigate(constants.getEnvUrl());
LoginPage loginPage = new LoginPage();
var signUpPage = loginPage.openSignUpPage();
signUpPage.signUp("test-2", "qa", "test-2_qa", "secret", "secret");
}
}
|
package rabbitmq.entity;
/**
*
* @描述: MQ消息队列唯一标识配置
* @版权: Copyright (c) 2019
* @公司: 思迪科技
* @作者: 严磊
* @版本: 1.0
* @创建日期: 2019年7月29日
* @创建时间: 下午2:50:39
*/
public class QueueContants {
/**
* 消息队列
*/
public final static String actQueueName = "act_queue_name";
}
|
/*
* Copyright (C) 2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.importer.parser.record.entity.topic;
import static com.hedera.mirror.importer.config.CacheConfiguration.CACHE_MANAGER_TABLE_TIME_PARTITION;
import com.hedera.mirror.common.domain.StreamType;
import com.hedera.mirror.importer.IntegrationTest;
import com.hedera.mirror.importer.config.Owner;
import com.hedera.mirror.importer.db.TimePartition;
import com.hedera.mirror.importer.db.TimePartitionService;
import com.hedera.mirror.importer.parser.record.entity.EntityProperties;
import com.hedera.mirror.importer.repository.TopicMessageLookupRepository;
import jakarta.annotation.Resource;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.CacheManager;
import org.springframework.jdbc.core.JdbcTemplate;
public abstract class AbstractTopicMessageLookupIntegrationTest extends IntegrationTest {
protected static final Duration RECORD_FILE_INTERVAL = StreamType.RECORD.getFileCloseInterval();
private static final String CHECK_TABLE_EXISTENCE = "select 'topic_message_plain'::regclass";
private static final String CREATE_DDL =
"""
alter table topic_message rename to topic_message_plain;
create table topic_message (like topic_message_plain including constraints, primary key (consensus_timestamp, topic_id)) partition by range (consensus_timestamp);
create table topic_message_default partition of topic_message default;
create table topic_message_00 partition of topic_message for values from ('1680000000000000000') to ('1682000000000000000');
create table topic_message_01 partition of topic_message for values from ('1682000000000000000') to ('1684000000000000000');
""";
private static final String REVERT_DDL =
"""
drop table topic_message cascade;
alter table topic_message_plain rename to topic_message;
""";
@Autowired
@Qualifier(CACHE_MANAGER_TABLE_TIME_PARTITION)
private CacheManager cacheManager;
@Resource
protected EntityProperties entityProperties;
@Autowired
@Owner
protected JdbcTemplate jdbcTemplate;
@Resource
protected TimePartitionService timePartitionService;
@Resource
protected TopicMessageLookupRepository topicMessageLookupRepository;
protected List<TimePartition> partitions;
@BeforeEach
void setup() {
entityProperties.getPersist().setTopics(true);
entityProperties.getPersist().setTopicMessageLookups(true);
createPartitions();
}
private void createPartitions() {
if (isV1()) {
jdbcTemplate.execute(CREATE_DDL);
}
partitions = timePartitionService.getTimePartitions("topic_message");
}
@AfterEach
protected void revertPartitions() {
if (!isV1()) {
return;
}
try {
jdbcTemplate.execute(CHECK_TABLE_EXISTENCE);
jdbcTemplate.execute(REVERT_DDL);
// clear cache so for v1 TimePartitionService won't return stale partition info
cacheManager.getCacheNames().forEach(n -> cacheManager.getCache(n).clear());
} catch (Exception e) {
//
}
}
}
|
package br.com.nozinho.ejb.service.impl;
import java.util.List;
import javax.ejb.Stateless;
import br.com.nozinho.dao.PermissaoDAO;
import br.com.nozinho.ejb.service.PermissaoService;
import br.com.nozinho.model.Permissao;
@Stateless
public class PermissaoServiceImpl extends GenericServiceImpl<Permissao, Long> implements PermissaoService{
@Override
public List<Permissao> findPermissoes() {
return ((PermissaoDAO)getDAO()).findPermissoes();
}
}
|
package com.lnjecit.jms.constants;
/**
* @author lnj
* @description 常量
* @date 2019-01-03 15:04
**/
public interface ActiveMQConstants {
String BROKER_URL = "tcp://192.168.8.131:61616";
String AUTHOR_QUEUE = "author-queue";
String NEWS_TOPIC = "news-topic";
}
|
package com.mideas.rpg.v2.hud;
import com.mideas.rpg.v2.Mideas;
import com.mideas.rpg.v2.game.spell.SpellManager;
public class SpellLevel {
private static boolean spell1;
private static boolean spell3;
private static boolean spell7;
private static boolean spell10;
private static boolean spell15;
public static void addSpell() {
/*if(Mideas.joueur1().getClasseString().equals("Guerrier")) {
if(!spell1 && Mideas.joueur1().getLevel() >= 1) {
Mideas.joueur1().setSpellUnlocked(0, SpellManager.getSpell(102));
spell1 = true;
}
if(!spell3 && Mideas.joueur1().getLevel() >= 3) {
Mideas.joueur1().setSpellUnlocked(1, SpellManager.getSpell(101));
spell3 = true;
}
if(!spell7 && Mideas.joueur1().getLevel() >= 7) {
Mideas.joueur1().setSpellUnlocked(2, SpellManager.getSpell(105));
spell7 = true;
}
if(!spell10 && Mideas.joueur1().getLevel() >= 10) {
Mideas.joueur1().setSpellUnlocked(3, SpellManager.getSpell(104));
spell10 = true;
}
if(!spell15 && Mideas.joueur1().getLevel() >= 15) {
Mideas.joueur1().setSpellUnlocked(4, SpellManager.getSpell(103));
spell15 = true;
}
}*/
}
public static void setSpellLevelFalse() {
spell1 = false;
spell3 = false;
spell7 = false;
spell10 = false;
spell15 = false;
}
}
|
package com.IRCTradingDataGenerator.tradingDataGenerator.Controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.IRCTradingDataGenerator.tradingDataGenerator.Models.Trade;
import com.IRCTradingDataGenerator.tradingDataGenerator.Services.FileService;
import com.IRCTradingDataGenerator.tradingDataGenerator.Services.TradeService;
@Controller
@RequestMapping("/fileController")
@CrossOrigin(origins = "http://localhost:3000")
public class FileController {
@Autowired
FileService fileService;
@Autowired
TradeService tradeService;
@PostMapping("/ExportToFile/{trade_id}")
public ResponseEntity<String> exportTradeProductToFile(@PathVariable("trade_id")int trade_id) {
Trade trade = tradeService.getTradeById(trade_id).get();
return ResponseEntity.ok(fileService.exportTradeToFile(trade));
}
@PostMapping("/ExportAllTradesToFile/")
public ResponseEntity<String> exportAllTradesProductToFile() {
List<Trade> allTrades = tradeService.getTrades();
return ResponseEntity.ok(fileService.exportTradesToFile(allTrades));
}
}
|
package com.jiuzhe.app.hotel.service;
import com.jiuzhe.app.hotel.entity.HotelRegion;
import java.util.List;
public interface RegionService {
/**
* @Description:获取所有的城市
*/
List<HotelRegion> getAllRegion();
}
|
package com.yuecheng.yue.ui.bean;
import java.util.List;
/**
* Created by yuecheng on 2017/11/12.
*/
public class YUE_FriendsListBean {
int resulecode;
List<YUE_FriendsBean> value;
public int getResulecode() {
return resulecode;
}
public void setResulecode(int resulecode) {
this.resulecode = resulecode;
}
public List<YUE_FriendsBean> getValue() {
return value;
}
public void setValue(List<YUE_FriendsBean> value) {
this.value = value;
}
}
|
package com.example.bgmmixer.model;
import com.example.bgmmixer.dtos.StageDto;
import javax.persistence.*;
@Entity
public class Stage {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private double startTime;
private double endTime;
@ManyToOne
private Song song;
public Stage(){}
public Stage(StageDto stageDto){
this.name = stageDto.getName();
this.startTime = stageDto.getStartTime();
this.endTime = stageDto.getEndTime();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getStartTime() {
return startTime;
}
public void setStartTime(double startTime) {
this.startTime = startTime;
}
public double getEndTime() {
return endTime;
}
public void setEndTime(double endTime) {
this.endTime = endTime;
}
public Song getSong() {
return song;
}
public void setSong(Song song) {
this.song = song;
}
@Override
public String toString() {
return "Stage{" +
"id=" + id +
", name='" + name + '\'' +
", startTime=" + startTime +
", endTime=" + endTime +
", song=" + song +
'}';
}
}
|
package Hero;
import java.awt.*;
import java.util.Scanner;
import org.apache.log4j.Logger;
public class Main {
public int winner;
public Main(){
winner=0;
}
public void PrintInfo(){
System.out.println("ヒーロー:\n A-B-C-D-E-F-G-H-I-J");
System.out.println("Hero-A:Abdi, Hero-B:Bacheler\nHero-C:Cahill, Hero-D:" +
"Dahlia\nHero-E:Earle, Hero-F:Fairchild\nHero-G:Gabrielle, Hero-H:"
+"Hackett\nHero-I:Imogene, Hero-J:Jacobson");
}
public static Logger LOGGER = Logger.getLogger(Hero.Main.class);
//---------------------------------------------------------------------------
public static void main(String[]args)throws AWTException
{
Scanner sc=new Scanner(System.in);
Main Mainset=new Main();
battlefield Field=new battlefield();
Pixel pixel=new Pixel();
Field.SetField();
//-------------------------------------------------------------------------------------
Mainset.PrintInfo();
System.out.println("Please choose the HERO\n"+"ヒーロー");
LOGGER.debug("This is debug message.");
HeroA A_=new HeroA();HeroB B_=new HeroB();
HeroC C_=new HeroC();HeroD D_=new HeroD();
HeroE E_=new HeroE();HeroF F_=new HeroF();
HeroG G_=new HeroG();HeroH H_=new HeroH();
HeroI I_=new HeroI();HeroJ J_=new HeroJ();
//----------------------------------------------------------------------------------
for(int HeroNum=0;HeroNum<5;HeroNum++)
{
char in=sc.next().charAt(0);
Field.field[0][2*HeroNum+1]=in;
switch (in){
case'A':A_.SetLocation(0,2*HeroNum+1);A_.horde=1;break;
case'B':B_.SetLocation(0,2*HeroNum+1);B_.horde=1;break;
case'C':C_.SetLocation(0,2*HeroNum+1);C_.horde=1;break;
case'D':D_.SetLocation(0,2*HeroNum+1);D_.horde=1;break;
case'E':E_.SetLocation(0,2*HeroNum+1);E_.horde=1;break;
case'F':F_.SetLocation(0,2*HeroNum+1);F_.horde=1;break;
case'G':G_.SetLocation(0,2*HeroNum+1);G_.horde=1;break;
case'H':H_.SetLocation(0,2*HeroNum+1);H_.horde=1;break;
case'I':I_.SetLocation(0,2*HeroNum+1);I_.horde=1;break;
case'J':J_.SetLocation(0,2*HeroNum+1);J_.horde=1;break;
}
LOGGER.info("You chose hero "+in+", location is (0,"+(2*HeroNum+1)+")");
}
System.out.println("Please choose the HERO\n"+"ヒーロー");
for(int HeroNum=0;HeroNum<5;HeroNum++)
{
char in=sc.next().charAt(0);
LOGGER.info("You chose hero "+in);
Field.field[10][2*HeroNum+1]=in;
switch (in){
case'A':A_.SetLocation(10,2*HeroNum+1);A_.horde=2;break;
case'B':B_.SetLocation(10,2*HeroNum+1);B_.horde=2;break;
case'C':C_.SetLocation(10,2*HeroNum+1);C_.horde=2;break;
case'D':D_.SetLocation(10,2*HeroNum+1);D_.horde=2;break;
case'E':E_.SetLocation(10,2*HeroNum+1);E_.horde=2;break;
case'F':F_.SetLocation(10,2*HeroNum+1);F_.horde=2;break;
case'G':G_.SetLocation(10,2*HeroNum+1);G_.horde=2;break;
case'H':H_.SetLocation(10,2*HeroNum+1);H_.horde=2;break;
case'I':I_.SetLocation(10,2*HeroNum+1);I_.horde=2;break;
case'J':J_.SetLocation(10,2*HeroNum+1);J_.horde=2;break;
}
LOGGER.info("You chose hero "+in+", location is (10,"+(2*HeroNum+1)+")");
}
Field.Print_Field_single();
String option;
while(Mainset.winner==0) {
option=sc.next();
if(option.equals("MOVE")) {
char on=sc.next().charAt(0);
char dir = sc.next().charAt(0);
switch (on){
case'A':A_.Move(dir,Field);
A_.ShowInfo(Field);break;
case'B':B_.Move(dir,Field);
B_.ShowInfo(Field);break;
case'C':C_.Move(dir,Field);
C_.ShowInfo(Field);break;
case'D':D_.Move(dir,Field);
D_.ShowInfo(Field);break;
case'E':E_.Move(dir,Field);
E_.ShowInfo(Field);break;
case'F':F_.Move(dir,Field);
F_.ShowInfo(Field);break;
case'G':G_.Move(dir,Field);
G_.ShowInfo(Field);break;
case'H':H_.Move(dir,Field);
H_.ShowInfo(Field);break;
case'I':I_.Move(dir,Field);
I_.ShowInfo(Field);break;
case'J':J_.Move(dir,Field);
J_.ShowInfo(Field);break;
}
Field.Print_Field_single();
Mainset.PrintInfo();
//LOGGER.debug("You move hero "+on+" to a new location ");
}
else if(option.equals("ATTACK")){
char ac=sc.next().charAt(0);
char pa=sc.next().charAt(0);
Mainset.PrintInfo();
Field.PrintField();
switch (ac){
case 'A':{
switch (pa){
case'B':A_.Attacking(B_);B_.PassiveSkill();
Field.CalculatePath(A_,B_);B_.ShowInfo(Field);break;
case'C':A_.Attacking(C_);C_.PassiveSkill();
Field.CalculatePath(A_,C_);C_.ShowInfo(Field);break;
case'D':A_.Attacking(D_);D_.PassiveSkill();
Field.CalculatePath(A_,D_);D_.ShowInfo(Field);break;
case'E':A_.Attacking(E_);E_.PassiveSkill();
Field.CalculatePath(A_,E_);E_.ShowInfo(Field);break;
case'F':A_.Attacking(F_);F_.PassiveSkill();
Field.CalculatePath(A_,F_);F_.ShowInfo(Field);break;
case'G':A_.Attacking(G_);G_.PassiveSkill();
Field.CalculatePath(A_,G_);G_.ShowInfo(Field);break;
case'H':A_.Attacking(H_);H_.PassiveSkill();
Field.CalculatePath(A_,H_);H_.ShowInfo(Field);break;
case'I':A_.Attacking(I_);I_.PassiveSkill();
Field.CalculatePath(A_,I_);I_.ShowInfo(Field);break;
case'J':A_.Attacking(J_);J_.PassiveSkill();
Field.CalculatePath(A_,J_);J_.ShowInfo(Field);break;
}
A_.ShowInfo(Field);
LOGGER.debug("You let hero "+ac+" to attack hero "+pa);
break;
}
case 'B':{
switch (pa){
case'A':B_.Attacking(A_);A_.PassiveSkill();
Field.CalculatePath(B_,A_);A_.ShowInfo(Field);break;
case'C':B_.Attacking(C_);B_.PassiveSkill();
Field.CalculatePath(B_,C_);C_.ShowInfo(Field);break;
case'D':B_.Attacking(D_);D_.PassiveSkill();
Field.CalculatePath(B_,D_);D_.ShowInfo(Field);break;
case'E':B_.Attacking(E_);E_.PassiveSkill();
Field.CalculatePath(B_,E_);E_.ShowInfo(Field);break;
case'F':B_.Attacking(F_);F_.PassiveSkill();
Field.CalculatePath(B_,F_);F_.ShowInfo(Field);break;
case'G':B_.Attacking(G_);G_.PassiveSkill();
Field.CalculatePath(B_,G_);G_.ShowInfo(Field);break;
case'H':B_.Attacking(H_);H_.PassiveSkill();
Field.CalculatePath(B_,H_);H_.ShowInfo(Field);break;
case'I':B_.Attacking(I_);I_.PassiveSkill();
Field.CalculatePath(B_,I_);I_.ShowInfo(Field);break;
case'J':B_.Attacking(J_);J_.PassiveSkill();
Field.CalculatePath(B_,J_);J_.ShowInfo(Field);break;
}
B_.ShowInfo(Field);
break;
}
case 'C':{
switch (pa){
case'B':C_.Attacking(B_);B_.PassiveSkill();
Field.CalculatePath(C_,B_);B_.ShowInfo(Field);break;
case'A':C_.Attacking(A_);A_.PassiveSkill();
Field.CalculatePath(C_,A_);A_.ShowInfo(Field);break;
case'D':C_.Attacking(D_);D_.PassiveSkill();
Field.CalculatePath(C_,D_);D_.ShowInfo(Field);break;
case'E':C_.Attacking(E_);E_.PassiveSkill();
Field.CalculatePath(C_,E_);E_.ShowInfo(Field);break;
case'F':C_.Attacking(F_);F_.PassiveSkill();
Field.CalculatePath(C_,F_);F_.ShowInfo(Field);break;
case'G':C_.Attacking(G_);G_.PassiveSkill();
Field.CalculatePath(C_,G_);G_.ShowInfo(Field);break;
case'H':C_.Attacking(H_);H_.PassiveSkill();
Field.CalculatePath(C_,H_);H_.ShowInfo(Field);break;
case'I':C_.Attacking(I_);I_.PassiveSkill();
Field.CalculatePath(C_,I_);I_.ShowInfo(Field);break;
case'J':C_.Attacking(J_);J_.PassiveSkill();
Field.CalculatePath(C_,J_);J_.ShowInfo(Field);break;
}
C_.ShowInfo(Field);
break;
}
case 'D':{
switch (pa){
case'B':D_.Attacking(B_);B_.PassiveSkill();
Field.CalculatePath(D_,B_);B_.ShowInfo(Field);break;
case'C':D_.Attacking(C_);C_.PassiveSkill();
Field.CalculatePath(D_,C_);C_.ShowInfo(Field);break;
case'A':D_.Attacking(A_);A_.PassiveSkill();
Field.CalculatePath(D_,A_);A_.ShowInfo(Field);break;
case'E':D_.Attacking(E_);E_.PassiveSkill();
Field.CalculatePath(D_,E_);E_.ShowInfo(Field);break;
case'F':D_.Attacking(F_);F_.PassiveSkill();
Field.CalculatePath(D_,F_);F_.ShowInfo(Field);break;
case'G':D_.Attacking(G_);G_.PassiveSkill();
Field.CalculatePath(D_,G_);G_.ShowInfo(Field);break;
case'H':D_.Attacking(H_);H_.PassiveSkill();
Field.CalculatePath(D_,H_);H_.ShowInfo(Field);break;
case'I':D_.Attacking(I_);I_.PassiveSkill();
Field.CalculatePath(D_,I_);I_.ShowInfo(Field);break;
case'J':D_.Attacking(J_);J_.PassiveSkill();
Field.CalculatePath(D_,J_);J_.ShowInfo(Field);break;
}
D_.ShowInfo(Field);
break;
}
case 'E':{
switch (pa){
case'B':E_.Attacking(B_);B_.PassiveSkill();
Field.CalculatePath(E_,B_);B_.ShowInfo(Field);break;
case'C':E_.Attacking(C_);C_.PassiveSkill();
Field.CalculatePath(E_,C_);C_.ShowInfo(Field);break;
case'D':E_.Attacking(D_);D_.PassiveSkill();
Field.CalculatePath(E_,D_);D_.ShowInfo(Field);break;
case'A':E_.Attacking(A_);A_.PassiveSkill();
Field.CalculatePath(E_,A_);A_.ShowInfo(Field);break;
case'F':E_.Attacking(F_);F_.PassiveSkill();
Field.CalculatePath(E_,F_);F_.ShowInfo(Field);break;
case'G':E_.Attacking(G_);G_.PassiveSkill();
Field.CalculatePath(E_,G_);G_.ShowInfo(Field);break;
case'H':E_.Attacking(H_);H_.PassiveSkill();
Field.CalculatePath(E_,H_);H_.ShowInfo(Field);break;
case'I':E_.Attacking(I_);I_.PassiveSkill();
Field.CalculatePath(E_,I_);I_.ShowInfo(Field);break;
case'J':E_.Attacking(J_);J_.PassiveSkill();
Field.CalculatePath(E_,J_);J_.ShowInfo(Field);break;
}
E_.ShowInfo(Field);
break;
}
case 'F':{
switch (pa){
case'B':F_.Attacking(B_);B_.PassiveSkill();
Field.CalculatePath(F_,B_);B_.ShowInfo(Field);break;
case'C':F_.Attacking(C_);C_.PassiveSkill();
Field.CalculatePath(F_,C_);C_.ShowInfo(Field);break;
case'D':F_.Attacking(D_);D_.PassiveSkill();
Field.CalculatePath(F_,D_);D_.ShowInfo(Field);break;
case'E':F_.Attacking(E_);E_.PassiveSkill();
Field.CalculatePath(F_,E_);E_.ShowInfo(Field);break;
case'A':F_.Attacking(A_);A_.PassiveSkill();
Field.CalculatePath(F_,A_);A_.ShowInfo(Field);break;
case'G':F_.Attacking(G_);G_.PassiveSkill();
Field.CalculatePath(F_,G_);G_.ShowInfo(Field);break;
case'H':F_.Attacking(H_);H_.PassiveSkill();
Field.CalculatePath(F_,H_);H_.ShowInfo(Field);break;
case'I':F_.Attacking(I_);I_.PassiveSkill();
Field.CalculatePath(F_,I_);I_.ShowInfo(Field);break;
case'J':F_.Attacking(J_);J_.PassiveSkill();
Field.CalculatePath(F_,J_);J_.ShowInfo(Field);break;
}
F_.ShowInfo(Field);
break;
}
case 'G':{
switch (pa){
case'B':G_.Attacking(B_);B_.PassiveSkill();
Field.CalculatePath(G_,B_);B_.ShowInfo(Field);break;
case'C':G_.Attacking(C_);C_.PassiveSkill();
Field.CalculatePath(G_,C_);C_.ShowInfo(Field);break;
case'D':G_.Attacking(D_);D_.PassiveSkill();
Field.CalculatePath(G_,D_);D_.ShowInfo(Field);break;
case'E':G_.Attacking(E_);E_.PassiveSkill();
Field.CalculatePath(G_,E_);E_.ShowInfo(Field);break;
case'F':G_.Attacking(F_);F_.PassiveSkill();
Field.CalculatePath(G_,F_);F_.ShowInfo(Field);break;
case'A':G_.Attacking(A_);A_.PassiveSkill();
Field.CalculatePath(G_,A_);A_.ShowInfo(Field);break;
case'H':G_.Attacking(H_);H_.PassiveSkill();
Field.CalculatePath(G_,H_);H_.ShowInfo(Field);break;
case'I':G_.Attacking(I_);I_.PassiveSkill();
Field.CalculatePath(G_,I_);I_.ShowInfo(Field);break;
case'J':G_.Attacking(J_);J_.PassiveSkill();
Field.CalculatePath(G_,J_);J_.ShowInfo(Field);break;
}
G_.ShowInfo(Field);
break;
}
case 'H':{
switch (pa){
case'B':H_.Attacking(B_);B_.PassiveSkill();
Field.CalculatePath(H_,B_);B_.ShowInfo(Field);break;
case'C':H_.Attacking(C_);C_.PassiveSkill();
Field.CalculatePath(H_,C_);C_.ShowInfo(Field);break;
case'D':H_.Attacking(D_);D_.PassiveSkill();
Field.CalculatePath(H_,D_);D_.ShowInfo(Field);break;
case'E':H_.Attacking(E_);E_.PassiveSkill();
Field.CalculatePath(H_,E_);E_.ShowInfo(Field);break;
case'F':H_.Attacking(F_);F_.PassiveSkill();
Field.CalculatePath(H_,F_);F_.ShowInfo(Field);break;
case'G':H_.Attacking(G_);G_.PassiveSkill();
Field.CalculatePath(H_,G_);G_.ShowInfo(Field);break;
case'A':H_.Attacking(A_);A_.PassiveSkill();
Field.CalculatePath(H_,A_);A_.ShowInfo(Field);break;
case'I':H_.Attacking(I_);I_.PassiveSkill();
Field.CalculatePath(H_,I_);I_.ShowInfo(Field);break;
case'J':H_.Attacking(J_);J_.PassiveSkill();
Field.CalculatePath(H_,J_);J_.ShowInfo(Field);break;
}
H_.ShowInfo(Field);
break;
}
case 'I':{
switch (pa){
case'B':I_.Attacking(B_);B_.PassiveSkill();
Field.CalculatePath(I_,B_);B_.ShowInfo(Field);break;
case'C':I_.Attacking(C_);C_.PassiveSkill();
Field.CalculatePath(I_,C_);C_.ShowInfo(Field);break;
case'D':I_.Attacking(D_);D_.PassiveSkill();
Field.CalculatePath(I_,D_);D_.ShowInfo(Field);break;
case'E':I_.Attacking(E_);E_.PassiveSkill();
Field.CalculatePath(I_,E_);E_.ShowInfo(Field);break;
case'F':I_.Attacking(F_);F_.PassiveSkill();
Field.CalculatePath(I_,F_);F_.ShowInfo(Field);break;
case'G':I_.Attacking(G_);G_.PassiveSkill();
Field.CalculatePath(I_,G_);G_.ShowInfo(Field);break;
case'H':I_.Attacking(H_);H_.PassiveSkill();
Field.CalculatePath(I_,H_);H_.ShowInfo(Field);break;
case'A':I_.Attacking(A_);A_.PassiveSkill();
Field.CalculatePath(I_,A_);A_.ShowInfo(Field);break;
case'J':I_.Attacking(J_);J_.PassiveSkill();
Field.CalculatePath(I_,J_);J_.ShowInfo(Field);break;
}
I_.ShowInfo(Field);
break;
}
case 'J':{
switch (pa){
case'B':J_.Attacking(B_);B_.PassiveSkill();
Field.CalculatePath(J_,B_);B_.ShowInfo(Field);break;
case'C':J_.Attacking(C_);C_.PassiveSkill();
Field.CalculatePath(J_,C_);C_.ShowInfo(Field);break;
case'D':J_.Attacking(D_);D_.PassiveSkill();
Field.CalculatePath(J_,D_);D_.ShowInfo(Field);break;
case'E':J_.Attacking(E_);E_.PassiveSkill();
Field.CalculatePath(J_,E_);E_.ShowInfo(Field);break;
case'F':J_.Attacking(F_);F_.PassiveSkill();
Field.CalculatePath(J_,F_);F_.ShowInfo(Field);break;
case'G':J_.Attacking(G_);G_.PassiveSkill();
Field.CalculatePath(J_,G_);G_.ShowInfo(Field);break;
case'H':J_.Attacking(H_);H_.PassiveSkill();
Field.CalculatePath(J_,H_);H_.ShowInfo(Field);break;
case'I':J_.Attacking(I_);I_.PassiveSkill();
Field.CalculatePath(J_,I_);I_.ShowInfo(Field);break;
case'A':J_.Attacking(A_);A_.PassiveSkill();
Field.CalculatePath(J_,A_);A_.ShowInfo(Field);break;
}
J_.ShowInfo(Field);
break;
}
}
LOGGER.debug("You let hero "+ac+" attack hero "+pa);
}
//-------------------------------------------------------------------------
else if(option.equals("ACTIVE"))
{
char ac=sc.next().charAt(0);
char pa=sc.next().charAt(0);
switch (ac){
case 'A':{
switch (pa){
case'B':A_.ActiveSkill(B_);Field.CalculatePath(A_,B_);
B_.ShowInfo(Field);break;
case'C':A_.ActiveSkill(C_);Field.CalculatePath(A_,C_);
C_.ShowInfo(Field);break;
case'D':A_.ActiveSkill(D_);Field.CalculatePath(A_,D_);
D_.ShowInfo(Field);break;
case'E':A_.ActiveSkill(E_);Field.CalculatePath(A_,E_);
E_.ShowInfo(Field);break;
case'F':A_.ActiveSkill(F_);Field.CalculatePath(A_,F_);
F_.ShowInfo(Field);break;
case'G':A_.ActiveSkill(G_);Field.CalculatePath(A_,G_);
G_.ShowInfo(Field);break;
case'H':A_.ActiveSkill(H_);Field.CalculatePath(A_,H_);
H_.ShowInfo(Field);break;
case'I':A_.ActiveSkill(I_);Field.CalculatePath(A_,I_);
I_.ShowInfo(Field);break;
case'J':A_.ActiveSkill(J_);Field.CalculatePath(A_,J_);
J_.ShowInfo(Field);break;
}
A_.ShowInfo(Field);
break;
}
case 'B':{
switch (pa){
case'A':B_.ActiveSkill(A_);Field.CalculatePath(B_,A_);
A_.ShowInfo(Field);break;
case'C':B_.ActiveSkill(C_);Field.CalculatePath(B_,C_);
C_.ShowInfo(Field);break;
case'D':B_.ActiveSkill(D_);Field.CalculatePath(B_,D_);
D_.ShowInfo(Field);break;
case'E':B_.ActiveSkill(E_);Field.CalculatePath(B_,E_);
E_.ShowInfo(Field);break;
case'F':B_.ActiveSkill(F_);Field.CalculatePath(B_,F_);
F_.ShowInfo(Field);break;
case'G':B_.ActiveSkill(G_);Field.CalculatePath(B_,G_);
G_.ShowInfo(Field);break;
case'H':B_.ActiveSkill(H_);Field.CalculatePath(B_,H_);
H_.ShowInfo(Field);break;
case'I':B_.ActiveSkill(I_);Field.CalculatePath(B_,I_);
I_.ShowInfo(Field);break;
case'J':B_.ActiveSkill(J_);Field.CalculatePath(B_,J_);
J_.ShowInfo(Field);break;
}
B_.ShowInfo(Field);
break;
}
case 'C':{
switch (pa){
case'B':C_.ActiveSkill(B_);Field.CalculatePath(C_,B_);
B_.ShowInfo(Field);break;
case'A':C_.ActiveSkill(A_);Field.CalculatePath(C_,A_);
A_.ShowInfo(Field);break;
case'D':C_.ActiveSkill(D_);Field.CalculatePath(C_,D_);
D_.ShowInfo(Field);break;
case'E':C_.ActiveSkill(E_);Field.CalculatePath(C_,E_);
E_.ShowInfo(Field);break;
case'F':C_.ActiveSkill(F_);Field.CalculatePath(C_,F_);
F_.ShowInfo(Field);break;
case'G':C_.ActiveSkill(G_);Field.CalculatePath(C_,G_);
G_.ShowInfo(Field);break;
case'H':C_.ActiveSkill(H_);Field.CalculatePath(C_,H_);
H_.ShowInfo(Field);break;
case'I':C_.ActiveSkill(I_);Field.CalculatePath(C_,I_);
I_.ShowInfo(Field);break;
case'J':C_.ActiveSkill(J_);Field.CalculatePath(C_,J_);
J_.ShowInfo(Field);break;
}
C_.ShowInfo(Field);
break;
}
case 'D':{
switch (pa){
case'B':D_.ActiveSkill(B_);Field.CalculatePath(D_,B_);
B_.ShowInfo(Field);break;
case'C':D_.ActiveSkill(C_);Field.CalculatePath(D_,C_);
C_.ShowInfo(Field);break;
case'A':D_.ActiveSkill(A_);Field.CalculatePath(D_,A_);
A_.ShowInfo(Field);break;
case'E':D_.ActiveSkill(E_);Field.CalculatePath(D_,E_);
E_.ShowInfo(Field);break;
case'F':D_.ActiveSkill(F_);Field.CalculatePath(D_,F_);
F_.ShowInfo(Field);break;
case'G':D_.ActiveSkill(G_);Field.CalculatePath(D_,G_);
G_.ShowInfo(Field);break;
case'H':D_.ActiveSkill(H_);Field.CalculatePath(D_,H_);
H_.ShowInfo(Field);break;
case'I':D_.ActiveSkill(I_);Field.CalculatePath(D_,I_);
I_.ShowInfo(Field);break;
case'J':D_.ActiveSkill(J_);Field.CalculatePath(D_,J_);
J_.ShowInfo(Field);break;
}
D_.ShowInfo(Field);
break;
}
case 'E':{
switch (pa){
case'B':E_.ActiveSkill(B_);Field.CalculatePath(E_,B_);
B_.ShowInfo(Field);break;
case'C':E_.ActiveSkill(C_);Field.CalculatePath(E_,C_);
C_.ShowInfo(Field);break;
case'D':E_.ActiveSkill(D_);Field.CalculatePath(E_,D_);
D_.ShowInfo(Field);break;
case'A':E_.ActiveSkill(A_);Field.CalculatePath(E_,A_);
A_.ShowInfo(Field);break;
case'F':E_.ActiveSkill(F_);Field.CalculatePath(E_,F_);
F_.ShowInfo(Field);break;
case'G':E_.ActiveSkill(G_);Field.CalculatePath(E_,G_);
G_.ShowInfo(Field);break;
case'H':E_.ActiveSkill(H_);Field.CalculatePath(E_,H_);
H_.ShowInfo(Field);break;
case'I':E_.ActiveSkill(I_);Field.CalculatePath(E_,I_);
I_.ShowInfo(Field);break;
case'J':E_.ActiveSkill(J_);Field.CalculatePath(E_,J_);
J_.ShowInfo(Field);break;
}
E_.ShowInfo(Field);
break;
}
case 'F':{
switch (pa){
case'B':F_.ActiveSkill(B_);Field.CalculatePath(F_,B_);
B_.ShowInfo(Field);break;
case'C':F_.ActiveSkill(C_);Field.CalculatePath(F_,C_);
C_.ShowInfo(Field);break;
case'D':F_.ActiveSkill(D_);Field.CalculatePath(F_,D_);
D_.ShowInfo(Field);break;
case'E':F_.ActiveSkill(E_);Field.CalculatePath(F_,E_);
E_.ShowInfo(Field);break;
case'A':F_.ActiveSkill(A_);Field.CalculatePath(F_,A_);
A_.ShowInfo(Field);break;
case'G':F_.ActiveSkill(G_);Field.CalculatePath(F_,G_);
G_.ShowInfo(Field);break;
case'H':F_.ActiveSkill(H_);Field.CalculatePath(F_,H_);
H_.ShowInfo(Field);break;
case'I':F_.ActiveSkill(I_);Field.CalculatePath(F_,I_);
I_.ShowInfo(Field);break;
case'J':F_.ActiveSkill(J_);Field.CalculatePath(F_,J_);
J_.ShowInfo(Field);break;
}
F_.ShowInfo(Field);
break;
}
case 'G':{
switch (pa){
case'B':G_.ActiveSkill(B_);Field.CalculatePath(G_,B_);
B_.ShowInfo(Field);break;
case'C':G_.ActiveSkill(C_);Field.CalculatePath(G_,C_);
C_.ShowInfo(Field);break;
case'D':G_.ActiveSkill(D_);Field.CalculatePath(G_,D_);
D_.ShowInfo(Field);break;
case'E':G_.ActiveSkill(E_);Field.CalculatePath(G_,E_);
E_.ShowInfo(Field);break;
case'F':G_.ActiveSkill(F_);Field.CalculatePath(G_,F_);
F_.ShowInfo(Field);break;
case'A':G_.ActiveSkill(A_);Field.CalculatePath(G_,A_);
A_.ShowInfo(Field);break;
case'H':G_.ActiveSkill(H_);Field.CalculatePath(G_,H_);
H_.ShowInfo(Field);break;
case'I':G_.ActiveSkill(I_);Field.CalculatePath(G_,I_);
I_.ShowInfo(Field);break;
case'J':G_.ActiveSkill(J_);Field.CalculatePath(G_,J_);
J_.ShowInfo(Field);break;
}
G_.ShowInfo(Field);
break;
}
case 'H':{
switch (pa){
case'B':H_.ActiveSkill(B_);Field.CalculatePath(H_,B_);
B_.ShowInfo(Field);break;
case'C':H_.ActiveSkill(C_);Field.CalculatePath(H_,C_);
C_.ShowInfo(Field);break;
case'D':H_.ActiveSkill(D_);Field.CalculatePath(H_,D_);
D_.ShowInfo(Field);break;
case'E':H_.ActiveSkill(E_);Field.CalculatePath(H_,E_);
E_.ShowInfo(Field);break;
case'F':H_.ActiveSkill(F_);Field.CalculatePath(H_,F_);
F_.ShowInfo(Field);break;
case'G':H_.ActiveSkill(G_);Field.CalculatePath(H_,G_);
G_.ShowInfo(Field);break;
case'A':H_.ActiveSkill(A_);Field.CalculatePath(H_,H_);
A_.ShowInfo(Field);break;
case'I':H_.ActiveSkill(I_);Field.CalculatePath(H_,I_);
I_.ShowInfo(Field);break;
case'J':H_.ActiveSkill(J_);Field.CalculatePath(H_,J_);
J_.ShowInfo(Field);break;
}
H_.ShowInfo(Field);
break;
}
case 'I':{
switch (pa){
case'B':I_.ActiveSkill(B_);
Field.CalculatePath(I_,B_);
B_.ShowInfo(Field);break;
case'C':I_.ActiveSkill(C_);
Field.CalculatePath(I_,C_);
C_.ShowInfo(Field);break;
case'D':I_.ActiveSkill(D_);Field.CalculatePath(I_,D_);
D_.ShowInfo(Field);break;
case'E':I_.ActiveSkill(E_);Field.CalculatePath(I_,E_);
E_.ShowInfo(Field);break;
case'F':I_.ActiveSkill(F_);Field.CalculatePath(I_,F_);
F_.ShowInfo(Field);break;
case'G':I_.ActiveSkill(G_);Field.CalculatePath(I_,G_);
G_.ShowInfo(Field);break;
case'H':I_.ActiveSkill(H_);Field.CalculatePath(I_,H_);
H_.ShowInfo(Field);break;
case'A':I_.ActiveSkill(A_);Field.CalculatePath(I_,A_);
A_.ShowInfo(Field);break;
case'J':I_.ActiveSkill(J_);Field.CalculatePath(I_,J_);
J_.ShowInfo(Field);break;
}
I_.ShowInfo(Field);
break;
}
case 'J':{
switch (pa){
case'B':J_.ActiveSkill(B_);Field.CalculatePath(J_,B_);
B_.ShowInfo(Field);break;
case'C':J_.ActiveSkill(C_);Field.CalculatePath(J_,C_);
C_.ShowInfo(Field);break;
case'D':J_.ActiveSkill(D_);Field.CalculatePath(J_,D_);
D_.ShowInfo(Field);break;
case'E':J_.ActiveSkill(E_);Field.CalculatePath(J_,E_);
E_.ShowInfo(Field);break;
case'F':J_.ActiveSkill(F_);Field.CalculatePath(J_,F_);
F_.ShowInfo(Field);break;
case'G':J_.ActiveSkill(G_);Field.CalculatePath(J_,G_);
G_.ShowInfo(Field);break;
case'H':J_.ActiveSkill(H_);Field.CalculatePath(J_,H_);
H_.ShowInfo(Field);break;
case'I':J_.ActiveSkill(I_);Field.CalculatePath(J_,I_);
I_.ShowInfo(Field);break;
case'A':J_.ActiveSkill(A_);Field.CalculatePath(J_,A_);
A_.ShowInfo(Field);break;
}
J_.ShowInfo(Field);
break;
}
}
Mainset.PrintInfo();
LOGGER.debug("You let hero "+ac+" launch active skill to attack hero "+pa);
}
else if(option.equals("CHECKMATE")) {
char be=sc.next().charAt(0);
switch(be){
case'A':pixel.BeAttcked(A_,Field);pixel.EndOfGame(Mainset);break;
case'B':pixel.BeAttcked(B_,Field);pixel.EndOfGame(Mainset);break;
case'C':pixel.BeAttcked(C_,Field);pixel.EndOfGame(Mainset);break;
case'D':pixel.BeAttcked(D_,Field);pixel.EndOfGame(Mainset);break;
case'E':pixel.BeAttcked(E_,Field);pixel.EndOfGame(Mainset);break;
case'F':pixel.BeAttcked(F_,Field);pixel.EndOfGame(Mainset);break;
case'G':pixel.BeAttcked(G_,Field);pixel.EndOfGame(Mainset);break;
case'H':pixel.BeAttcked(H_,Field);pixel.EndOfGame(Mainset);break;
case'I':pixel.BeAttcked(I_,Field);pixel.EndOfGame(Mainset);break;
case'J':pixel.BeAttcked(J_,Field);pixel.EndOfGame(Mainset);break;
}
LOGGER.debug("You let hero "+be+" attack Chrystal tower.");
}
else if(option.equals("SKILL")){
char ch=sc.next().charAt(0);
switch(ch){
case'A':A_.SpecialSkill(Field);break;
case'B':B_.SpecialSkill(Field);break;
case'C':C_.SpecialSkill(Field);break;
case'D':D_.SpecialSkill(Field);break;
case'E':E_.SpecialSkill(Field);break;
case'F':F_.SpecialSkill(Field);break;
case'G':G_.SpecialSkill(Field);break;
case'H':H_.SpecialSkill(Field);break;
case'I':I_.SpecialSkill(Field);break;
case'J':J_.SpecialSkill(Field);break;
}
LOGGER.debug("You let hero "+ch+" launch special skill.");
}
}
}
}
|
package com.espendwise.tools.gencode.tasks;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Environment;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.PropertySet;
import org.hibernate.MappingNotFoundException;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.ant.*;
import org.hibernate.util.StringHelper;
import java.io.File;
import java.util.*;
public class DbBaseHbmToolTask extends HibernateToolTask {
ConfigurationTask configurationTask;
private File destDir;
private List generators = new ArrayList();
private Path classPath;
private Path templatePath;
private Properties properties = new Properties();
private void checkConfiguration() {
if(configurationTask!=null) {
throw new BuildException("Only a single configuration is allowed.");
}
}
public ExporterTask createHbmTemplate() {
ExporterTask generator = new GenericExporterTask(this);
generators.add(generator);
return generator;
}
public ConfigurationTask createConfiguration() {
checkConfiguration();
configurationTask = new ConfigurationTask();
return configurationTask;
}
public DbBaseXmlConfigurationTask createDbBaseConfiguration() {
checkConfiguration();
configurationTask = new DbBaseXmlConfigurationTask();
return (DbBaseXmlConfigurationTask) configurationTask;
}
/**
* Set the classpath to be used when running the Java class
*
* @param s an Ant Path object containing the classpath.
*/
public void setClasspath(Path s) {
classPath = s;
}
/**
* Adds a path to the classpath.
*
* @return created classpath
*/
public Path createClasspath() {
classPath = new Path(getProject() );
return classPath;
}
public void execute() {
log("Executing Hibernate Tool with a " + configurationTask.getDescription() );
validateParameters();
log("validateParameters OK");
Iterator iterator = generators.iterator();
AntClassLoader loader = getProject().createClassLoader(classPath);
ExporterTask generatorTask = null;
int count = 1;
try {
loader.setParent(this.getClass().getClassLoader() ); // if this is not set, classes from the taskdef cannot be found - which is crucial for e.g. annotations.
loader.setThreadContextLoader();
while (iterator.hasNext() ) {
generatorTask = (ExporterTask) iterator.next();
log(count++ + ". task: " + generatorTask);
generatorTask.execute();
}
} catch (RuntimeException re) {
re.printStackTrace();
// reportException(re, count, generatorTask);
}
finally {
if (loader != null) {
loader.resetThreadContextLoader();
loader.cleanup();
}
}
}
private void reportException(Throwable re, int count, ExporterTask generatorTask) {
log("An exception occurred while running exporter #" + count + ":" + generatorTask, Project.MSG_ERR);
log("To get the full stack trace run ant with -verbose", Project.MSG_ERR);
log(re.toString(), Project.MSG_ERR);
String ex = new String();
Throwable cause = re.getCause();
while(cause!=null) {
ex += cause.toString() + "\n";
if(cause==cause.getCause()) {
break; // we reached the top.
} else {
cause=cause.getCause();
}
}
if(StringHelper.isNotEmpty(ex)) {
log(ex, Project.MSG_ERR);
}
String newbieMessage = getProbableSolutionOrCause(re);
if(newbieMessage!=null) {
log(newbieMessage);
}
if(re instanceof BuildException) {
throw (BuildException)re;
} else {
throw new BuildException(re, getLocation());
}
}
private String getProbableSolutionOrCause(Throwable re) {
if(re==null) return null;
if(re instanceof MappingNotFoundException) {
MappingNotFoundException mnf = (MappingNotFoundException)re;
if("resource".equals(mnf.getType())) {
return "A " + mnf.getType() + " located at " + mnf.getPath() + " was not found.\n" +
"Check the following:\n" +
"\n" +
"1) Is the spelling/casing correct ?\n" +
"2) Is " + mnf.getPath() + " available via the classpath ?\n" +
"3) Does it actually exist ?\n";
} else {
return "A " + mnf.getType() + " located at " + mnf.getPath() + " was not found.\n" +
"Check the following:\n" +
"\n" +
"1) Is the spelling/casing correct ?\n" +
"2) Do you permission to access " + mnf.getPath() + " ?\n" +
"3) Does it actually exist ?\n";
}
}
if(re instanceof ClassNotFoundException || re instanceof NoClassDefFoundError) {
return "A class were not found in the classpath of the Ant task.\n" +
"Ensure that the classpath contains the classes needed for Hibernate and your code are in the classpath.\n";
}
if(re instanceof UnsupportedClassVersionError) {
return "You are most likely running the ant task with a JRE that is older than the JRE required to use the classes.\n" +
"e.g. running with JRE 1.3 or 1.4 when using JDK 1.5 annotations is not possible.\n" +
"Ensure that you are using a correct JRE.";
}
if(re.getCause()!=re) {
return getProbableSolutionOrCause( re.getCause() );
}
return null;
}
private void validateParameters() {
if(generators.isEmpty()) {
throw new BuildException("No exporters specified in <hibernatetool>. There has to be at least one specified. An exporter is e.g. <hbm2java> or <hbmtemplate>. See documentation for details.", getLocation());
} else {
for (Object generator : generators) {
ExporterTask generatorTask = (ExporterTask) generator;
generatorTask.validateParameters();
}
}
}
/**
* @return
*/
public File getDestDir() {
return destDir;
}
public void setDestDir(File file) {
destDir = file;
}
/**
* @return
*/
public Configuration getConfiguration() {
return configurationTask.getConfiguration();
}
public void setTemplatePath(Path path) {
templatePath = path;
}
public Path getTemplatePath() {
if(templatePath==null) {
templatePath = new Path(getProject()); // empty path
}
return templatePath;
}
public Properties getProperties() {
Properties p = new Properties();
p.putAll(getConfiguration().getProperties());
p.putAll(properties);
return p;
}
public void addConfiguredPropertySet(PropertySet ps) {
properties.putAll(ps.getProperties());
}
public void addConfiguredProperty(Environment.Variable property) {
properties.put(property.getKey(), property.getValue());
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.01.28 at 02:10:24 PM CST
//
package org.mesa.xml.b2mml;
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;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for OperationsMaterialBillItemType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="OperationsMaterialBillItemType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType"/>
* <element name="Description" type="{http://www.mesa.org/xml/B2MML-V0600}DescriptionType" minOccurs="0"/>
* <element name="MaterialClassID" type="{http://www.mesa.org/xml/B2MML-V0600}MaterialClassIDType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="MaterialDefinitionID" type="{http://www.mesa.org/xml/B2MML-V0600}MaterialDefinitionIDType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="UseType" type="{http://www.mesa.org/xml/B2MML-V0600}CodeType" minOccurs="0"/>
* <element name="AssemblyBillOfMaterialItem" type="{http://www.mesa.org/xml/B2MML-V0600}OperationsMaterialBillItemType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="AssemblyType" type="{http://www.mesa.org/xml/B2MML-V0600}AssemblyTypeType" minOccurs="0"/>
* <element name="AssemblyRelationship" type="{http://www.mesa.org/xml/B2MML-V0600}AssemblyRelationshipType" minOccurs="0"/>
* <element name="MaterialSpecificationID" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Quantity" type="{http://www.mesa.org/xml/B2MML-V0600}QuantityValueType" maxOccurs="unbounded" minOccurs="0"/>
* <group ref="{http://www.mesa.org/xml/B2MML-V0600-AllExtensions}OperationsBillOfMaterialItem" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OperationsMaterialBillItemType", propOrder = {
"id",
"description",
"materialClassID",
"materialDefinitionID",
"useType",
"assemblyBillOfMaterialItem",
"assemblyType",
"assemblyRelationship",
"materialSpecificationID",
"quantity"
})
public class OperationsMaterialBillItemType {
@XmlElement(name = "ID", required = true)
protected IdentifierType id;
@XmlElement(name = "Description")
protected DescriptionType description;
@XmlElement(name = "MaterialClassID")
protected List<MaterialClassIDType> materialClassID;
@XmlElement(name = "MaterialDefinitionID")
protected List<MaterialDefinitionIDType> materialDefinitionID;
@XmlElement(name = "UseType")
protected CodeType useType;
@XmlElement(name = "AssemblyBillOfMaterialItem")
protected List<OperationsMaterialBillItemType> assemblyBillOfMaterialItem;
@XmlElement(name = "AssemblyType")
protected AssemblyTypeType assemblyType;
@XmlElement(name = "AssemblyRelationship")
protected AssemblyRelationshipType assemblyRelationship;
@XmlElement(name = "MaterialSpecificationID")
protected List<IdentifierType> materialSpecificationID;
@XmlElement(name = "Quantity")
protected List<QuantityValueType> quantity;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link IdentifierType }
*
*/
public IdentifierType getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link IdentifierType }
*
*/
public void setID(IdentifierType value) {
this.id = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link DescriptionType }
*
*/
public DescriptionType getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link DescriptionType }
*
*/
public void setDescription(DescriptionType value) {
this.description = value;
}
/**
* Gets the value of the materialClassID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the materialClassID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMaterialClassID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link MaterialClassIDType }
*
*
*/
public List<MaterialClassIDType> getMaterialClassID() {
if (materialClassID == null) {
materialClassID = new ArrayList<MaterialClassIDType>();
}
return this.materialClassID;
}
/**
* Gets the value of the materialDefinitionID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the materialDefinitionID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMaterialDefinitionID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link MaterialDefinitionIDType }
*
*
*/
public List<MaterialDefinitionIDType> getMaterialDefinitionID() {
if (materialDefinitionID == null) {
materialDefinitionID = new ArrayList<MaterialDefinitionIDType>();
}
return this.materialDefinitionID;
}
/**
* Gets the value of the useType property.
*
* @return
* possible object is
* {@link CodeType }
*
*/
public CodeType getUseType() {
return useType;
}
/**
* Sets the value of the useType property.
*
* @param value
* allowed object is
* {@link CodeType }
*
*/
public void setUseType(CodeType value) {
this.useType = value;
}
/**
* Gets the value of the assemblyBillOfMaterialItem property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the assemblyBillOfMaterialItem property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAssemblyBillOfMaterialItem().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link OperationsMaterialBillItemType }
*
*
*/
public List<OperationsMaterialBillItemType> getAssemblyBillOfMaterialItem() {
if (assemblyBillOfMaterialItem == null) {
assemblyBillOfMaterialItem = new ArrayList<OperationsMaterialBillItemType>();
}
return this.assemblyBillOfMaterialItem;
}
/**
* Gets the value of the assemblyType property.
*
* @return
* possible object is
* {@link AssemblyTypeType }
*
*/
public AssemblyTypeType getAssemblyType() {
return assemblyType;
}
/**
* Sets the value of the assemblyType property.
*
* @param value
* allowed object is
* {@link AssemblyTypeType }
*
*/
public void setAssemblyType(AssemblyTypeType value) {
this.assemblyType = value;
}
/**
* Gets the value of the assemblyRelationship property.
*
* @return
* possible object is
* {@link AssemblyRelationshipType }
*
*/
public AssemblyRelationshipType getAssemblyRelationship() {
return assemblyRelationship;
}
/**
* Sets the value of the assemblyRelationship property.
*
* @param value
* allowed object is
* {@link AssemblyRelationshipType }
*
*/
public void setAssemblyRelationship(AssemblyRelationshipType value) {
this.assemblyRelationship = value;
}
/**
* Gets the value of the materialSpecificationID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the materialSpecificationID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMaterialSpecificationID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link IdentifierType }
*
*
*/
public List<IdentifierType> getMaterialSpecificationID() {
if (materialSpecificationID == null) {
materialSpecificationID = new ArrayList<IdentifierType>();
}
return this.materialSpecificationID;
}
/**
* Gets the value of the quantity property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the quantity property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getQuantity().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link QuantityValueType }
*
*
*/
public List<QuantityValueType> getQuantity() {
if (quantity == null) {
quantity = new ArrayList<QuantityValueType>();
}
return this.quantity;
}
}
|
package com.csmugene.gridpagerview.listener;
import android.view.ViewGroup;
import com.csmugene.gridpagerview.adapter.AdapterViewHolder;
import java.util.List;
/**
* Created by ichungseob on 2018. 8. 20..
*/
public interface OnBinderViewHolderListener {
void onBindViewHolder(AdapterViewHolder holder, int position, List<String> iconUrlArrayList, List<String> titleArrayList);
AdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType);
}
|
/*
* 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 PRO1041.FORM;
import java.awt.Image;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import PRO1041.DAO.NhanVienDAO;
/**
/**
*
* @author phamt
*/
public class NhanVien extends javax.swing.JFrame {
String username="sa";
String password="123";
String url="jdbc:sqlserver://localhost:1433;databaseName=QL_NhaXe";
private String header[] = {"Mã NV","Họ Tên","Email","Số ĐT","Giới Tính","Chức Vụ","Hình Ảnh"};
private DefaultTableModel tblModel = new DefaultTableModel(header, 0);
private ArrayList<NhanVienDAO> list = new ArrayList<NhanVienDAO>();
String strHinhanh = null;
String thongbao = "";
private int curredIndex=-1;
/**
* Creates new form NhanVien
*/
public NhanVien() {
initComponents();
buttonGroup1.add(rb_nam);
buttonGroup1.add(rb_nu);
loadDataToTable();
LoadData();
}
public void loadDataToTable(){
try {
tblModel.setRowCount(0);
Connection con = DriverManager.getConnection(url,username,password);
Statement st = con.createStatement();
String sql = "select * from NhanVien";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
Vector r = new Vector();
r.add(rs.getInt(1));
r.add(rs.getString(2));
r.add(rs.getString(3));
r.add(rs.getString(4));
r.add(rs.getString(5));
r.add(rs.getString(6));
r.add(rs.getString(7));
tblModel.addRow(r);
}
tbl_nv.setModel(tblModel);
con.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
public void LoadData(){
Connection conn = null;
Statement stm = null;
try {
conn = DriverManager.getConnection(url,username,password);
stm = conn.createStatement();
String sql = "";
sql = "select * from NhanVien";
ResultSet rs = stm.executeQuery(sql);
list.clear();
while(rs.next()){
String MaNV = rs.getString("MaNV");
String TenNV = rs.getString("TenNV");
String SDT = rs.getString("SoDT");
boolean GioiTinh = rs.getBoolean("GioiTinh");
String Email = rs.getString("Email");
String ChucVu = rs.getString("ChucVu");
String HinhAnh = rs.getString("Hinh");
NhanVienDAO diemNV = new NhanVienDAO(MaNV, TenNV, SDT, GioiTinh, Email, ChucVu, HinhAnh);
list.add(diemNV);
}
curredIndex=0;
DislayNV();
rs.close();
stm.close();
conn.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
public void LoadImage(String hinh){
ImageIcon image1 = new ImageIcon("src\\IMG\\ImageNV\\" +hinh);
Image im = image1.getImage();
ImageIcon icon1 = new ImageIcon(im.getScaledInstance(btn_anh.getWidth(), btn_anh.getHeight(), im.SCALE_SMOOTH));
btn_anh.setIcon(icon1);
}
public void DislayNV(){
NhanVienDAO nvs = list.get(curredIndex);
txt_ma.setText(nvs.MaNV);
txt_ten.setText(nvs.TenNV);
txt_sdt.setText(nvs.SDT);
rb_nam.setSelected(nvs.GioiTinh);
rb_nu.setSelected(nvs.GioiTinh);
txt_email.setText(nvs.Email);
cbb_chucvu.setSelectedItem(nvs.ChucVu);
LoadImage(nvs.HinhAnh);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
btn_them = new javax.swing.JButton();
txt_ma = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
txt_ten = new javax.swing.JTextField();
rb_nam = new javax.swing.JRadioButton();
rb_nu = new javax.swing.JRadioButton();
cbb_chucvu = new javax.swing.JComboBox<>();
jButton1 = new javax.swing.JButton();
btn_sua = new javax.swing.JButton();
jLabel13 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
txt_email = new javax.swing.JTextField();
txt_sdt = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
btn_back = new javax.swing.JButton();
btn_reset = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tbl_nv = new javax.swing.JTable();
btn_anh = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
btn_timkiem = new javax.swing.JButton();
txt_timkiem = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
background = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setLocation(new java.awt.Point(325, 90));
jPanel1.setLayout(null);
btn_them.setBackground(new java.awt.Color(162, 218, 246));
btn_them.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btn_them.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/themnv.png"))); // NOI18N
btn_them.setText("Thêm Nhân Viên");
btn_them.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_themActionPerformed(evt);
}
});
jPanel1.add(btn_them);
btn_them.setBounds(100, 210, 440, 50);
jPanel1.add(txt_ma);
txt_ma.setBounds(150, 60, 180, 30);
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel7.setForeground(new java.awt.Color(0, 58, 145));
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel7.setText("Nhân Viên");
jPanel1.add(jLabel7);
jLabel7.setBounds(60, 10, 640, 44);
jLabel8.setText("Tên nhân viên:");
jPanel1.add(jLabel8);
jLabel8.setBounds(70, 110, 80, 14);
jLabel10.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel10.setText("Ảnh");
jPanel1.add(jLabel10);
jLabel10.setBounds(600, 40, 80, 30);
jLabel11.setText("Giới tính:");
jPanel1.add(jLabel11);
jLabel11.setBounds(70, 180, 60, 14);
jPanel1.add(txt_ten);
txt_ten.setBounds(150, 100, 180, 30);
rb_nam.setText("Nam");
jPanel1.add(rb_nam);
rb_nam.setBounds(150, 180, 50, 23);
rb_nu.setText("Nữ");
jPanel1.add(rb_nu);
rb_nu.setBounds(220, 180, 40, 23);
cbb_chucvu.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Admin", "Nhân Viên", " " }));
jPanel1.add(cbb_chucvu);
cbb_chucvu.setBounds(410, 80, 90, 30);
jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/xoa.png"))); // NOI18N
jButton1.setText("Xóa Nhân Viên");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1);
jButton1.setBounds(160, 480, 170, 50);
btn_sua.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btn_sua.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/icon-bao-hanh.png"))); // NOI18N
btn_sua.setText("Sửa Thông Tin");
btn_sua.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_suaActionPerformed(evt);
}
});
jPanel1.add(btn_sua);
btn_sua.setBounds(390, 480, 170, 50);
jLabel13.setText("Email:");
jPanel1.add(jLabel13);
jLabel13.setBounds(350, 120, 40, 14);
jLabel12.setText("Chức vụ:");
jPanel1.add(jLabel12);
jLabel12.setBounds(350, 80, 50, 14);
jLabel9.setText("SDT:");
jPanel1.add(jLabel9);
jLabel9.setBounds(70, 150, 30, 14);
jPanel1.add(txt_email);
txt_email.setBounds(410, 120, 120, 30);
jPanel1.add(txt_sdt);
txt_sdt.setBounds(150, 140, 180, 30);
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel6.setText("Mã nhân viên:");
jPanel1.add(jLabel6);
jLabel6.setBounds(70, 70, 76, 15);
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel5.setText("Back");
jPanel1.add(jLabel5);
jLabel5.setBounds(20, 84, 40, 20);
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel4.setText("Reset");
jPanel1.add(jLabel4);
jLabel4.setBounds(20, 200, 40, 15);
btn_back.setBackground(new java.awt.Color(244, 143, 143));
btn_back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/ql.png"))); // NOI18N
btn_back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_backActionPerformed(evt);
}
});
jPanel1.add(btn_back);
btn_back.setBounds(10, 30, 50, 90);
btn_reset.setBackground(new java.awt.Color(99, 114, 252));
btn_reset.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/reset.png"))); // NOI18N
btn_reset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_resetActionPerformed(evt);
}
});
jPanel1.add(btn_reset);
btn_reset.setBounds(10, 140, 50, 90);
tbl_nv.setBackground(new java.awt.Color(204, 204, 255));
tbl_nv.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tbl_nv.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tbl_nvMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tbl_nv);
jPanel1.add(jScrollPane1);
jScrollPane1.setBounds(70, 340, 600, 90);
btn_anh.setBackground(new java.awt.Color(169, 209, 238));
btn_anh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/them.png"))); // NOI18N
btn_anh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_anhActionPerformed(evt);
}
});
jPanel1.add(btn_anh);
btn_anh.setBounds(560, 70, 150, 160);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/background/nen2.png"))); // NOI18N
jPanel1.add(jLabel3);
jLabel3.setBounds(50, 10, 670, 250);
btn_timkiem.setBackground(new java.awt.Color(204, 204, 0));
btn_timkiem.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
btn_timkiem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/icontimnhanvien.png"))); // NOI18N
btn_timkiem.setText("Tìm");
btn_timkiem.setAlignmentY(0.0F);
btn_timkiem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_timkiemActionPerformed(evt);
}
});
jPanel1.add(btn_timkiem);
btn_timkiem.setBounds(500, 280, 170, 49);
txt_timkiem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_timkiemActionPerformed(evt);
}
});
jPanel1.add(txt_timkiem);
txt_timkiem.setBounds(70, 290, 400, 40);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/background/nen3.png"))); // NOI18N
jPanel1.add(jLabel1);
jLabel1.setBounds(20, 0, 730, 550);
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/background/Untitled-3.png"))); // NOI18N
jPanel1.add(jLabel2);
jLabel2.setBounds(30, 0, 720, 450);
background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/background/nen1.png"))); // NOI18N
background.setText("back");
jPanel1.add(background);
background.setBounds(0, 0, 770, 560);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 763, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 555, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txt_timkiemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_timkiemActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_timkiemActionPerformed
private void btn_anhActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_anhActionPerformed
try {
JFileChooser choose=new JFileChooser("src\\IMG\\ImageNV");
int chon=choose.showOpenDialog(this);
File file = choose.getSelectedFile();
Image img = ImageIO.read(file);
strHinhanh = file.getName();
int width = btn_anh.getWidth();
int height= btn_anh.getHeight();
btn_anh.setIcon(new ImageIcon(img.getScaledInstance(width, height, 0)));
}catch(Exception e){
System.out.println(e.toString());
}
}//GEN-LAST:event_btn_anhActionPerformed
private void tbl_nvMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_nvMouseClicked
int r = tbl_nv.getSelectedRow();
if (r < 0) {
return;
}
txt_ma.setText(tbl_nv.getValueAt(r, 0).toString());
txt_ten.setText(tbl_nv.getValueAt(r, 1).toString());
txt_sdt.setText(tbl_nv.getValueAt(r, 2).toString());
txt_email.setText(tbl_nv.getValueAt(r, 3).toString());
if ((tbl_nv.getValueAt(r, 4).toString()).equals("1")) {
rb_nam.setSelected(true);
}else {
rb_nu.setSelected(true);
}
cbb_chucvu.setSelectedItem(tbl_nv.getValueAt(r, 5).toString());
LoadImage(tbl_nv.getValueAt(r, 6).toString());
}//GEN-LAST:event_tbl_nvMouseClicked
private void btn_themActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_themActionPerformed
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(url, username, password);
String sql = "insert into NhanVien values(?,?,?,?,?,?)\n";
PreparedStatement st = con.prepareStatement(sql);
st.setString(1, txt_ten.getText());
st.setString(2, txt_sdt.getText());
st.setString(3, txt_email.getText());
st.setString(5, cbb_chucvu.getSelectedItem().toString());
st.setString(6, strHinhanh);
boolean gt;
if (rb_nam.isSelected()) {
gt = true;
} else {
gt = false;
}
st.setBoolean(4, gt);
st.executeUpdate();
JOptionPane.showMessageDialog(this, "Thêm nhân viên thành công");
con.close();
loadDataToTable();
} catch (Exception e) {
System.out.println(e);
}
}//GEN-LAST:event_btn_themActionPerformed
private void btn_timkiemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_timkiemActionPerformed
int i;
String manv = txt_timkiem.getText();
for (i = 0; i < list.size(); i++) {
NhanVienDAO nv = list.get(i);
if (nv.MaNV.equals(manv) == true) {
curredIndex = i;
tbl_nv.setRowSelectionInterval(curredIndex, curredIndex);
DislayNV();
break;
}
}
if (i == list.size()) {
JOptionPane.showMessageDialog(this, "Không tìm thấy nhân viên");
}
}//GEN-LAST:event_btn_timkiemActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
int ret = JOptionPane.showConfirmDialog(this, "Bạn có muốn xóa không?", "Có",
JOptionPane.YES_NO_OPTION);
if (ret != JOptionPane.YES_OPTION) {
return;
}
Connection c = null;
PreparedStatement ps = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
c = DriverManager.getConnection(url, username, password);
ps = c.prepareStatement("Delete From NhanVien where MaNV = ?");
ps.setString(1, txt_ma.getText());
String ten = txt_ten.getText();
ret = ps.executeUpdate();
if (ret != -1) {
JOptionPane.showMessageDialog(this, "Đã xóa nhân viên " + ten);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (c != null) {
c.close();
}
if (ps != null) {
ps.close();
loadDataToTable();
LoadData();
}
} catch (Exception ex2) {
ex2.printStackTrace();
}
}
}//GEN-LAST:event_jButton1ActionPerformed
private void btn_suaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_suaActionPerformed
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(url, username, password);
String sql = "update NhanVien set TenNV=?, SoDT=?, Email=?, GioiTinh=?, ChucVu=?, Hinh=? where MaNV=?";
PreparedStatement st = con.prepareStatement(sql);
st.setString(1, txt_ten.getText());
st.setString(2, txt_sdt.getText());
st.setString(3, txt_email.getText());
st.setString(6, strHinhanh);
boolean gt;
if (rb_nam.isSelected()) {
gt = true;
} else {
gt = false;
}
st.setBoolean(4, gt);
st.setString(5, cbb_chucvu.getSelectedItem().toString());
st.setString(7, txt_ma.getText());
st.executeUpdate();
JOptionPane.showMessageDialog(this, "Sửa thông tin thành công thành công");
con.close();
loadDataToTable();
LoadData();
} catch (Exception e) {
System.out.println(e);
JOptionPane.showMessageDialog(this, "Error");
}
}//GEN-LAST:event_btn_suaActionPerformed
private void btn_backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_backActionPerformed
TrangChu tx = new TrangChu();
tx.setVisible(true);
dispose();
}//GEN-LAST:event_btn_backActionPerformed
private void btn_resetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_resetActionPerformed
txt_ma.setText("");
txt_ten.setText("");
txt_sdt.setText("");
rb_nam.setSelected(false);
rb_nu.setSelected(false);
txt_email.setText("");
cbb_chucvu.setSelectedItem("");
LoadImage("");
}//GEN-LAST:event_btn_resetActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NhanVien.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NhanVien.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NhanVien.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NhanVien.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NhanVien().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel background;
private javax.swing.JButton btn_anh;
private javax.swing.JButton btn_back;
private javax.swing.JButton btn_reset;
private javax.swing.JButton btn_sua;
private javax.swing.JButton btn_them;
private javax.swing.JButton btn_timkiem;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JComboBox<String> cbb_chucvu;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JRadioButton rb_nam;
private javax.swing.JRadioButton rb_nu;
private javax.swing.JTable tbl_nv;
private javax.swing.JTextField txt_email;
private javax.swing.JTextField txt_ma;
private javax.swing.JTextField txt_sdt;
private javax.swing.JTextField txt_ten;
private javax.swing.JTextField txt_timkiem;
// End of variables declaration//GEN-END:variables
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tez.runtime.library.cartesianproduct;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.tez.dag.api.EdgeManagerPluginDescriptor;
import org.apache.tez.dag.api.EdgeProperty;
import org.apache.tez.dag.api.VertexLocationHint;
import org.apache.tez.dag.api.VertexManagerPluginContext;
import org.apache.tez.dag.api.VertexManagerPluginContext.ScheduleTaskRequest;
import org.apache.tez.dag.api.event.VertexState;
import org.apache.tez.dag.api.event.VertexStateUpdate;
import org.apache.tez.dag.records.TaskAttemptIdentifierImpl;
import org.apache.tez.dag.records.TezDAGID;
import org.apache.tez.dag.records.TezTaskAttemptID;
import org.apache.tez.dag.records.TezTaskID;
import org.apache.tez.dag.records.TezVertexID;
import org.apache.tez.runtime.api.TaskAttemptIdentifier;
import org.apache.tez.runtime.api.events.VertexManagerEvent;
import org.apache.tez.runtime.library.shuffle.impl.ShuffleUserPayloads.VertexManagerEventPayloadProto;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.tez.dag.api.EdgeProperty.DataMovementType.BROADCAST;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyMapOf;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class TestCartesianProductVertexManagerUnpartitioned {
private static long desiredBytesPerGroup = 1000;
@Captor
private ArgumentCaptor<Map<String, EdgeProperty>> edgePropertiesCaptor;
@Captor
private ArgumentCaptor<List<ScheduleTaskRequest>> scheduleRequestCaptor;
@Captor
private ArgumentCaptor<Integer> parallelismCaptor;
private CartesianProductVertexManagerUnpartitioned vertexManager;
private VertexManagerPluginContext ctx;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
ctx = mock(VertexManagerPluginContext.class);
vertexManager = new CartesianProductVertexManagerUnpartitioned(ctx);
}
/**
* v0 and v1 are two cartesian product sources
*/
private void setupDAGVertexOnly(boolean doGrouping) throws Exception {
when(ctx.getInputVertexEdgeProperties()).thenReturn(getEdgePropertyMap(2));
setSrcParallelism(ctx, doGrouping ? 10 : 1, 2, 3);
CartesianProductVertexManagerConfig config = new CartesianProductVertexManagerConfig(
false, new String[]{"v0","v1"}, null, 0, 0, doGrouping, desiredBytesPerGroup, null);
vertexManager.initialize(config);
}
/**
* v0 and v1 are two cartesian product sources; v2 is broadcast source; without auto grouping
*/
private void setupDAGVertexOnlyWithBroadcast() throws Exception {
Map<String, EdgeProperty> edgePropertyMap = getEdgePropertyMap(2);
edgePropertyMap.put("v2", EdgeProperty.create(BROADCAST, null, null, null, null));
when(ctx.getInputVertexEdgeProperties()).thenReturn(edgePropertyMap);
setSrcParallelism(ctx, 2, 3, 5);
CartesianProductVertexManagerConfig config =
new CartesianProductVertexManagerConfig(
false, new String[]{"v0","v1"}, null, 0, 0, false, 0, null);
vertexManager.initialize(config);
}
/**
* v0 and g0 are two sources; g0 is vertex group of v1 and v2
*/
private void setupDAGVertexGroup(boolean doGrouping) throws Exception {
when(ctx.getInputVertexEdgeProperties()).thenReturn(getEdgePropertyMap(3));
setSrcParallelism(ctx, doGrouping ? 10: 1, 2, 3, 4);
Map<String, List<String>> vertexGroupMap = new HashMap<>();
vertexGroupMap.put("g0", Arrays.asList("v1", "v2"));
when(ctx.getInputVertexGroups()).thenReturn(vertexGroupMap);
CartesianProductVertexManagerConfig config = new CartesianProductVertexManagerConfig(
false, new String[]{"v0","g0"}, null, 0, 0, doGrouping, desiredBytesPerGroup, null);
vertexManager.initialize(config);
}
/**
* g0 and g1 are two sources; g0 is vertex group of v0 and v1; g1 is vertex group of v2 and v3
*/
private void setupDAGVertexGroupOnly(boolean doGrouping) throws Exception {
when(ctx.getInputVertexEdgeProperties()).thenReturn(getEdgePropertyMap(4));
setSrcParallelism(ctx, doGrouping ? 10 : 1, 2, 3, 4, 5);
Map<String, List<String>> vertexGroupMap = new HashMap<>();
vertexGroupMap.put("g0", Arrays.asList("v0", "v1"));
vertexGroupMap.put("g1", Arrays.asList("v2", "v3"));
when(ctx.getInputVertexGroups()).thenReturn(vertexGroupMap);
CartesianProductVertexManagerConfig config = new CartesianProductVertexManagerConfig(
false, new String[]{"g0","g1"}, null, 0, 0, doGrouping, desiredBytesPerGroup, null);
vertexManager.initialize(config);
}
private Map<String, EdgeProperty> getEdgePropertyMap(int numSrcV) {
Map<String, EdgeProperty> edgePropertyMap = new HashMap<>();
for (int i = 0; i < numSrcV; i++) {
edgePropertyMap.put("v"+i, EdgeProperty.create(EdgeManagerPluginDescriptor.create(
CartesianProductEdgeManager.class.getName()), null, null, null, null));
}
return edgePropertyMap;
}
private void setSrcParallelism(VertexManagerPluginContext ctx, int multiplier, int... numTasks) {
int i = 0;
for (int numTask : numTasks) {
when(ctx.getVertexNumTasks(eq("v"+i))).thenReturn(numTask * multiplier);
i++;
}
}
private TaskAttemptIdentifier getTaId(String vertexName, int taskId) {
return new TaskAttemptIdentifierImpl("dag", vertexName,
TezTaskAttemptID.getInstance(TezTaskID.getInstance(TezVertexID.getInstance(
TezDAGID.getInstance("0", 0, 0), 0), taskId), 0));
}
private VertexManagerEvent getVMEevnt(long outputSize, String vName, int taskId) {
VertexManagerEventPayloadProto.Builder builder = VertexManagerEventPayloadProto.newBuilder();
builder.setOutputSize(outputSize);
VertexManagerEvent vmEvent =
VertexManagerEvent.create("cp vertex", builder.build().toByteString().asReadOnlyByteBuffer());
vmEvent.setProducerAttemptIdentifier(getTaId(vName, taskId));
return vmEvent;
}
private void verifyEdgeProperties(EdgeProperty edgeProperty, String[] sources,
int[] numChunksPerSrc, int numChunk, int chunkIdOffset)
throws InvalidProtocolBufferException {
CartesianProductEdgeManagerConfig conf = CartesianProductEdgeManagerConfig.fromUserPayload(
edgeProperty.getEdgeManagerDescriptor().getUserPayload());
assertArrayEquals(sources, conf.getSourceVertices().toArray());
assertArrayEquals(numChunksPerSrc, conf.numChunksPerSrc);
assertEquals(numChunk, conf.numChunk);
assertEquals(chunkIdOffset, conf.chunkIdOffset);
}
private void verifyScheduleRequest(int expectedTimes, int... expectedTid) {
verify(ctx, times(expectedTimes)).scheduleTasks(scheduleRequestCaptor.capture());
if (expectedTimes > 0) {
List<ScheduleTaskRequest> requests = scheduleRequestCaptor.getValue();
int i = 0;
for (int tid : expectedTid) {
assertEquals(tid, requests.get(i).getTaskIndex());
i++;
}
}
}
@Test(timeout = 5000)
public void testDAGVertexOnly() throws Exception {
setupDAGVertexOnly(false);
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v0", VertexState.CONFIGURED));
verify(ctx, never()).reconfigureVertex(
anyInt(), any(VertexLocationHint.class), anyMapOf(String.class, EdgeProperty.class));
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v1", VertexState.CONFIGURED));
verify(ctx, times(1)).reconfigureVertex(parallelismCaptor.capture(),
isNull(VertexLocationHint.class), edgePropertiesCaptor.capture());
assertEquals(6, (int) parallelismCaptor.getValue());
Map<String, EdgeProperty> edgeProperties = edgePropertiesCaptor.getValue();
verifyEdgeProperties(edgeProperties.get("v0"), new String[]{"v0", "v1"}, new int[]{2, 3}, 2, 0);
verifyEdgeProperties(edgeProperties.get("v1"), new String[]{"v0", "v1"}, new int[]{2, 3}, 3, 0);
vertexManager.onVertexStarted(null);
verifyScheduleRequest(0);
vertexManager.onSourceTaskCompleted(getTaId("v0", 0));
verify(ctx, never()).scheduleTasks(scheduleRequestCaptor.capture());
vertexManager.onSourceTaskCompleted(getTaId("v1", 0));
verify(ctx, times(1)).scheduleTasks(scheduleRequestCaptor.capture());
verifyScheduleRequest(1, 0);
vertexManager.onSourceTaskCompleted(getTaId("v1", 1));
verify(ctx, times(2)).scheduleTasks(scheduleRequestCaptor.capture());
verifyScheduleRequest(2, 1);
}
@Test(timeout = 5000)
public void testDAGVertexOnlyWithGrouping() throws Exception {
setupDAGVertexOnly(true);
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v0", VertexState.CONFIGURED));
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v1", VertexState.CONFIGURED));
vertexManager.onVertexManagerEventReceived(getVMEevnt(desiredBytesPerGroup, "v0", 0));
verify(ctx, never()).reconfigureVertex(
anyInt(), any(VertexLocationHint.class), anyMapOf(String.class, EdgeProperty.class));
vertexManager.onVertexManagerEventReceived(getVMEevnt(1, "v1", 0));
verify(ctx, never()).reconfigureVertex(
anyInt(), any(VertexLocationHint.class), anyMapOf(String.class, EdgeProperty.class));
vertexManager.onVertexManagerEventReceived(getVMEevnt(0, "v0", 1));
for (int i = 1; i < 30; i++) {
vertexManager.onVertexManagerEventReceived(getVMEevnt(1, "v1", i));
}
verify(ctx, times(1)).reconfigureVertex(
anyInt(), any(VertexLocationHint.class), edgePropertiesCaptor.capture());
Map<String, EdgeProperty> edgeProperties = edgePropertiesCaptor.getValue();
verifyEdgeProperties(edgeProperties.get("v0"), new String[]{"v0", "v1"}, new int[]{10, 1}, 10, 0);
verifyEdgeProperties(edgeProperties.get("v1"), new String[]{"v0", "v1"}, new int[]{10, 1}, 1, 0);
vertexManager.onVertexStarted(null);
verifyScheduleRequest(0);
vertexManager.onSourceTaskCompleted(getTaId("v0", 0));
vertexManager.onSourceTaskCompleted(getTaId("v0", 1));
for (int i = 0; i < 29; i++) {
vertexManager.onSourceTaskCompleted(getTaId("v1", i));
}
verifyScheduleRequest(0);
vertexManager.onSourceTaskCompleted(getTaId("v1", 29));
verifyScheduleRequest(1, 0);
}
@Test(timeout = 5000)
public void testDAGVertexGroup() throws Exception {
setupDAGVertexGroup(false);
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v0", VertexState.CONFIGURED));
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v1", VertexState.CONFIGURED));
verify(ctx, never()).reconfigureVertex(
anyInt(), any(VertexLocationHint.class), anyMapOf(String.class, EdgeProperty.class));
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v2", VertexState.CONFIGURED));
verify(ctx, times(1)).reconfigureVertex(parallelismCaptor.capture(),
isNull(VertexLocationHint.class), edgePropertiesCaptor.capture());
assertEquals(14, (int) parallelismCaptor.getValue());
Map<String, EdgeProperty> edgeProperties = edgePropertiesCaptor.getValue();
verifyEdgeProperties(edgeProperties.get("v0"), new String[]{"v0", "g0"}, new int[]{2, 7}, 2, 0);
verifyEdgeProperties(edgeProperties.get("v1"), new String[]{"v0", "g0"}, new int[]{2, 7}, 3, 0);
verifyEdgeProperties(edgeProperties.get("v2"), new String[]{"v0", "g0"}, new int[]{2, 7}, 4, 3);
vertexManager.onVertexStarted(null);
verifyScheduleRequest(0);
vertexManager.onSourceTaskCompleted(getTaId("v0",1));
vertexManager.onSourceTaskCompleted(getTaId("v1",2));
verifyScheduleRequest(1, 9);
vertexManager.onSourceTaskCompleted(getTaId("v2", 0));
verifyScheduleRequest(2, 10);
}
@Test(timeout = 5000)
public void testDAGVertexGroupWithGrouping() throws Exception {
setupDAGVertexGroup(true);
for (int i = 0; i < 3; i++) {
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v" + i, VertexState.CONFIGURED));
}
vertexManager.onVertexManagerEventReceived(getVMEevnt(desiredBytesPerGroup, "v0", 0));
vertexManager.onVertexManagerEventReceived(getVMEevnt(desiredBytesPerGroup, "v1", 0));
verify(ctx, never()).reconfigureVertex(
anyInt(), any(VertexLocationHint.class), anyMapOf(String.class, EdgeProperty.class));
vertexManager.onVertexManagerEventReceived(getVMEevnt(0, "v0", 1));
for (int i = 0; i < 40; i++) {
vertexManager.onVertexManagerEventReceived(getVMEevnt(1, "v2", i));
}
verify(ctx, times(1)).reconfigureVertex(
anyInt(), any(VertexLocationHint.class), edgePropertiesCaptor.capture());
Map<String, EdgeProperty> edgeProperties = edgePropertiesCaptor.getValue();
verifyEdgeProperties(edgeProperties.get("v0"), new String[]{"v0", "g0"}, new int[]{10, 31}, 10, 0);
verifyEdgeProperties(edgeProperties.get("v1"), new String[]{"v0", "g0"}, new int[]{10, 31}, 30, 0);
verifyEdgeProperties(edgeProperties.get("v2"), new String[]{"v0", "g0"}, new int[]{10, 31}, 1, 30);
vertexManager.onVertexStarted(null);
verifyScheduleRequest(0);
vertexManager.onSourceTaskCompleted(getTaId("v0", 0));
vertexManager.onSourceTaskCompleted(getTaId("v1", 10));
vertexManager.onSourceTaskCompleted(getTaId("v2", 0));
verifyScheduleRequest(0);
vertexManager.onSourceTaskCompleted(getTaId("v0", 1));
verifyScheduleRequest(1, 10);
for (int i = 1; i < 40; i++) {
vertexManager.onSourceTaskCompleted(getTaId("v2", i));
}
verifyScheduleRequest(2, 30);
}
@Test(timeout = 5000)
public void testDAGVertexGroupOnly() throws Exception {
setupDAGVertexGroupOnly(false);
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v0", VertexState.CONFIGURED));
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v2", VertexState.CONFIGURED));
verify(ctx, never()).reconfigureVertex(
anyInt(), any(VertexLocationHint.class), anyMapOf(String.class, EdgeProperty.class));
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v1", VertexState.CONFIGURED));
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v3", VertexState.CONFIGURED));
verify(ctx, times(1)).reconfigureVertex(parallelismCaptor.capture(),
isNull(VertexLocationHint.class), edgePropertiesCaptor.capture());
assertEquals(45, (int) parallelismCaptor.getValue());
Map<String, EdgeProperty> edgeProperties = edgePropertiesCaptor.getValue();
verifyEdgeProperties(edgeProperties.get("v0"), new String[]{"g0", "g1"}, new int[]{5, 9}, 2, 0);
verifyEdgeProperties(edgeProperties.get("v1"), new String[]{"g0", "g1"}, new int[]{5, 9}, 3, 2);
verifyEdgeProperties(edgeProperties.get("v2"), new String[]{"g0", "g1"}, new int[]{5, 9}, 4, 0);
verifyEdgeProperties(edgeProperties.get("v3"), new String[]{"g0", "g1"}, new int[]{5, 9}, 5, 4);
vertexManager.onVertexStarted(null);
verifyScheduleRequest(0);
vertexManager.onSourceTaskCompleted(getTaId("v0", 1));
vertexManager.onSourceTaskCompleted(getTaId("v2", 3));
verifyScheduleRequest(1, 12);
vertexManager.onSourceTaskCompleted(getTaId("v1", 2));
verifyScheduleRequest(2, 39);
vertexManager.onSourceTaskCompleted(getTaId("v3", 0));
verifyScheduleRequest(3, 13, 40);
}
@Test(timeout = 5000)
public void testDAGVertexGroupOnlyWithGrouping() throws Exception {
setupDAGVertexGroupOnly(true);
for (int i = 0; i < 4; i++) {
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v" + i, VertexState.CONFIGURED));
}
vertexManager.onVertexManagerEventReceived(getVMEevnt(desiredBytesPerGroup, "v0", 0));
vertexManager.onVertexManagerEventReceived(getVMEevnt(desiredBytesPerGroup, "v2", 0));
verify(ctx, never()).reconfigureVertex(
anyInt(), any(VertexLocationHint.class), anyMapOf(String.class, EdgeProperty.class));
vertexManager.onVertexManagerEventReceived(getVMEevnt(0, "v0", 1));
for (int i = 0; i < 5; i++) {
vertexManager.onVertexManagerEventReceived(getVMEevnt(desiredBytesPerGroup/5, "v1", i));
}
for (int i = 0; i < 50; i++) {
vertexManager.onVertexManagerEventReceived(getVMEevnt(1, "v3", i));
}
verify(ctx, times(1)).reconfigureVertex(
anyInt(), any(VertexLocationHint.class), edgePropertiesCaptor.capture());
Map<String, EdgeProperty> edgeProperties = edgePropertiesCaptor.getValue();
verifyEdgeProperties(edgeProperties.get("v0"), new String[]{"g0", "g1"}, new int[]{16, 41}, 10, 0);
verifyEdgeProperties(edgeProperties.get("v1"), new String[]{"g0", "g1"}, new int[]{16, 41}, 6, 10);
verifyEdgeProperties(edgeProperties.get("v2"), new String[]{"g0", "g1"}, new int[]{16, 41}, 40, 0);
verifyEdgeProperties(edgeProperties.get("v3"), new String[]{"g0", "g1"}, new int[]{16, 41}, 1, 40);
vertexManager.onVertexStarted(null);
verifyScheduleRequest(0);
vertexManager.onSourceTaskCompleted(getTaId("v0", 1));
vertexManager.onSourceTaskCompleted(getTaId("v2", 20));
verifyScheduleRequest(0);
vertexManager.onSourceTaskCompleted(getTaId("v0", 0));
verifyScheduleRequest(1, 20);
vertexManager.onSourceTaskCompleted(getTaId("v3", 0));
verifyScheduleRequest(1);
for (int i = 1; i < 50; i++) {
vertexManager.onSourceTaskCompleted(getTaId("v3", i));
}
verifyScheduleRequest(2, 40);
vertexManager.onSourceTaskCompleted(getTaId("v1", 5));
verifyScheduleRequest(2);
for (int i = 6; i < 10; i++) {
vertexManager.onSourceTaskCompleted(getTaId("v1", i));
}
verifyScheduleRequest(3, 471, 491);
}
@Test(timeout = 5000)
public void testSchedulingVertexOnlyWithBroadcast() throws Exception {
setupDAGVertexOnlyWithBroadcast();
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v0", VertexState.CONFIGURED));
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v1", VertexState.CONFIGURED));
vertexManager.onVertexStarted(null);
verifyScheduleRequest(0);
vertexManager.onSourceTaskCompleted(getTaId("v0", 0));
vertexManager.onSourceTaskCompleted(getTaId("v1", 1));
verifyScheduleRequest(0);
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v2", VertexState.RUNNING));
verifyScheduleRequest(1);
verify(ctx, times(1)).scheduleTasks(scheduleRequestCaptor.capture());
}
@Test(timeout = 5000)
public void testOnVertexStart() throws Exception {
setupDAGVertexOnly(false);
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v0", VertexState.CONFIGURED));
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v1", VertexState.CONFIGURED));
vertexManager.onVertexStarted(Arrays.asList(getTaId("v0", 0), getTaId("v1", 0)));
verifyScheduleRequest(1, 0);
}
@Test(timeout = 5000)
public void testZeroSrcTask() throws Exception {
ctx = mock(VertexManagerPluginContext.class);
vertexManager = new CartesianProductVertexManagerUnpartitioned(ctx);
when(ctx.getVertexNumTasks(eq("v0"))).thenReturn(2);
when(ctx.getVertexNumTasks(eq("v1"))).thenReturn(0);
CartesianProductVertexManagerConfig config =
new CartesianProductVertexManagerConfig(
false, new String[]{"v0","v1"}, null, 0, 0, false, 0, null);
Map<String, EdgeProperty> edgePropertyMap = new HashMap<>();
edgePropertyMap.put("v0", EdgeProperty.create(EdgeManagerPluginDescriptor.create(
CartesianProductEdgeManager.class.getName()), null, null, null, null));
edgePropertyMap.put("v1", EdgeProperty.create(EdgeManagerPluginDescriptor.create(
CartesianProductEdgeManager.class.getName()), null, null, null, null));
when(ctx.getInputVertexEdgeProperties()).thenReturn(edgePropertyMap);
vertexManager.initialize(config);
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v0", VertexState.CONFIGURED));
vertexManager.onVertexStateUpdated(new VertexStateUpdate("v1", VertexState.CONFIGURED));
vertexManager.onVertexStarted(new ArrayList<TaskAttemptIdentifier>());
vertexManager.onSourceTaskCompleted(getTaId("v0", 0));
vertexManager.onSourceTaskCompleted(getTaId("v0", 1));
}
}
|
package com.takshine.wxcrm.service;
import com.takshine.wxcrm.base.services.EntityService;
/**
* 文章信息
*
* @author liulin
*
*/
public interface ArticleInfoService extends EntityService {
}
|
package symcryptolab1;
import java.util.*;
public class FrequencyCounter {
public static Map<String, Integer> count(String text, int nGramLength, boolean identityStep) {
Map<String, Integer> freqs = new TreeMap<>();
int step = identityStep ? 1 : nGramLength;
int limit = text.length() - nGramLength + 1;
for (int i = 0; i < limit; i += step) {
String nGram = text.substring(i, i + nGramLength);
Integer prev = freqs.get(nGram);
freqs.put(nGram, 1 + (prev == null ? 0 : prev));
}
return freqs;
}
}
|
package com.bluesky.admin.api.modules.sys.service;
import com.bluesky.admin.api.modules.sys.vo.AdminRoleVO;
import com.bluesky.admin.api.modules.sys.vo.req.AddRoleWithMenusReq;
import com.bluesky.admin.api.modules.sys.vo.req.AdminRoleRetrieveReq;
import com.bluesky.admin.api.modules.sys.vo.req.ModifyRoleWithMenusReq;
import com.bluesky.admin.api.modules.sys.vo.req.RemoveRoleReq;
import com.github.pagehelper.PageInfo;
/**
* @author Lijinchun
* @Package com.bluesky.admin.api.modules.sys.service
* @date 2019/7/30 22:54
*/
public interface IAdminRoleService {
/**
* 检索角色信息
* @param adminRoleRetrieveReq
* @return
*/
PageInfo<AdminRoleVO> retrieve(AdminRoleRetrieveReq adminRoleRetrieveReq);
/**
* 添加角色附加菜单信息
* @param addRoleWithMenusReq
* @return
*/
boolean addRoleWithMenus(AddRoleWithMenusReq addRoleWithMenusReq);
/**
* 修改角色附加菜单
* @param modifyRoleWithMenusReq
* @return
*/
boolean modifyRoleWithMenus(ModifyRoleWithMenusReq modifyRoleWithMenusReq);
/**
* 删除角色信息
* @param removeRoleReq
* @return
*/
boolean removeRole(RemoveRoleReq removeRoleReq);
}
|
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
/**
* * 数组的相对排序
*
* <p>给你两个数组,arr1 和 arr2,
*
* <p>arr2 中的元素各不相同 arr2 中的每个元素都出现在 arr1 中 对 arr1 中的元素进行排序,使 arr1
* 中项的相对顺序和 arr2 中的相对顺序相同。未在 arr2 中出现过的元素需要按照升序放在 arr1 的末尾。
*
* <p>
*
* <p>示例:
*
* <p>输入:arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] 输出:[2,2,2,1,4,3,3,9,6,7,19]
*
* <p>来源:力扣(LeetCode)
*
* 总结本方法的核心就是 int类型的数组转为 List<Integer> 利用list 进行遍历, 同时利用列表可以删除元素
* 然后将剩下的元素,进行排序,排序之后直接添加到队尾</>
*
*/
public class ArrayRelativeSorted {
/**
* 思路是 遍历arrr中的数组,然后从一中找相关的元素,进行排序,找到一个就剔除相关的元素,然后把剩下的进行排序直接添加到队列尾部
* @param arr1
* @param arr2
* @return
*/
public int[] relativeSortArray(int[] arr1, int[] arr2) {
int[] tem = new int[arr1.length];
List<Integer> tempArr1 = Arrays.stream(arr1).boxed().collect(Collectors.toList());
int index =0;
for(int ele:arr2){
for (int i = tempArr1.size() - 1; i >= 0; i--) {
Integer e = tempArr1.get(i);
if(ele == e){
tem[index++]=ele;
tempArr1.remove(e);
}
}
}
if(!tempArr1.isEmpty()){
Collections.sort(tempArr1);
for(int i=0;i<tempArr1.size();i++){
tem[index++]=(Integer) tempArr1.get(i);;
}
}
return tem;
}
public static void main(String[] args) {
int[] arr1 =new int[]{2,3,1,3,2,4,6,7,9,2,19};
int[] arr2 =new int[]{2,1,4,3,9,6};
int[] res = new ArrayRelativeSorted().relativeSortArray(arr1,arr2);
System.out.println(res);
}
}
|
package com.estrelladelsur.connectionmanager;
public class ConnectionManager {
}
|
package jie.android.ip.screen.play;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import aurelienribon.tweenengine.Timeline;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.TweenManager;
import jie.android.ip.CommonConsts.PackConfig;
import jie.android.ip.common.actor.ImageActor;
import jie.android.ip.common.actor.ImageActorAccessor;
import jie.android.ip.common.actor.ScreenGroup;
import jie.android.ip.screen.BaseScreen;
import jie.android.ip.screen.play.PlayConfig.Const;
import jie.android.ip.screen.play.PlayConfig.Image;
public class ToggleGroup extends ScreenGroup {
private final TextureAtlas textureAtlas;
private final TweenManager tweenManager;
// private final PlayScreenListener.RendererInternalEventListener internalListener;
private ImageActor right, left;
private ImageActor bg;
public ToggleGroup(final BaseScreen screen) {
super(screen);
this.textureAtlas = super.resources.getTextureAtlas(PackConfig.SCREEN_PLAY);
this.tweenManager = super.screen.getTweenManager();
// this.internalListener = internalListener;
initStage();
}
@Override
protected void initStage() {
this.setBounds(Const.Toggle.BASE_X, Const.Toggle.BASE_Y, Const.Toggle.WIDTH, Const.Toggle.HEIGHT);
bg = new ImageActor(textureAtlas.findRegion(Image.Toggle.BG));
bg.setBounds(Const.Toggle.BASE_X, Const.Toggle.BASE_Y, Const.Toggle.WIDTH, Const.Toggle.HEIGHT);
// bg.setColor(0, 0, 0, 1);
this.addActor(bg);
right = new ImageActor(textureAtlas.findRegion(Image.Toggle.RIGHT));
right.setBounds(Const.Toggle.BASE_X_RIGHT, Const.Toggle.BASE_Y_RIGHT, Const.Toggle.WIDTH_RIGHT, Const.Toggle.HEIGHT_RIGHT);
// right.setPosition(Const.Toggle.BASE_X_RIGHT, Const.Toggle.BASE_Y_RIGHT);
this.addActor(right);
left = new ImageActor(textureAtlas.findRegion(Image.Toggle.LEFT));
left.setBounds(Const.Toggle.BASE_X_LEFT, Const.Toggle.BASE_Y_LEFT, Const.Toggle.WIDTH_LEFT, Const.Toggle.HEIGHT_LEFT);
this.addActor(left);
screen.addActor(this);
// this.setZIndex(0x64);
}
public void enter(final TweenCallback tweenCallback) {
Timeline.createParallel()
.push(Tween.set(bg, ImageActorAccessor.OPACITY).target(1))
.push(Tween.set(bg, ImageActorAccessor.TINT).target(0, 0, 0))
.push(Tween.to(bg, ImageActorAccessor.OPACITY, 0.5f).target(0))
.push(Tween.to(bg, ImageActorAccessor.TINT, 0.5f).target(1, 1, 1))
.push(Tween.to(right, ImageActorAccessor.POSITION_X, 0.5f).targetRelative(Const.Toggle.WIDTH_RIGHT))
.push(Tween.to(left, ImageActorAccessor.POSITION_X, 0.5f).targetRelative(-Const.Toggle.WIDTH_LEFT))
.setCallback(tweenCallback)
.start(tweenManager);
}
public void out(final TweenCallback tweenCallback) {
Timeline.createParallel()
.push(Tween.set(bg, ImageActorAccessor.OPACITY).target(0))
.push(Tween.set(right, ImageActorAccessor.POSITION_X).target(Const.Toggle.WIDTH))
.push(Tween.set(left, ImageActorAccessor.POSITION_X).target(-Const.Toggle.WIDTH_LEFT))
.push(Tween.to(bg, ImageActorAccessor.OPACITY, 0.5f).target(1))
.push(Tween.to(bg, ImageActorAccessor.TINT, 0.5f).target(0, 0, 0))
.push(Tween.to(right, ImageActorAccessor.POSITION_X, 0.5f).targetRelative(-Const.Toggle.WIDTH_RIGHT))
.push(Tween.to(left, ImageActorAccessor.POSITION_X, 0.5f).targetRelative(Const.Toggle.WIDTH_LEFT))
.setCallback(tweenCallback)
.start(tweenManager);
}
}
|
package com.vikastadge.hibernate.annotations;
import com.vikastadge.hibernate.annotations.dao.entity.PersonEntity;
import com.vikastadge.hibernate.annotations.service.PersonService;
public class HibernatePrimaryKeyGenerationStrategy {
public static void main( String[] args ) {
PersonEntity personEntity = new PersonEntity();
personEntity.setName("Bob");
PersonService personService = new PersonService();
personService.save(personEntity);
}
}
|
package ap.cayenne.learning.functions;
import ap.cayenne.learning.listeners.MyLifecycleListener;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.Persistent;
import org.apache.cayenne.configuration.server.ServerRuntime;
import org.apache.cayenne.query.SelectById;
import org.example.cayenne.persistent.Contact;
import org.example.cayenne.persistent.Invoice;
import org.example.cayenne.persistent.Payment;
import org.junit.*;
import java.util.ArrayList;
import java.util.List;
public class PaymentFunctionsTest {
private ServerRuntime runtime;
private ObjectContext context;
private List<Persistent> objects;
private Invoice invoice;
Contact contact;
@Before
public void before(){
runtime = ServerRuntime.builder().addConfig("cayenne-CayenneModelerTest.xml").build();
context = runtime.newContext();
objects = new ArrayList<>();
contact = ContactFunctions.createContact("testName", "testLastName", "test@gmail.com", context);
objects.add(contact);
invoice = InvoiceFunctions.createInvoice(context, 600, "1st invoice");
invoice.setContact(contact);
objects.add(invoice);
}
@After
public void after(){
context.deleteObjects(objects);
context.commitChanges();
}
@Test
public void testCreatePayment(){
Payment payment = context.newObject(Payment.class);
payment.setInvoice(invoice);
objects.add(payment);
context.commitChanges();
ObjectContext newContext = runtime.newContext();
Payment expected = SelectById.query(Payment.class, payment.getObjectId()).selectOne(newContext);
if (expected == null){
Assert.fail();
} else {
Assert.assertEquals(expected.getObjectId(), payment.getObjectId());
}
}
@Ignore
@Test()
public void TestValidateOnSaveListenerWork (){
runtime.getChannel().getEntityResolver().getCallbackRegistry().addListener(Payment.class, new MyLifecycleListener());
addPaymentsToInvoice(invoice, 250, 2);
Invoice inv = InvoiceFunctions.createInvoice(context, 500, "2d invoice");
inv.setContact(contact);
objects.add(inv);
addPaymentsToInvoice(inv, 40, 4);
context.commitChanges();
}
/*
* creating 2 payments and setting them to an invoice
*
* int paymentAmount - amount that will be set to every created payment
* Invoice invoice - created payments will be set to that invoice
* ObjectContext context - its the context to put payments
*/
private void addPaymentsToInvoice (Invoice invoice, int paymentAmount, int quantity){
for (int i = 0; i < quantity; i++) {
Payment payment = context.newObject(Payment.class);
payment.setAmount(paymentAmount);
payment.setInvoice(invoice);
objects.add(payment);
}
}
}
|
package mop.test.java.database.model;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mop.main.java.database.model.queryable.Episode;
public class EpisodeTest {
@Test
public void testEpisodeId() {
Episode sut = new Episode();
sut.setEpisodeId(7);
assertEquals(7, sut.getEpisodeId());
}
@Test
public void testEpisodeNumber() {
Episode sut = new Episode();
sut.setEpisodeNumber(9);
assertEquals(9, sut.getEpisodeNumber());
}
@Test
public void testName() {
Episode sut = new Episode();
sut.setName("mop.test episode");
assertEquals("mop.test episode", sut.getName());
}
@Test
public void testFileLocation() {
Episode sut = new Episode();
sut.setFileLocation("C://mop.test");
assertEquals("C://mop.test", sut.getFileLocation());
}
}
|
package fr.lteconsulting.servlet.action;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import fr.lteconsulting.DonneesScope;
import fr.lteconsulting.Joueur;
import fr.lteconsulting.dao.JoueurDao;
@WebServlet( "/login" )
public class LoginServlet extends ActionServlet
{
private static final long serialVersionUID = 1L;
@EJB
private JoueurDao joueurDao;
@Override
protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
// extraire les parametres de la requete
String login = request.getParameter( "login" );
String password = request.getParameter( "password" );
// on va vérifier si le joueur s'est bien authentifié
// on parcours la liste des joueurs en cherchant un joueur qui correspond
// aux informations données dans la requête par l'utilisateur
Joueur joueur = joueurDao.findJoueurByLoginPassword( login, password );
if( joueur != null )
DonneesScope.setJoueurSession( joueur, request );
redirigerReferer( request, response );
}
}
|
package leecode.dfs;
import java.util.LinkedList;
import java.util.Queue;
//对比lee695
public class 岛屿数量_200 {
int[][]dirs=new int[][]{{1,0},{0,1},{0,-1},{-1,0}};//并查集只需要走右,走下 方向 即{1,0},{0,1}
public int numsIslands(char[][]grid){
boolean[][]visit=new boolean[grid.length][grid[0].length];
int ans=0;
for (int i = 0; i <grid.length ; i++) {
for (int j = 0; j <grid[0].length ; j++) {
/*
!visit[i][j]要加上这个
从一个点联通的 1 就不需要再记录为岛屿了,不需要再调用dfs了
dfs函数中都进行了标记 visit
如果不加 !visit[i][j] 则所有的1都被dfs,即使相互联通的
*/
if(grid[i][j]=='1'&&!visit[i][j]){//要加个 &&!visit[i][j]
numswithdfs(grid,i,j,visit);
ans++;
}
}
}
return ans;
}
/*
liweiwei dfs图解
注意 选择起点的条件,即调用dfs的点满足的条件
还有 dfs函数中进行对下一个点dfs的条件
每次从一个点向四个方向dfs,并且按照一定的顺序
开始dfs时 记录四个方向的状态
每个方向状态有一下情况:
1、越界
2、未访问 且为1
3、未访问 且为0
4、已经访问过
每个方向处理:
1、接下来要走
2、等待回溯(等待要走的格子走完后,再对自己进行处理)
四个方向全部走完,则退回到上一个格子,找上一个格子的下一个方向
当从一个方向dfs完毕,返回到开始dfs的点时,可以选择恢复状态,因为即使恢复为未访问状态,也是按照固定的顺序进行dfs的,
所以不会再对该点进行dfs,但是如果从另外一点开始进行dfs时(调用dfs函数时设置的起点),可能又对该点进行dfs
每次调用dfs函数完毕,就是对 传入dfs起点这个点相通的所有点都处理完毕
*/
public void numswithdfs(char[][]grid,int i,int j,boolean[][]visit){
visit[i][j]=true;
for(int[]dir:dirs){
int x=i+dir[0];
int y=j+dir[1];
//判断该点的状态能否进行dfs:未越界,未dfs,且为1
if(!bound(x,y,grid)&&!visit[x][y]&&grid[i][j]=='1'){
numswithdfs(grid,x,y,visit);
}
}
return;
}
/*
“广度优先遍历”不用回溯,但是需要一个 “辅助队列”
所有加入队列的结点,都应该马上被标记为 “已经访问”,否则有可能会被重复加入队列。
*/
public int numswithbfs(char[][]grid) {
boolean[][]visit=new boolean[grid.length][grid[0].length];
int ans=0;
int col=grid[0].length;
int row=grid.length;
for (int i = 0; i <grid.length ; i++) {
for (int j = 0; j < grid[0].length; j++) {
/*
如果一个点没有访问过,且是1,则进行bfs
*/
if(!visit[i][j]&&grid[i][j]=='1'){
ans++;
LinkedList<Integer>queue=new LinkedList<>();
/*
将 横 纵坐标转化为一个数字,否则需要存一个数组
*/
queue.addLast(i*col+j);
visit[i][j]=true;//标记为已经访问
while (!queue.isEmpty()){
int cur=queue.pollFirst();
int newX=cur/col;
int newY=cur&col;
if(bound(newX,newY,grid)&&grid[newX][newY]=='1'&&!visit[newX][newY]){
queue.addFirst(newX*col+newY);
visit[newX][newY]=true;
}
}
}
}
}
return ans;
}
public boolean bound(int x, int y, char[][] grid) {
return x >= 0 && x < grid.length && y >= 0 && y < grid[0].length;
}
//考虑使用并查集合解决
public int numsIslands2(char[][]grid) {
int m=grid.length;
int n=grid[0].length;
int dummy=m*n;
union union=new union(m*n+1);
for (int i = 0; i <grid.length ; i++) {
for (int j = 0; j <grid[0].length ; j++) {
if(grid[i][j]=='1'){
for(int[]dir:dirs){
int x=i+dir[0];
int y=j+dir[1];
if(bound(x,y,grid)&&grid[x][y]=='1'){
union.merge(i*n+j,x*n+y);
}
}
}else {
union.merge(i*n+j,dummy);
}
}
}
return union.getCount()-1;
}
class union{
public int[]parent;
public int[]size;
public int count;
public union(int n){
this.count=n;
parent=new int[n];
size=new int[n];
for (int i = 0; i <n ; i++) {//不要忘记这里初始化
parent[i]=i;
size[i]=1;
}
}
public void merge(int node1,int node2){
int father1=findFather(node1);
int father2=findFather(node2);
if(father1==father2){
return;
}
if(size[father1]>size[father2]){
parent[father2]=father1;
size[father1]+=size[father2];
}else {
parent[father1]=father2;
size[father2]+=size[father1];
}
count--;
}
public boolean connected(int node1,int node2){
return findFather(node1)==findFather(node2);
}
private int findFather(int node){
while (parent[node]!=node){
parent[node]=parent[parent[node]];
node=parent[node];
}
return node;
}
public int getCount(){
return count;
}
}
}
|
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_models.Facility;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_service.FacilityService;
@RestController
@RequestMapping("/app/facility")
@CrossOrigin
public class FacilityController {
@Autowired
private FacilityService facilityService;
@GetMapping("/all")
public List<Facility> getAllFacilityInformation() {
return facilityService.findAllFacilityInformation();
}
}
|
package com.example.eclaros.miaplicacion1;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity {
private TextView titulo;
private Button abmcategorias;
private Button abmproductos;
private Button abmclientes;
private Button listarproductos;
private Button listarclientes;
private Button listarpedidos;
private Button atras;
private String mensaje_recibido;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context=this;
//Recibimos el mensaje del anterior activitu.
Intent datos=getIntent();
mensaje_recibido=datos.getStringExtra("mensaje");
//Declaramos los componentes
titulo=(TextView)findViewById(R.id.titulo_menu);
abmcategorias=(Button)findViewById(R.id.abmcategorias);
abmproductos=(Button)findViewById(R.id.abmproductos);
abmclientes=(Button)findViewById(R.id.abmclientes);
listarproductos=(Button)findViewById(R.id.listarproductos);
listarclientes=(Button)findViewById(R.id.listarclientes);
listarpedidos=(Button)findViewById(R.id.listarpedidos);
atras=(Button)findViewById(R.id.salir);
abmcategorias.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent a = new Intent(context, MainBdActivity.class);
startActivity(a);
}
});
abmproductos.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent a = new Intent(context, ProductoActivity.class);
startActivity(a);
}
});
atras.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
/*
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
*/
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* ErpDrawingidId generated by hbm2java
*/
public class ErpDrawingidId implements java.io.Serializable {
private String mc;
private String bh;
private String version;
public ErpDrawingidId() {
}
public ErpDrawingidId(String mc, String bh, String version) {
this.mc = mc;
this.bh = bh;
this.version = version;
}
public String getMc() {
return this.mc;
}
public void setMc(String mc) {
this.mc = mc;
}
public String getBh() {
return this.bh;
}
public void setBh(String bh) {
this.bh = bh;
}
public String getVersion() {
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof ErpDrawingidId))
return false;
ErpDrawingidId castOther = (ErpDrawingidId) other;
return ((this.getMc() == castOther.getMc())
|| (this.getMc() != null && castOther.getMc() != null && this.getMc().equals(castOther.getMc())))
&& ((this.getBh() == castOther.getBh()) || (this.getBh() != null && castOther.getBh() != null
&& this.getBh().equals(castOther.getBh())))
&& ((this.getVersion() == castOther.getVersion()) || (this.getVersion() != null
&& castOther.getVersion() != null && this.getVersion().equals(castOther.getVersion())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getMc() == null ? 0 : this.getMc().hashCode());
result = 37 * result + (getBh() == null ? 0 : this.getBh().hashCode());
result = 37 * result + (getVersion() == null ? 0 : this.getVersion().hashCode());
return result;
}
}
|
package chapter_1_14_Threads;
import java.util.concurrent.atomic.AtomicLong;
public class Atomic {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
AtomicLong al1 = new AtomicLong(0);
AtomicRun ar = new AtomicRun();
ar.a = al1;
for (int i=0; i<500; i++)
new Thread(ar).start();
Thread.sleep(500);
System.out.println();
System.out.println("AtomicLong: " + ar.a);
Long l1 = 0l;
LongRun lr = new LongRun();
lr.a = l1;
for (int i=0; i<500; i++)
new Thread(lr).start();
Thread.sleep(500);
System.out.println();
System.out.println("Long: " + lr.a);
}
}
class LongRun implements Runnable {
Long a;
public void run() {
if (Thread.currentThread().getId() % 2 == 0)
System.out.print(" " + a++);
else
System.out.print(" " + a--);
}
}
class AtomicRun implements Runnable {
AtomicLong a;
public void run() {
if (Thread.currentThread().getId() % 2 == 0)
System.out.print(" " + a.incrementAndGet());
else
System.out.print(" " + a.decrementAndGet());
}
}
|
package data;
import business.BusinessADBean;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Created by wierz on 2016/4/21.
*/
public class BusinessAdDAO {
/** 从数据库中获取业务信息 */
public static ArrayList<BusinessADBean> selectBusinessADBeans() {
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT business.No, employee.Name, employee.Department, employee.Rank, business.Type, business.Date_1, business.Date_2, business.Date_3 "
+ "FROM business "
+ "INNER JOIN employee "
+ "ON business.EmployeeID = employee.EmployeeID";
try {
ps = connection.prepareStatement(query);
rs = ps.executeQuery();
ArrayList<BusinessADBean> list = new ArrayList<>();
while (rs.next()) {
BusinessADBean businessADBean = new BusinessADBean();
businessADBean.setNo(rs.getInt("No"));
businessADBean.setName(rs.getString("Name"));
businessADBean.setDepartment(rs.getString("Department"));
businessADBean.setRank(rs.getString("Rank"));
businessADBean.setType(rs.getString("Type"));
businessADBean.setDate1(rs.getDate("Date_1"));
businessADBean.setDate2(rs.getDate("Date_2"));
businessADBean.setDate3(rs.getDate("Date_3"));
list.add(businessADBean);
}
return list;
} catch (SQLException e) {
System.out.println(e);
return null;
} finally {
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
}
|
package com.kareo.ui.codingcapture.implementation.request;
import com.kareo.ui.codingcapture.implementation.data.CustomerTask;
import com.kareo.ui.codingcapture.implementation.data.Encounter;
/**
* Created by deepalik on 06/10/15.
*/
public class TaskCreationRequest {
Encounter encounter;
CustomerTask customerTask;
Long patientId;
Long encounterId;
Long providerId;
public Long getProviderId() {
return providerId;
}
public void setProviderId(Long providerId) {
this.providerId = providerId;
}
int pageNum;
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public Long getPatientId() {
return patientId;
}
public void setPatientId(Long patientId) {
this.patientId = patientId;
}
public Long getEncounterId() {
return encounterId;
}
public void setEncounterId(Long encounterId) {
this.encounterId = encounterId;
}
public Encounter getEncounter() {
return encounter;
}
public void setEncounter(Encounter encounter) {
this.encounter = encounter;
}
public CustomerTask getCustomerTask() {
return customerTask;
}
public void setCustomerTask(CustomerTask customerTask) {
this.customerTask = customerTask;
}
}
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package edu.se.ustc;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import edu.se.ustc.item.BusRouteInfo;
import edu.se.ustc.util.dbUtil;
import java.sql.*;
/**
* This example demonstrates the use of the {@link ResponseHandler} to simplify
* the process of processing the HTTP response and releasing associated
* resources.
*/
public class ClientWithResponseHandler implements Runnable {
/**
* the main handler function of Crawls
* @throws Exception
*/
private String fileName; //进程生成的文件名
private String URL; //进程URL
private static boolean startFlag; //所有进程启动标志
public ClientWithResponseHandler(String fileName, String URL){
this.fileName=fileName;
this.URL=URL;
}
public List<BusRouteInfo> run(String URL) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
List<BusRouteInfo> bsrList = new ArrayList<BusRouteInfo>();
try {
HttpGet httpget = new HttpGet(URL);
//debug
//System.out.println("Executing request " + httpget.getRequestLine());
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
public String handleResponse(final HttpResponse response)
throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity)
: null;
} else {
throw new ClientProtocolException(
"Unexpected response status: " + status);
}
}
};
String responseBody = httpclient.execute(httpget, responseHandler);
//System.out.println("----------------------------------------");
//System.out.println(responseBody);
String str = responseBody.substring(responseBody.indexOf("table"),
responseBody.lastIndexOf("table"));
//debug
//System.out.println(str);
BusRouteInfo binfo=new BusRouteInfo();
bsrList = binfo.getBusRouteInfoList(str);
//debug, print all infomation
//binfo.printBusRouteInfo(bsrList);
//select the db
//dbUtil db = new dbUtil();
//result=db.executeQuery("SELECT * FROM station_stats");
// if(result!=null)
// System.out.println(result.getString(1));
} finally {
httpclient.close();
}
return bsrList;
}
// public static void main(String[] agrs){
//
// //ClientWithResponseHandler cwrh = new ClientWithResponseHandler();
// //
// //String address = "http://www.szjt.gov.cn/BusQuery/APTSLine.aspx?cid=175ecd8d-c39d-4116-83ff-109b946d7cb4&LineGuid=9acf55b9-8406-40ef-8056-6de249174ee0&LineInfo=19(%E6%96%B0%E7%81%AB%E8%BD%A6%E7%AB%99%E5%8C%97%E4%B8%B4%E6%97%B6%E5%B9%BF%E5%9C%BA)";
// //快线2号
// String address ="http://www.szjt.gov.cn/BusQuery/APTSLine.aspx?cid=175ecd8d-c39d-4116-83ff-109b946d7cb4&LineGuid=e0e5561a-32ea-432d-ac98-38eed8c4e448&LineInfo=%E5%BF%AB%E7%BA%BF2%E5%8F%B7(%E7%8B%AC%E5%A2%85%E6%B9%96%E9%AB%98%E6%95%99%E5%8C%BA%E9%A6%96%E6%9C%AB%E7%AB%99=%3E%E7%81%AB%E8%BD%A6%E7%AB%99)";
// try {
// cwrh.run(address);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// }
//设置进程开始标志
public static void setStartFlag(boolean flag){
startFlag=flag;
}
//获得进程开始标志
public static boolean getStartFlag(){
return startFlag;
}
@Override
public void run() {
// TODO Auto-generated method stub
if(getStartFlag()){
System.out.println(fileName + " thread is start.");
}
else{
System.out.println(fileName + " thread is closed.");
}
ClientWithResponseHandler cwrh = new ClientWithResponseHandler(fileName, URL);
//旧的list用于保存更新之前的信息, 方便对比
List<BusRouteInfo> oldList =new ArrayList<BusRouteInfo>();
List<BusRouteInfo> bsiList =new ArrayList<BusRouteInfo>();
try {
oldList = cwrh.run(URL);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(getStartFlag()){
try {
bsiList=cwrh.run(URL);
Thread.currentThread().sleep(5000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BusRouteInfo bri=new BusRouteInfo();
if(oldList!=null&&bsiList!=null)
{
try {
if(bri.saveToTxt(fileName,oldList, bsiList)){
oldList = bsiList;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.