text
stringlengths
10
2.72M
package com.hrc.administrator.startup; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import android.util.Log; import android.widget.Toast; /** * Created by Administrator on 2016/12/26. */ public class StartupReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { //判断接受到的广播是否为收到短信的Broadcast Action if("android.provider.Telephony.SMS_RECEIVED".equals(intent.getAction())){ Log.d("onReceive","进入if语句"); StringBuilder sb=new StringBuilder(); //接受由SmS传过来的数据 Bundle bundle=intent.getExtras(); if(bundle!=null){ Log.d("onReceive","bundle数据不为空"); //通过pdus可以获得接受到的所有短信息 Object[] objArray=(Object[])bundle.get("pdus"); //构建短信对象array,并依据收到的对象长度来创建array的大小 SmsMessage[] messages=new SmsMessage[objArray.length]; for(int i=0;i<objArray.length;i++){ messages[i]=SmsMessage.createFromPdu((byte[])objArray[i]); } Log.d("onReceive","第一个for循环执行完毕"); //将送来的短信合并自定信息于StringBuilder中 for (SmsMessage current:messages){ sb.append("短信来源:"); //获得接受短信的电话号码 sb.append(current.getDisplayOriginatingAddress()); sb.append("/n------短信内容-------/n"); //获得短信的内容 Intent mainIntent=new Intent(context,MainActivity.class); mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(mainIntent); Toast.makeText(context,sb.toString(),Toast.LENGTH_SHORT).show(); } } } } }
package doc.online.util; import doc.online.dao.ClientDAO; import java.util.Random; public final class Generator { public static String generateNewClientId() { return generateRamdomNumericString(Configuration.getClientIdStringLength()); } public static String generateNewClientSecret() { return "12345678"; } public static String generateRamdomNumericString(int len) { ClientDAO clientDAO = new ClientDAO(); StringBuffer sb = new StringBuffer(); Random r = new Random(); do { sb = new StringBuffer(); for (int i = 0; i < len; i++) { sb.append(r.nextInt(10)); } } while (clientDAO.isClientIdExist(sb.toString())); return sb.toString(); } }
package classes.model; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; @Entity @Table(name = "tb_user") @SequenceGenerator(name = "sequence", sequenceName = "tb_user_id_seq") public class User implements Serializable { private Integer id; private String role; private String name; private String email; private String password; private String sex; private String document; private String phone; private String registration; private Address address; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } 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 getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getDocument() { return document; } public void setDocument(String document) { this.document = document; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getRegistration() { return registration; } public void setRegistration(String registration) { this.registration = registration; } @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="address_id") //@Transient public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @Transient public boolean isAdmin() { return this.role.equals("admin"); } @Transient public String getReadableRole(){ if(isAdmin()){ return "Funcionário"; } return "Cliente"; } @Override public String toString() { return "\n" + "id: " + getId() + "\n" + "role: " + getRole() + "\n" + "name: " + getName() + "\n" + "email: " + getEmail() + "\n" + "password: " + getPassword() + "\n" + "sex: " + getSex() + "\n" + "document: " + getDocument() + "\n" + "phone: " + getPhone() + "\n" + "registration: " + getRegistration() + "\n"; } }
package sr.hakrinbank.intranet.api.service.bean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PostFilter; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import sr.hakrinbank.intranet.api.model.Currency; import sr.hakrinbank.intranet.api.repository.CurrencyRepository; import sr.hakrinbank.intranet.api.service.CurrencyService; import java.util.List; /** * Created by clint on 5/24/17. */ @Service @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class CurrencyServiceBean implements CurrencyService { @Autowired private CurrencyRepository currencyRepository; @Override @PostFilter("filterObject.deleted() == false") public List<Currency> findAllCurrencies() { return currencyRepository.findAll(); } @Override public Currency findById(long id) { return currencyRepository.findOne(id); } @Override public void updateCurrency(Currency currency) { currencyRepository.save(currency); } @Override public List<Currency> findAllActiveCurrencies() { return currencyRepository.findActiveCurrencies(); } @Override public List<Currency> findAllActiveCurrenciesBySearchQuery(String qry) { return currencyRepository.findAllActiveCurrenciesBySearchQuery(qry); } }
package com.alibaba.druid.sql.repository.function; public class Signatures { }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package negocio; import datos.ClienteTelefonoBD; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author MASS */ public class ClienteTelefonoLista { private ArrayList clienteTelefonos=new ArrayList(); public ArrayList getClienteTelefonos() { return clienteTelefonos; } public void setClienteTelefonos(ArrayList clienteTelefonos) { this.clienteTelefonos = clienteTelefonos; } public void listar(){ try { ClienteTelefonoBD clienteTelefonoBD = new ClienteTelefonoBD(); setClienteTelefonos(clienteTelefonoBD.listar()); } catch (SQLException ex) { Logger.getLogger(ClienteTelefonoLista.class.getName()).log(Level.SEVERE, null, ex); } } }
/** * SprDAOHibernate.java * * Last Update $Id: SprDAOHibernate.java,v 1.1.1.1 2008-07-01 17:47:54 rba Exp $ * * History: * $Log: SprDAOHibernate.java,v $ * Revision 1.1.1.1 2008-07-01 17:47:54 rba * Initial import of IDETestHarness * */ package org.imo.lrit.ide.test.dao; /** * */ import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Restrictions; import org.imo.lrit.ide.test.model.Spr; public class SprDAOHibernate extends GenericHibernateDAO<Spr, Long> implements SprDAO{ }
package pl.herbata.project.mvc.editplayerdialog; import pl.herbata.project.database.MainDatabase; import pl.herbata.project.Player; import pl.herbata.project.mvc.Model; public class EditPlayerDialogModel implements Model { private MainDatabase database; private int updatedPlayersId; public EditPlayerDialogModel() { database = MainDatabase.getInstance(); updatedPlayersId = 0; } public void setUpdatedPlayersId(int id) { updatedPlayersId = id; } public void updatePlayer(String nickname) { database.updatePlayer(updatedPlayersId, nickname); } public Player getSelectedPlayer() { return database.selectPlayerOnId(updatedPlayersId); } }
package Java; public class SwapingNumber1 { public static void main(String[] args) { System.out.println("SWAPING NUMBER Without USING THIRD VARIABLE"); int a=10; int b= 20; System.out.println("Before swaping a= " +a); System.out.println("Before swaping b= " +b); a= a+b; System.out.println("After a+b value of a= "+a); b= a-b; a=a-b; System.out.println("After swaping a= " +a); System.out.println("After swaping b= " +b); } }
package com.gsccs.sme.plat.shop.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.gsccs.sme.plat.corp.service.CorpService; /** * */ @Controller @RequestMapping("/buyer") public class BuyerController { @Autowired private CorpService buyerService; }
package com.admin.databinding; import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; /** * 目录页 * * @author Administrator */ public class ListActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ativity_list); } public void easyUsing(View view) { //简单使用 startActivity(new Intent(this,MainActivity.class)); } public void singleBind(View view) { //单向数据绑定 startActivity(new Intent(this,SingleBindActivity.class)); } public void twoWayBinding(View view) { //双向数据绑定 startActivity(new Intent(this,TwoWayBindingActivity.class)); } public void highBinding(View view) { //高级绑定 startActivity(new Intent(this,HighLevelBinding.class)); } }
package com.springlearnig.moviecatalogservice.resources; import com.springlearnig.moviecatalogservice.models.CatalogItem; import com.springlearnig.moviecatalogservice.models.Movie; import com.springlearnig.moviecatalogservice.models.UserRating; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; //import org.springframework.web.reactive.function.client.WebClient; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping("/catalog") public class MovieCatalogResource { @Autowired private RestTemplate restTemplate; // @Autowired // private DiscoveryClient discoveryClient; // @Autowired // WebClient.Builder webClientBuilder; //get all rated movie IDs //For each movie ID,call movie info service and get details //put them all together @RequestMapping("/{userId}") public List<CatalogItem> getCatalog(@PathVariable("userId") String userId){ UserRating ratings = restTemplate.getForObject("http://ratings-data-service/ratingsdata/users/"+userId,UserRating.class); return ratings.getRatings().stream().map(rating ->{ System.out.println("enter here"); Movie movie = restTemplate.getForObject("http://movie-info-service/movies/"+rating.getMovieId(), Movie.class); //making call to API and unmarshalling into the Obj System.out.println("get back main place after call"); return new CatalogItem(movie.getName(), movie.getDescription(), rating.getRating()); } ) .collect(Collectors.toList()); // return Collections.singletonList(new CatalogItem("Transformers","Test",4)); } } /* Movie movie = webClientBuilder.build() .get() .uri("http://localhost:8082/movies/"+rating.getMovieId()) .retrieve() .bodyToMono(Movie.class) .block(); */
package com.quixmart.sdk.domain.order; public class QXOrderItem { private Integer num; private String cargowayId; public QXOrderItem() { } public QXOrderItem(Integer num, String cargowayId) { this.num = num; this.cargowayId = cargowayId; } public Integer getNum() { return num; } public void setNum(Integer num) { this.num = num; } public String getCargowayId() { return cargowayId; } public void setCargowayId(String cargowayId) { this.cargowayId = cargowayId; } @Override public String toString() { return "QXOrderItem{" + "num=" + num + ", cargowayId='" + cargowayId + '\'' + '}'; } }
import OSI.Physical.Cable; import OSI.Physical.Component; import OSI.Physical.NIC; import Standards.Ethernet; import Standards.MAC; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args){ List<Component> componentList = new ArrayList<>(); MAC m = new MAC(""); NIC t = new NIC(m, 2, 100, false, componentList); componentList.add(t); Cable c = new Cable(Ethernet.IEE802_3AE, "Black", 5, false, componentList); System.out.println(c); System.out.println(t); } }
package com.jit.consumer04; class Movie { String name; String result; Movie(String name, String result) { this.name = name; this.result = result; } }
package co.edu.meli.domain.usecase; import co.edu.meli.domain.model.Point; import co.edu.meli.domain.model.SpaceshipReference; import co.edu.meli.domain.provider.SatelliteProvider; import data.SatellitesDataProvider; import groovy.util.logging.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.when; @Slf4j public class CalculatePositionUseCaseTest { @Mock SatelliteProvider satellites; @InjectMocks CalculatePositionUseCase calculatePositionUseCase; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); } @Test void testProcess() { final SpaceshipReference spaceship = SpaceshipReference.builder() .toKenobi(485.696d) .toSkywalker(266.083d) .toSato(600.5d) .build(); when(satellites.getKenobi()).thenReturn(SatellitesDataProvider.kenobi()); when(satellites.getSkywalker()).thenReturn(SatellitesDataProvider.skywalker()); when(satellites.getSato()).thenReturn(SatellitesDataProvider.sato()); Point result = calculatePositionUseCase.process(spaceship); Assertions.assertEquals(-100d, result.getEast(), "X position not compliant."); Assertions.assertEquals(75.5d, result.getNorth(), "Y position not compliant."); } }
package gameController; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.ListIterator; import java.util.Scanner; import javax.imageio.ImageIO; public class Tabuleiro implements java.io.Serializable{ /** * */ private static final long serialVersionUID = 3477989291388052589L; public transient BufferedImage imgTabuleiro; public transient BufferedImage imgCorda; public transient BufferedImage imgCano; public transient BufferedImage imgFaca; public transient BufferedImage imgChave; public transient BufferedImage imgCastical; public transient BufferedImage imgRevolver; private double img_escalaHorizontal = 1.0; private double img_escalaVertical = 1.0; public int[][] matriz; private int matriz_numColunas; private int matriz_numLinhas; private int matriz_deslocamentoColunas; private int matriz_deslocamentoLinhas; private int matriz_larguraColuna; private int matriz_alturaLinha; //Container dos itens que estão dentro de um comodo - tam = maxJogadores + maxArmas public int[][] comodos = new int[ObservedGame.numRooms][ObservedGame.numPlayers + ObservedGame.numWeapons]; public static final Color corGreen = new Color(36,83,41, 255); public static final Color corMustard = new Color(204,176,32, 255); public static final Color corPeacock = new Color(45,62,118, 255); public static final Color corPlum = new Color(101,68,85, 255); public static final Color corScarlet = new Color(203,82,74, 255); public static final Color corWhite = new Color(183,186,193, 255); public static final Color corAlcance = new Color(153, 255, 153, 128); /* Estados da matriz * Valores associados a cada posi��o da matriz. */ public static final int VAZIO = -1; public static final int ALCANCE = -2; public static final int INVALIDO = -3; public Tabuleiro(){ Scanner infomatriz=null; readImages(); try{ infomatriz = new Scanner(new FileReader("assets/Tabuleiro-Dobrado")); } catch (IOException e){ System.out.println("Incapaz de abrir arquivo. Erro:" + e.getMessage()); System.exit(1); } matriz_alturaLinha = infomatriz.nextInt(); matriz_larguraColuna = infomatriz.nextInt(); matriz_deslocamentoLinhas = infomatriz.nextInt(); matriz_deslocamentoColunas = infomatriz.nextInt(); matriz_numLinhas = imgTabuleiro.getHeight()/matriz_alturaLinha; matriz_numColunas = imgTabuleiro.getWidth()/matriz_larguraColuna; matriz = new int[matriz_numLinhas*matriz_numColunas][2]; for(int j=0; j<ObservedGame.numRooms; j++) for(int i=0; i<(ObservedGame.numPlayers + ObservedGame.numWeapons); i++) comodos[j][i] = -1; for(int i=0; i<getTamanhoTabuleiro(); i++){ if(infomatriz.hasNext()) { matriz[i][0] = infomatriz.nextInt(); matriz[i][1] = Tabuleiro.VAZIO; }else{ System.out.println("Ärquivo da matriz menor que o esperado"); System.exit(1); } } infomatriz.close(); } void readImages() { System.out.println("reading images"); try{ imgTabuleiro = ImageIO.read(new File("assets/Tabuleiro-Dobrado.JPG")); imgCorda = ImageIO.read(new File("assets/Armas/Corda.jpg")); imgCano = ImageIO.read(new File("assets/Armas/Cano.jpg")); imgFaca = ImageIO.read(new File("assets/Armas/Faca.jpg")); imgChave = ImageIO.read(new File("assets/Armas/ChaveInglesa.jpg")); imgCastical = ImageIO.read(new File("assets/Armas/Castical.jpg")); imgRevolver = ImageIO.read(new File("assets/Armas/Revolver.jpg")); } catch (IOException e){ System.out.println("Incapaz de abrir arquivo. Erro:" + e.getMessage()); System.exit(1); } } public int getXJogador(int x){ return (int) img_escalaHorizontal*(matriz_larguraColuna*x + matriz_deslocamentoColunas); } public int getXPosJogador(int pos){ System.out.println("pegando x jogador"); return (int) img_escalaHorizontal*(matriz_larguraColuna*(pos%matriz_numColunas) + matriz_deslocamentoColunas); } public int getYJogador(int y){ return (int) img_escalaVertical*(matriz_alturaLinha*y + matriz_deslocamentoLinhas); } public int getYPosJogador(int pos){ return (int) img_escalaVertical*(matriz_alturaLinha*(pos/matriz_numColunas) + matriz_deslocamentoLinhas); } public int getXComodo(int posComodo, int indexComodo) { System.out.println("pegando x de uma arma"); indexComodo += ObservedGame.COZINHA; switch(indexComodo) { case(ObservedGame.COZINHA): return (int) img_escalaHorizontal*(matriz_larguraColuna*(1+(posComodo%4)) + matriz_deslocamentoColunas); case(ObservedGame.JANTAR): return (int) img_escalaHorizontal*(matriz_larguraColuna*(1+(posComodo%4)) + matriz_deslocamentoColunas); case(ObservedGame.ESTAR): return (int) img_escalaHorizontal*(matriz_larguraColuna*(1+(posComodo%4)) + matriz_deslocamentoColunas); case(ObservedGame.MUSICA): return (int) img_escalaHorizontal*(matriz_larguraColuna*(10+(posComodo%4)) + matriz_deslocamentoColunas); case(ObservedGame.ENTRADA): return (int) img_escalaHorizontal*(matriz_larguraColuna*(10+(posComodo%4)) + matriz_deslocamentoColunas); case(ObservedGame.INVERNO): return (int) img_escalaHorizontal*(matriz_larguraColuna*(19+(posComodo%4)) + matriz_deslocamentoColunas); case(ObservedGame.JOGOS): return (int) img_escalaHorizontal*(matriz_larguraColuna*(19+(posComodo%4)) + matriz_deslocamentoColunas); case(ObservedGame.BIBLIOTECA): return (int) img_escalaHorizontal*(matriz_larguraColuna*(19+(posComodo%4)) + matriz_deslocamentoColunas); case(ObservedGame.ESCRITORIO): return (int) img_escalaHorizontal*(matriz_larguraColuna*(19+(posComodo%4)) + matriz_deslocamentoColunas); } return 0; } public int getYComodo(int posComodo, int indexComodo) { indexComodo += ObservedGame.COZINHA; switch(indexComodo) { case(ObservedGame.COZINHA): if(posComodo < 4) return (int) img_escalaVertical*(matriz_alturaLinha*(2) + matriz_deslocamentoLinhas); if(posComodo < 8) return (int) img_escalaVertical*(matriz_alturaLinha*(3) + matriz_deslocamentoLinhas); return (int) img_escalaVertical*(matriz_alturaLinha*(4) + matriz_deslocamentoLinhas); case(ObservedGame.JANTAR): if(posComodo < 4) return (int) img_escalaVertical*(matriz_alturaLinha*(11) + matriz_deslocamentoLinhas); if(posComodo < 8) return (int) img_escalaVertical*(matriz_alturaLinha*(12) + matriz_deslocamentoLinhas); return (int) img_escalaVertical*(matriz_alturaLinha*(13) + matriz_deslocamentoLinhas); case(ObservedGame.ESTAR): if(posComodo < 4) return (int) img_escalaVertical*(matriz_alturaLinha*(21) + matriz_deslocamentoLinhas); if(posComodo < 8) return (int) img_escalaVertical*(matriz_alturaLinha*(22) + matriz_deslocamentoLinhas); return (int) img_escalaVertical*(matriz_alturaLinha*(23) + matriz_deslocamentoLinhas); case(ObservedGame.MUSICA): if(posComodo < 4) return (int) img_escalaVertical*(matriz_alturaLinha*(2) + matriz_deslocamentoLinhas); if(posComodo < 8) return (int) img_escalaVertical*(matriz_alturaLinha*(3) + matriz_deslocamentoLinhas); return (int) img_escalaVertical*(matriz_alturaLinha*(4) + matriz_deslocamentoLinhas); case(ObservedGame.ENTRADA): if(posComodo < 4) return (int) img_escalaVertical*(matriz_alturaLinha*(21) + matriz_deslocamentoLinhas); if(posComodo < 8) return (int) img_escalaVertical*(matriz_alturaLinha*(22) + matriz_deslocamentoLinhas); return (int) img_escalaVertical*(matriz_alturaLinha*(23) + matriz_deslocamentoLinhas); case(ObservedGame.INVERNO): if(posComodo < 4) return (int) img_escalaVertical*(matriz_alturaLinha*(2) + matriz_deslocamentoLinhas); if(posComodo < 8) return (int) img_escalaVertical*(matriz_alturaLinha*(3) + matriz_deslocamentoLinhas); return (int) img_escalaVertical*(matriz_alturaLinha*(4) + matriz_deslocamentoLinhas); case(ObservedGame.JOGOS): if(posComodo < 4) return (int) img_escalaVertical*(matriz_alturaLinha*(9) + matriz_deslocamentoLinhas); if(posComodo < 8) return (int) img_escalaVertical*(matriz_alturaLinha*(10) + matriz_deslocamentoLinhas); return (int) img_escalaVertical*(matriz_alturaLinha*(11) + matriz_deslocamentoLinhas); case(ObservedGame.BIBLIOTECA): if(posComodo < 4) return (int) img_escalaVertical*(matriz_alturaLinha*(15) + matriz_deslocamentoLinhas); if(posComodo < 8) return (int) img_escalaVertical*(matriz_alturaLinha*(16) + matriz_deslocamentoLinhas); return (int) img_escalaVertical*(matriz_alturaLinha*(17) + matriz_deslocamentoLinhas); case(ObservedGame.ESCRITORIO): if(posComodo < 4) return (int) img_escalaVertical*(matriz_alturaLinha*(21) + matriz_deslocamentoLinhas); if(posComodo < 8) return (int) img_escalaVertical*(matriz_alturaLinha*(22) + matriz_deslocamentoLinhas); return (int) img_escalaVertical*(matriz_alturaLinha*(23) + matriz_deslocamentoLinhas); } return 0; } public int getTamanhoTabuleiro(){ return matriz_numLinhas*matriz_numColunas; } public int getDX(){ return (int) (matriz_larguraColuna*img_escalaHorizontal); } public int getDY(){ return (int) (matriz_alturaLinha*img_escalaVertical); } public boolean posValida(int X, int Y, int passo, int indexJogador, boolean pixelFlag) { int xMouse, yMouse; int[] posJogador = {-1, -1, -1, -1}; if(pixelFlag == true){ xMouse = X/matriz_larguraColuna; yMouse = Y/matriz_alturaLinha; } else{ if(X<0 || X>=matriz_numColunas) return false; else xMouse = X; if(Y<0 || Y>=matriz_numLinhas) return false; else yMouse = Y; } int valorPos = matriz[xMouse + yMouse*matriz_numColunas][0]; int yJogador =-1; int xJogador =-1; if(valorPos != Tabuleiro.INVALIDO) { for(int i=0; i < getTamanhoTabuleiro();i++) if(matriz[i][0] == indexJogador){ posJogador[0] = i; break; } if(posJogador[0]==-1) { for(int j=0; j<9; j++) for(int i=0; i<12; i++) if(comodos[j][i] == indexJogador) { //switch para usar posjogador como porta do comodo switch(j + ObservedGame.COZINHA) { case (ObservedGame.COZINHA): if(!jogadorEm(4,7, indexJogador)) posJogador[0] = 4 + 7*matriz_numColunas; break; case (ObservedGame.JANTAR): if(!jogadorEm(8,12, indexJogador)) posJogador[0] = 8 + 12*matriz_numColunas; if(!jogadorEm(6,16, indexJogador)) posJogador[1] = 6 + 16*matriz_numColunas; break; case (ObservedGame.ESTAR): if(!jogadorEm(6,18, indexJogador)) posJogador[0] = 6 + 18*matriz_numColunas; break; case (ObservedGame.MUSICA): if(!jogadorEm(7,5, indexJogador)) posJogador[0] = 7 + 5*matriz_numColunas; if(!jogadorEm(16,5, indexJogador)) posJogador[1] = 16 + 5*matriz_numColunas; if(!jogadorEm(9,8, indexJogador)) posJogador[2] = 9 + 8*matriz_numColunas; if(!jogadorEm(14,8, indexJogador)) posJogador[3] = 14 + 8*matriz_numColunas; break; case (ObservedGame.ENTRADA): if(!jogadorEm(11,17, indexJogador)) posJogador[0] = 11 + 17*matriz_numColunas; if(!jogadorEm(12,17, indexJogador)) posJogador[1] = 12 + 17*matriz_numColunas; if(!jogadorEm(15,20, indexJogador)) posJogador[2] = 15 + 20*matriz_numColunas; break; case (ObservedGame.INVERNO): if(!jogadorEm(18,5, indexJogador)) posJogador[0] = 18 + 5*matriz_numColunas; break; case (ObservedGame.JOGOS): if(!jogadorEm(17, 9, indexJogador)) posJogador[0] = 17 + 9*matriz_numColunas; if(!jogadorEm(22,13, indexJogador)) posJogador[1] = 22 + 13*matriz_numColunas; break; case (ObservedGame.BIBLIOTECA): if(!jogadorEm(16,16, indexJogador)) posJogador[0] = 16 + 16*matriz_numColunas; if(!jogadorEm(20,13, indexJogador)) posJogador[1] = 20 + 13*matriz_numColunas; break; case (ObservedGame.ESCRITORIO): if(!jogadorEm(17, 20, indexJogador)) posJogador[0] = 17 + 20*matriz_numColunas; break; } } if(posJogador[0]==-1) return false; } for(int i=0; i<4; i++) { if(posJogador[i] == -1) break; xJogador = posJogador[i]%matriz_numColunas; yJogador = posJogador[i]/matriz_numColunas; if(matriz[xMouse + yMouse*matriz_numColunas][0] == -1){ System.out.println("nao em comodo"); if(emComodo(indexJogador) == -1){ if(distanciaValida(xMouse, yMouse, xJogador, yJogador, passo) && !jogadorEm(xMouse, yMouse, indexJogador)) return true; } else if(movimentacaoValidaSaindoComodo(xMouse, yMouse, passo, indexJogador)) return true; } else{ System.out.println("em comodo"); return movimentacaoValidaComodo(xMouse, yMouse, xJogador, yJogador, passo, indexJogador); } } } return false; } private boolean movimentacaoValidaComodo(int xMouse, int yMouse, int xJogador, int yJogador, int passo, int indexJogador) { //Dentro da cozinha if(matriz[xMouse + yMouse*matriz_numColunas][0] == ObservedGame.COZINHA) if(distanciaValida(4, 7, xJogador, yJogador, passo-1) && !jogadorEm(4, 7, indexJogador)) return true; //Dentro da sala de musica if(matriz[xMouse + yMouse*matriz_numColunas][0] == ObservedGame.MUSICA) if( (distanciaValida(7, 5, xJogador, yJogador, passo-1) && !jogadorEm(7,5, indexJogador)) || (distanciaValida(16, 5, xJogador, yJogador, passo-1) && !jogadorEm(16,5, indexJogador)) || (distanciaValida(9, 8, xJogador, yJogador, passo-1) && !jogadorEm(9,8, indexJogador)) || (distanciaValida(14, 8, xJogador, yJogador, passo-1) && !jogadorEm(14,8, indexJogador)) ) return true; //Dentro do jardim de inverno if(matriz[xMouse + yMouse*matriz_numColunas][0] == ObservedGame.INVERNO) if(distanciaValida(18, 5, xJogador, yJogador, passo-1) && !jogadorEm(18, 5, indexJogador)) return true; //Dentro do salao de jogos if(matriz[xMouse + yMouse*matriz_numColunas][0] == ObservedGame.JOGOS) if(((distanciaValida(17, 9, xJogador, yJogador, passo-1) && !jogadorEm(17,9, indexJogador)) || (distanciaValida(22, 13, xJogador, yJogador, passo-1) && !jogadorEm(22,13, indexJogador)))) return true; //Dentro da biblioteca if(matriz[xMouse + yMouse*matriz_numColunas][0] == ObservedGame.BIBLIOTECA) if(((distanciaValida(16, 16, xJogador, yJogador, passo-1) && !jogadorEm(16,16, indexJogador)) || (distanciaValida(20, 13, xJogador, yJogador, passo-1) && !jogadorEm(20,13, indexJogador)))) return true; //Dentro do escritorio if(matriz[xMouse + yMouse*matriz_numColunas][0] == ObservedGame.ESCRITORIO) if(distanciaValida(17, 20, xJogador, yJogador, passo-1) && !jogadorEm(17,20, indexJogador)) return true; //Dentro da entrada if(matriz[xMouse + yMouse*matriz_numColunas][0] == ObservedGame.ENTRADA) if(( (distanciaValida(11, 17, xJogador, yJogador, passo-1) && !jogadorEm(11,17, indexJogador)) || (distanciaValida(12, 17, xJogador, yJogador, passo-1) && !jogadorEm(12,17, indexJogador)) || (distanciaValida(15, 20, xJogador, yJogador, passo-1) && !jogadorEm(15,20, indexJogador))) ) return true; //Dentro da sala de estar if(matriz[xMouse + yMouse*matriz_numColunas][0] == ObservedGame.ESTAR) if(distanciaValida(6, 18, xJogador, yJogador, passo-1) && !jogadorEm(6,18, indexJogador)) return true; //Dentro da sala de jantar if(matriz[xMouse + yMouse*matriz_numColunas][0] == ObservedGame.JANTAR){ if(((distanciaValida(8, 12, xJogador, yJogador, passo-1) && !jogadorEm(8,12, indexJogador)) || (distanciaValida(6, 16, xJogador, yJogador, passo-1) && !jogadorEm(6,16, indexJogador)))) return true;} return false; } private boolean movimentacaoValidaSaindoComodo(int xMouse, int yMouse, int passo, int indexJogador){ int comodoJogador = emComodo(indexJogador); //Dentro da cozinha switch(comodoJogador) { case ObservedGame.COZINHA: if(distanciaValida(4, 7, xMouse, yMouse, passo-1) && !jogadorEm(4,7, indexJogador)) return true; //Dentro da sala de musica case ObservedGame.MUSICA: if( (distanciaValida(7, 5, xMouse, yMouse, passo-1) && !jogadorEm(7,5, indexJogador)) || (distanciaValida(16, 5, xMouse, yMouse, passo-1) && !jogadorEm(16,5, indexJogador)) || (distanciaValida(9, 8, xMouse, yMouse, passo-1) && !jogadorEm(9,8, indexJogador)) || (distanciaValida(14, 8, xMouse, yMouse, passo-1) && !jogadorEm(14,8, indexJogador)) ) return true; //Dentro do jardim de inverno case ObservedGame.INVERNO: if(distanciaValida(18, 5, xMouse, yMouse, passo-1) && !jogadorEm(18, 5, indexJogador)) return true; //Dentro do salao de jogos case ObservedGame.JOGOS: if(((distanciaValida(17, 9, xMouse, yMouse, passo-1) && !jogadorEm(17,9, indexJogador)) || (distanciaValida(22, 13, xMouse, yMouse, passo-1) && !jogadorEm(22,13, indexJogador)))) return true; //Dentro da biblioteca case ObservedGame.BIBLIOTECA: if(((distanciaValida(16, 16, xMouse, yMouse, passo-1) && !jogadorEm(16,16, indexJogador)) || (distanciaValida(20, 13, xMouse, yMouse, passo-1) && !jogadorEm(20,13, indexJogador)))) return true; //Dentro do escritorio case ObservedGame.ESCRITORIO: if(distanciaValida(17, 20, xMouse, yMouse, passo-1) && !jogadorEm(17,20, indexJogador)) return true; //Dentro da entrada case ObservedGame.ENTRADA: if(((distanciaValida(11, 17, xMouse, yMouse, passo-1) && !jogadorEm(11,17, indexJogador)) || (distanciaValida(12, 17, xMouse, yMouse, passo-1) && !jogadorEm(12,17, indexJogador)) || (distanciaValida(15, 20, xMouse, yMouse, passo-1) && !jogadorEm(15,20, indexJogador))) ) return true; //Dentro da sala de estar case ObservedGame.ESTAR: if(distanciaValida(6, 18, xMouse, yMouse, passo-1) && !jogadorEm(6,18, indexJogador)) return true; //Dentro da sala de jantar case ObservedGame.JANTAR: if(((distanciaValida(8, 12, xMouse, yMouse, passo-1) && !jogadorEm(8,12, indexJogador)) || (distanciaValida(6, 16, xMouse, yMouse, passo-1) && !jogadorEm(6,16, indexJogador)))) return true; } return false; } public int emComodo(int indexJogador) { for(int j=0; j<9; j++) for(int i=0; i<12; i++) if(comodos[j][i] == indexJogador) return j + ObservedGame.COZINHA; return -1; } private boolean jogadorEm(int x, int y, int indexJogador) { if(matriz[x+y*matriz_numColunas][0] != Tabuleiro.INVALIDO && matriz[x+y*matriz_numColunas][0] != Tabuleiro.VAZIO && matriz[x+y*matriz_numColunas][0] != Tabuleiro.ALCANCE && matriz[x+y*matriz_numColunas][0] != indexJogador) return true; return false; } private boolean distanciaValida(int x, int y, int xJogador, int yJogador, int passo) { if(Math.abs(x-xJogador) + Math.abs(y-yJogador) <= passo) return true; System.out.println("Muito longe!"); return false; } public void mudaPosJogadorPassagemSecreta(int indexJogador, int comodoJogador) { for(int j=0; j<ObservedGame.numPlayers+ObservedGame.numWeapons; j++) { if(comodos[comodoJogador - ObservedGame.COZINHA][j] == indexJogador){ comodos[comodoJogador - ObservedGame.COZINHA][j] = Tabuleiro.VAZIO; break; } } switch(comodoJogador) { case(ObservedGame.COZINHA): for(int j=0; j<ObservedGame.numPlayers+ObservedGame.numWeapons; j++) { if(comodos[ObservedGame.ESCRITORIO - ObservedGame.COZINHA][j] == Tabuleiro.VAZIO){ comodos[ObservedGame.ESCRITORIO - ObservedGame.COZINHA][j] = indexJogador; break; } } break; case(ObservedGame.ESTAR): for(int j=0; j<ObservedGame.numPlayers+ObservedGame.numWeapons; j++) { if(comodos[ObservedGame.INVERNO - ObservedGame.COZINHA][j] == Tabuleiro.VAZIO){ comodos[ObservedGame.INVERNO - ObservedGame.COZINHA][j] = indexJogador; break; } } break; case(ObservedGame.INVERNO): for(int j=0; j<ObservedGame.numPlayers+ObservedGame.numWeapons; j++) { if(comodos[ObservedGame.ESTAR - ObservedGame.COZINHA][j] == Tabuleiro.VAZIO){ comodos[ObservedGame.ESTAR - ObservedGame.COZINHA][j] = indexJogador; break; } } break; case(ObservedGame.ESCRITORIO): for(int j=0; j<ObservedGame.numPlayers+ObservedGame.numWeapons; j++) { if(comodos[ObservedGame.COZINHA - ObservedGame.COZINHA][j] == Tabuleiro.VAZIO){ comodos[ObservedGame.COZINHA - ObservedGame.COZINHA][j] = indexJogador; break; } } break; } } public void mudaPosJogador(int pixelX, int pixelY, int indexJogador) { int x = pixelX/matriz_larguraColuna; int y = pixelY/matriz_alturaLinha; int flag = 0; for(int i=0; i<getTamanhoTabuleiro(); i++){ if(matriz[i][0] == indexJogador){ matriz[i][0] = Tabuleiro.VAZIO; flag = 1; break; } } if(flag==0) { for(int i=0; i<ObservedGame.numRooms; i++){ for(int j=0; j<ObservedGame.numPlayers+ObservedGame.numWeapons; j++) { if(comodos[i][j] == indexJogador){ comodos[i][j] = Tabuleiro.VAZIO; break; } } } } switch(matriz[x + y*matriz_numColunas][0]) { case(ObservedGame.COZINHA): for(int i=0; i<ObservedGame.numPlayers+ObservedGame.numWeapons; i++) if(comodos[0][i] == Tabuleiro.VAZIO){ comodos[0][i] = indexJogador; break; } break; case(ObservedGame.JANTAR): for(int i=0; i<ObservedGame.numPlayers+ObservedGame.numWeapons; i++) if(comodos[1][i] == Tabuleiro.VAZIO){ comodos[1][i] = indexJogador; break; } break; case(ObservedGame.ESTAR): for(int i=0; i<ObservedGame.numPlayers+ObservedGame.numWeapons; i++) if(comodos[2][i] == Tabuleiro.VAZIO){ comodos[2][i] = indexJogador; break; } break; case(ObservedGame.MUSICA): for(int i=0; i<ObservedGame.numPlayers+ObservedGame.numWeapons; i++) if(comodos[3][i] == Tabuleiro.VAZIO){ comodos[3][i] = indexJogador; break; } break; case(ObservedGame.ENTRADA): for(int i=0; i<ObservedGame.numPlayers+ObservedGame.numWeapons; i++) if(comodos[4][i] == Tabuleiro.VAZIO){ comodos[4][i] = indexJogador; break; } break; case(ObservedGame.INVERNO): for(int i=0; i<ObservedGame.numPlayers+ObservedGame.numWeapons; i++) if(comodos[5][i] == Tabuleiro.VAZIO){ comodos[5][i] = indexJogador; break; } break; case(ObservedGame.JOGOS): for(int i=0; i<ObservedGame.numPlayers+ObservedGame.numWeapons; i++) if(comodos[6][i] == Tabuleiro.VAZIO){ comodos[6][i] = indexJogador; break; } break; case(ObservedGame.BIBLIOTECA): for(int i=0; i<ObservedGame.numPlayers+ObservedGame.numWeapons; i++) if(comodos[7][i] == Tabuleiro.VAZIO){ comodos[7][i] = indexJogador; break; } break; case(ObservedGame.ESCRITORIO): for(int i=0; i<ObservedGame.numPlayers+ObservedGame.numWeapons; i++) if(comodos[8][i] == Tabuleiro.VAZIO){ comodos[8][i] = indexJogador; break; } break; default: matriz[x+y*matriz_numColunas][0] = indexJogador; break; } } public void mudaPosArma(int indexComodo, int indexArma) { for(int j=0; j<9; j++) for(int i=0; i<12; i++) if(comodos[j][i] == indexArma) { comodos[j][i] = Tabuleiro.VAZIO; } switch(indexComodo) { case (ObservedGame.COZINHA): for(int i=0; i<12;i++) if(comodos[ObservedGame.COZINHA - 12][i] == -1){ comodos[ObservedGame.COZINHA - 12][i] = indexArma; break; } break; case (ObservedGame.JANTAR): for(int i=0; i<12;i++) if(comodos[ObservedGame.JANTAR - 12][i] == -1){ comodos[ObservedGame.JANTAR - 12][i] = indexArma; break; } break; case (ObservedGame.ESTAR): for(int i=0; i<12;i++) if(comodos[ObservedGame.ESTAR - 12][i] == -1){ comodos[ObservedGame.ESTAR - 12][i] = indexArma; break; } break; case (ObservedGame.MUSICA): for(int i=0; i<12;i++) if(comodos[ObservedGame.MUSICA - 12][i] == -1){ comodos[ObservedGame.MUSICA - 12][i] = indexArma; break; } break; case (ObservedGame.ENTRADA): for(int i=0; i<12;i++) if(comodos[ObservedGame.ENTRADA - 12][i] == -1){ comodos[ObservedGame.ENTRADA - 12][i] = indexArma; break; } break; case (ObservedGame.INVERNO): for(int i=0; i<12;i++) if(comodos[ObservedGame.INVERNO - 12][i] == -1){ comodos[ObservedGame.INVERNO - 12][i] = indexArma; break; } break; case (ObservedGame.JOGOS): for(int i=0; i<12;i++) if(comodos[ObservedGame.JOGOS - 12][i] == -1){ comodos[ObservedGame.JOGOS - 12][i] = indexArma; break; } break; case (ObservedGame.BIBLIOTECA): for(int i=0; i<12;i++) if(comodos[ObservedGame.BIBLIOTECA - 12][i] == -1){ comodos[ObservedGame.BIBLIOTECA - 12][i] = indexArma; break; } break; case (ObservedGame.ESCRITORIO): for(int i=0; i<12;i++) if(comodos[ObservedGame.ESCRITORIO - 12][i] == -1){ comodos[ObservedGame.ESCRITORIO - 12][i] = indexArma; break; } break; } } public double getEscalaHorizontal(){ return img_escalaHorizontal; } public void setEscalaHorizontal(double width){ img_escalaHorizontal = width/imgTabuleiro.getWidth(); } public double getEscalaVertical(){ return img_escalaVertical; } public void setEscalaVertical(double height){ img_escalaVertical = height/imgTabuleiro.getHeight(); } public void AdicionaAlcance(int die, int jogador) { int[] posJogador= {-1,-1,-1,-1}; int xJogador, yJogador, comodoJogador=-1; int Ymin, Ymax; for(int i=0; i<getTamanhoTabuleiro(); i++) if(matriz[i][0] == jogador){ posJogador[0] = i; break; } if(posJogador[0]==-1) { for(int j=0; j<9; j++) for(int i=0; i<12; i++) if(comodos[j][i] == jogador) { //switch para usar posjogador como porta do comodo switch(j + ObservedGame.COZINHA) { case (ObservedGame.COZINHA): comodoJogador = ObservedGame.COZINHA; if(!jogadorEm(4,7, jogador)) posJogador[0] = 4 + 7*matriz_numColunas; break; case (ObservedGame.JANTAR): comodoJogador = ObservedGame.JANTAR; if(!jogadorEm(8,12, jogador)) posJogador[0] = 8 + 12*matriz_numColunas; if(!jogadorEm(6,16, jogador)) posJogador[1] = 6 + 16*matriz_numColunas; break; case (ObservedGame.ESTAR): comodoJogador = ObservedGame.ESTAR; if(!jogadorEm(6,18, jogador)) posJogador[0] = 6 + 18*matriz_numColunas; break; case (ObservedGame.MUSICA): comodoJogador = ObservedGame.MUSICA; if(!jogadorEm(7,5, jogador)) posJogador[0] = 7 + 5*matriz_numColunas; if(!jogadorEm(16,5, jogador)) posJogador[1] = 16 + 5*matriz_numColunas; if(!jogadorEm(9,8, jogador)) posJogador[2] = 9 + 8*matriz_numColunas; if(!jogadorEm(14,8, jogador)) posJogador[3] = 14 + 8*matriz_numColunas; break; case (ObservedGame.ENTRADA): comodoJogador = ObservedGame.ENTRADA; if(!jogadorEm(11,17, jogador)) posJogador[0] = 11 + 17*matriz_numColunas; if(!jogadorEm(12,17, jogador)) posJogador[1] = 12 + 17*matriz_numColunas; if(!jogadorEm(15,20, jogador)) posJogador[2] = 15 + 20*matriz_numColunas; break; case (ObservedGame.INVERNO): comodoJogador = ObservedGame.INVERNO; if(!jogadorEm(18,5, jogador)) posJogador[0] = 18 + 5*matriz_numColunas; break; case (ObservedGame.JOGOS): comodoJogador = ObservedGame.JOGOS; if(!jogadorEm(17, 9, jogador)) posJogador[0] = 17 + 9*matriz_numColunas; if(!jogadorEm(22,13, jogador)) posJogador[1] = 22 + 13*matriz_numColunas; break; case (ObservedGame.BIBLIOTECA): comodoJogador = ObservedGame.BIBLIOTECA; if(!jogadorEm(16,16, jogador)) posJogador[0] = 16 + 16*matriz_numColunas; if(!jogadorEm(20,13, jogador)) posJogador[1] = 20 + 13*matriz_numColunas; break; case (ObservedGame.ESCRITORIO): comodoJogador = ObservedGame.ESCRITORIO; if(!jogadorEm(17, 20, jogador)) posJogador[0] = 17 + 20*matriz_numColunas; break; } } if(posJogador[0]==-1) return; } for(int k=0; k<4; k++) { if(posJogador[k] == -1) break; xJogador = posJogador[k]%matriz_numColunas; yJogador = posJogador[k]/matriz_numColunas; if(yJogador-die <= 0) Ymin =0; else Ymin =yJogador-die; if(yJogador+die >= matriz_numLinhas) Ymax = matriz_numLinhas-1; else Ymax = yJogador+die; for(int i=Ymin; i<=Ymax; i++){ for(int passosRestantes = die - Math.abs(yJogador-i); passosRestantes>=0; passosRestantes--){ if(yJogador==i && passosRestantes==0 && comodoJogador == -1) break; if(posValida(xJogador+passosRestantes, i, die, jogador, false) && (comodoJogador == -1 || comodoJogador != matriz[i*matriz_numColunas +(xJogador+passosRestantes)][0])){ matriz[i*matriz_numColunas +(xJogador+passosRestantes)][1] = Tabuleiro.ALCANCE; } if(posValida(xJogador-passosRestantes, i, die, jogador, false) && (comodoJogador == -1 || comodoJogador != matriz[i*matriz_numColunas +(xJogador-passosRestantes)][0])){ matriz[i*matriz_numColunas +(xJogador-passosRestantes)][1] = Tabuleiro.ALCANCE; } } } } } public void removeAlcance() { for(int i=0; i<getTamanhoTabuleiro(); i++) if(matriz[i][1] == Tabuleiro.ALCANCE) matriz[i][1] = Tabuleiro.VAZIO; } }
package com.oa.user.controller; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.oa.base.form.exception.SpringException; import com.oa.group.form.Group; import com.oa.group.service.GroupService; import com.oa.role.form.RoleInfo; import com.oa.role.service.RoleInfoService; import com.oa.user.form.UserInfo; import com.oa.user.form.UserInfoModel; import com.oa.user.service.UserInfoService; @Controller @RequestMapping("/setting/userManager") public class UserInfoController { @Autowired private UserInfoService userInfoService; private RoleInfoService roleInfoService; private GroupService groupService; private ServletContext servletContext; @RequestMapping(value="/listUser") public String listUser(Map<String,Object> map){ map.put("userInfo", new UserInfoModel()); map.put("userInfoList",userInfoService.selectAllUser()); return "/setting/userManager/userInfo"; } @RequestMapping(value="/addUser",method = RequestMethod.POST) public String addUser(@ModelAttribute("userInfo")UserInfo userInfo,BindingResult bindingResult ){ userInfoService.addUser(userInfo); return "redirect:/setting/userManager/listUser"; } private void validateImage(MultipartFile image) { if (!image.getContentType().equals("image/jpeg")) { throw new RuntimeException("Only JPG images are accepted"); } } private void saveImage(String filename, MultipartFile image) throws RuntimeException, IOException { try { File file = new File(servletContext.getRealPath("/") + "/" + filename); FileUtils.writeByteArrayToFile(file, image.getBytes()); System.out.println("Go to the location: " + file.toString() + " on your computer and verify that the image has been stored."); } catch (IOException e) { throw e; } } @RequestMapping(value="/updateUser",method=RequestMethod.POST) public String updateUser(@ModelAttribute("userInfo")UserInfo userInfo,BindingResult bindingResult){ userInfoService.updateUser(userInfo); return "redirect:/setting/userManager/listUser"; } @RequestMapping(value="/forwardUpdate/{updateUserId}") public ModelAndView forwardUpdate(@PathVariable("updateUserId") Integer id){ UserInfo userInfo = userInfoService.selectUserById(id); Map<String,Object> model = new HashMap<String,Object>(); model.put("userInfo", userInfo); return new ModelAndView("/setting/userManager/forwardUpdate",model); } @RequestMapping(value="/removeUser/{id}") public String removeUser(@PathVariable("id") Integer id){ userInfoService.removeUser(id); return "redirect:/setting/userManager/listUser"; } @RequestMapping(value="/deleteUser/{userId}") public String deleteUser(@PathVariable("userId") Integer id){ userInfoService.deleteUser(id); return "redirect:/setting/userManager/listUser"; } @RequestMapping(value="/assginRoles/{id}") public ModelAndView addRoles(@PathVariable("id") Integer id){ UserInfo userinfo = userInfoService.selectUserById(id); List<RoleInfo> selectAllRoleInfo = roleInfoService.selectAllRoleInfo(); Map<String,Object> model = new HashMap<String,Object>(); model.put("userInfo1", userinfo); model.put("roleList", selectAllRoleInfo); return new ModelAndView("/setting/userManager/assginRoles",model); } @RequestMapping(value="/saveAssignRole",method = RequestMethod.POST) public ModelAndView saveAssignRole(HttpServletRequest request){ String userId = request.getParameter("id"); UserInfo userInfo = userInfoService.selectUserById(Integer.parseInt(userId)); String[] values = request.getParameterValues("roles"); if(values==null || values.length==0){ throw new SpringException("at least one checkbox (roles) should be checked"); } Set<RoleInfo> sets = new HashSet<RoleInfo>(); for(String roleId : values){ RoleInfo role = roleInfoService.selectRoleInfoById(Integer.parseInt(roleId)); if(role!=null) sets.add(role); } userInfo.setRoles(sets); userInfoService.updateUser(userInfo); UserInfo info = userInfoService.selectUserById(Integer.parseInt(userId)); Map<String,Object> model = new HashMap<String,Object>(); model.put("userInfo", info); return new ModelAndView("/setting/userManager/userRoleList",model); } @RequestMapping(value="/assginGroups/{id}") public ModelAndView addGroups(@PathVariable("id") Integer id){ UserInfo userinfo = userInfoService.selectUserById(id); List<Group> groupList = groupService.selectAllGroup(); Map<String,Object> model = new HashMap<String,Object>(); model.put("userInfo", userinfo); model.put("groupList", groupList); return new ModelAndView("/setting/userManager/assginGroups",model); } @RequestMapping(value="/saveAssignGroup",method = RequestMethod.POST) public String saveAssignGroup(HttpServletRequest request){ String userId = request.getParameter("id"); UserInfo userInfo = userInfoService.selectUserById(Integer.parseInt(userId)); String[] values = request.getParameterValues("groups"); if(values==null || values.length==0){ throw new SpringException("at least one checkbox (roles) should be checked"); } Set<Group> sets = new HashSet<Group>(); for(String groupId : values){ Group group = groupService.selectGroupById(Integer.parseInt(groupId)); if(group!=null) sets.add(group); } userInfo.setGroups(sets); userInfoService.updateUser(userInfo); return "redirect:/setting/userManager/userGroupList/"+userId; } @RequestMapping(value="/userGroupList/{userId}") public ModelAndView getUserGroupList(@PathVariable("userId")String userId){ UserInfo info = userInfoService.selectUserById(Integer.parseInt(userId)); Map<String,Object> model = new HashMap<String,Object>(); model.put("userInfo", info); return new ModelAndView("/setting/userManager/userGroupList",model); } }
package util; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; public class DosugNavigatorApplication extends Application { SharedPreferences preferences; DosugNavigatorApplication application; public SharedPreferences getPreferences() { return preferences; } public void setPreferences(SharedPreferences preferences) { this.preferences = preferences; } Context context; @Override public void onCreate() { super.onCreate(); context = this; application = this; preferences = getSharedPreferences("dosugnavigator", 0); } // public static void exception_handler(Activity act) { // Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(act)); // } // // public static void exception_handler_home(Activity act) { // Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler_home(act)); // } }
package com.epam.training.klimov.rentalservice.entities; import java.io.Serializable; import java.util.Map; /** * The class Shop describes equipment available to rent and their quantity. * * @author Konstantin Klimov */ public class Shop implements Serializable { private static final long serialVersionUID = 1L; private Map<SportEquipment, Integer> goods; public Shop() { } public Map<SportEquipment, Integer> getGoods() { return goods; } public void setGoods(Map<SportEquipment, Integer> goods) { this.goods = goods; } }
package Lab_session3; public class Controller { public static void main(String[] args) { SubThread a1 = new SubThread(); Thread thread = new Thread(a1); thread.start(); }
package commands.server.ingame; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import cards.Card; import cards.Card.Color; import cards.basics.Attack; import core.player.PlayerCompleteServer; import core.player.PlayerInfo; import core.server.game.BattleLog; import core.server.game.GameInternal; import core.server.game.controllers.AbstractSingleStageGameController; import core.server.game.controllers.GameController; import core.server.game.controllers.mechanics.AttackGameController; import core.server.game.controllers.mechanics.UseCardOnHandGameController; import exceptions.server.game.GameFlowInterruptedException; import exceptions.server.game.IllegalPlayerActionException; import exceptions.server.game.InvalidCardException; import exceptions.server.game.InvalidPlayerCommandException; public class SerpentSpearInitiateAttackInGameServerCommand extends InGameServerCommand { private static final long serialVersionUID = 1L; private final Set<PlayerInfo> targets; private Set<Card> cards; public SerpentSpearInitiateAttackInGameServerCommand(Set<PlayerInfo> targets, Set<Card> cards) { this.targets = targets; this.cards = cards; } @Override public GameController getGameController() { return new AbstractSingleStageGameController() { @Override protected void handleOnce(GameInternal game) throws GameFlowInterruptedException { try { Set<PlayerCompleteServer> set = targets.stream().map(target -> game.findPlayer(target)).collect(Collectors.toSet()); source.useAttack(); Color color = cards.stream().map(card -> card.getColor()).reduce( cards.iterator().next().getColor(), (c1, c2) -> c1 == c2 ? c1 : Color.COLORLESS ); game.pushGameController(new AttackGameController(source, set, new Attack(color))); game.pushGameController(new UseCardOnHandGameController(source, cards)); game.log(BattleLog .playerAUsedEquipment(source, source.getWeapon()) .withCards(cards) .to("convert into an Attack") .onPlayers(set) ); } catch (InvalidPlayerCommandException e) { // TODO handle error e.printStackTrace(); } } }; } @Override public void validate(GameInternal game) throws IllegalPlayerActionException { if (source.getAttackUsed() >= source.getAttackLimit()) { throw new IllegalPlayerActionException("Serpent Spear: Player may no longer attack this turn"); } if (cards == null || cards.size() != 2) { throw new IllegalPlayerActionException("Serpent Spear: Must use 2 cards"); } if (targets == null) { throw new IllegalPlayerActionException("Serpent Spear: Targets cannot be null"); } if (targets.size() > source.getAttackTargetLimit()) { throw new IllegalPlayerActionException("Serpent Spear: Too many targets"); } Set<Card> replacement = new HashSet<>(); for (Card card : cards) { try { card = game.getDeck().getValidatedCard(card); replacement.add(card); } catch (InvalidCardException e) { throw new IllegalPlayerActionException("Serpent Spear: Card is invalid. " + e.getMessage()); } if (!source.getCardsOnHand().contains(card)) { throw new IllegalPlayerActionException("Serpent Spear: Player does not own the card used"); } } cards = replacement; Set<PlayerCompleteServer> tgts = new HashSet<>(); for (PlayerInfo target : targets) { PlayerCompleteServer other = game.findPlayer(target); tgts.add(other); if (other == null) { throw new IllegalPlayerActionException("Serpent Spear: Target not found"); } if (source.equals(other)) { throw new IllegalPlayerActionException("Serpent Spear: Target cannot be oneself"); } if (!source.isPlayerInAttackRange(other, game.getNumberOfPlayersAlive())) { throw new IllegalPlayerActionException("Serpent Spear: Target not in attack range"); } if (!other.isAlive()) { throw new IllegalPlayerActionException("Serpent Spear: Target not alive"); } } if (tgts.size() < targets.size()) { throw new IllegalPlayerActionException("Serpent Spear: Cannot have duplicated targets"); } } }
/* * Copyright 2016 TeddySoft Technology. All rights reserved. * */ package tw.teddysoft.gof.FactoryMethod; public abstract class DriveManager { public Drive getDrive(String type, int index){ Drive drive = createDrive(type, index); drive.updateFreeSpace(); drive.doQuickSMARTCheck(); return drive; } abstract protected Drive createDrive(String type, int index); }
package org.abhi.spring.service; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.abhi.spring.model.Movie; public class GetRating { public String imdbKey; private ConcurrentLinkedQueue<Movie> list; private List<Future<Movie>> futures = new ArrayList<>(); public ConcurrentLinkedQueue<Movie> getMovies(String[] names) throws UnsupportedEncodingException { list = new ConcurrentLinkedQueue<Movie>(); ExecutorService executorService=Executors.newFixedThreadPool(20); for (int i = 0; i < names.length; i++) { if (names[i].length() < 2) continue; names[i] = names[i].replaceAll( "[\\W_]|brrip|bluray|blu\\sray|bdrip|" + "camrip|extended edition|extended collectors edition|Director s Cut|dual audio|dual|hdrip|webrip|web\\-dl", " "); Matcher m = Pattern.compile("((19|20)\\d{2})").matcher(names[i]); String year = ""; if (m.find()) year = m.group(0); String[] str = names[i].split("(19|20)\\d{2}"); //System.out.println("string is=" + str[0] + " " + year); if(imdbKey.equals("")) futures.add(executorService.submit(new ConcurrentRatingHelper(URLEncoder.encode(str[0], "UTF-8"), year))); else futures.add(executorService.submit(new ConcurrentRatingHelperIMDB(URLEncoder.encode(str[0], "UTF-8"), year,imdbKey))); } executorService.shutdown(); try { for(Future<Movie> f : futures) list.add(f.get()); } catch (InterruptedException | ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } }
import java.io.*; class TestVariable { int instanceVariable = 100; static int staticVariable = 200; void method() { int localVariable = 300; System.out.println("Local varibale:"+localVariable); } public static void main(String args[]) { System.out.println("static Variable:"+staticVariable); TestVariable tv = new TestVariable(); System.out.println("Instance Varible:"+tv.instanceVariable); System.out.println("static Variable:"+tv.staticVariable); tv.method(); } }
package com.bill.notification.system; public class SaveBills { private String billName; private String dueDate; public String getBillName() { return billName; } public void setBillName(String billName) { this.billName = billName; } public String getDueDate() { return dueDate; } public void setDueDate(String dueDate) { this.dueDate = dueDate; } }
package walnoot.dodgegame.components; import walnoot.dodgegame.DodgeGame; import walnoot.dodgegame.SpriteAccessor; import aurelienribon.tweenengine.Tween; import com.badlogic.gdx.math.Vector2; public class MoveComponent extends Component{ private static final float SPEED = 2.5f; private static final float FADE_OUT_TIME = 0.5f; private static final float FADE_OUT_THRESHOLD = PlayerComponent.MOVE_RADIUS * PlayerComponent.MOVE_RADIUS; private int fadeTimer = 0; // private float dx, dy; private Vector2 translation = new Vector2(); public MoveComponent(Entity owner){ super(owner); } public void init(Vector2 translation){ init(translation.x, translation.y); } public void init(float dx, float dy){ fadeTimer = 0; setTranslation(dx, dy); } public void update(){ owner.translate(translation); float absX = owner.getxPos(); if(absX < 0) absX = -absX; float absY = owner.getyPos(); if(absY < 0) absY = -absY; // if(absX > GameState.MAP_SIZE || absY > GameState.MAP_SIZE){ if(owner.getPos().len2() < FADE_OUT_THRESHOLD){ if(fadeTimer == 0) Tween.to(owner.getComponent(SpriteComponent.class).getSprite(), SpriteAccessor.TRANSPARANCY, FADE_OUT_TIME).target(0f).start(DodgeGame.TWEEN_MANAGER); fadeTimer++; if(fadeTimer > DodgeGame.UPDATES_PER_SECOND * FADE_OUT_TIME) owner.remove(); } } /** * Sets the translation, give an normalized vector dictating the direction * * @param dx * @param dy */ public void setTranslation(float dx, float dy){ translation.set(dx * SPEED * DodgeGame.SECONDS_PER_UPDATE, dy * SPEED * DodgeGame.SECONDS_PER_UPDATE); } }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class PgsqlConnection { /********************************************************/ public static void loadDriver() { try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException cnfe) { System.out.println("Couldn't find driver class!"); cnfe.printStackTrace(); System.exit(1); } } /********************************************************/ private static String getPassword() { BufferedReader br = null; try { br = new BufferedReader(new FileReader("password.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } String password = null; try { password = br.readLine(); } catch (IOException | NullPointerException e) { e.printStackTrace(); } return password; } /********************************************************/ private static Connection getConnection(String password) { Connection postGresConn; try { postGresConn = DriverManager.getConnection("jdbc:postgresql://pgsql3.mif/studentu", "pane5605", password) ; } catch (SQLException sqle) { System.out.println("Couldn't connect to database!"); sqle.printStackTrace(); return null ; } System.out.println("Successfully connected to Postgres Database"); return postGresConn ; } /********************************************************/ public static void main(String[] args) { loadDriver() ; Connection connection = getConnection(getPassword()) ; if(connection != null) { System.out.println("Sekmingai prisijungta prie mokyklos pazymiu ir asmeniniu duomenu saugojimo sistemos!"); MainMeniu mainMeniu = new MainMeniu(connection); mainMeniu.start(); } if(connection != null) { try { connection.close() ; } catch (SQLException exp) { System.out.println("Cannot close connection!"); exp.printStackTrace(); } } } }
import java.util.*; class contactPersonNew { private int id; private String firstName; private String lastName; private String address; private String city; private String state; private String zip; private String phoneNumber; public contactPersonNew(String firstName,String lastName,String address,String city,String state, String zip,String phoneNumber,int id){ this.id = id; this.firstName = firstName; this.lastName = lastName; this.address = address; this.city = city; this.state = state; this.zip = zip; this.phoneNumber = phoneNumber; } contactPersonNew() { //pass } public String[] userInput() { String arr[] = new String[7]; Scanner sc = new Scanner(System.in); System.out.print("Enter FirstName : "); String firstName = sc.nextLine(); arr[0] = firstName; System.out.print("Enter LastName : "); String lastName = sc.nextLine(); arr[1] = lastName; System.out.print("Enter Address : "); String address = sc.nextLine(); arr[2] = address; System.out.print("Enter City : "); String city = sc.nextLine(); arr[3] = city; System.out.print("Enter State : "); String state = sc.nextLine(); arr[4] = state; System.out.print("Enter PhoneNUmber : "); String phoneNumber = sc.nextLine(); arr[5] = phoneNumber; System.out.print("Enter Zip : "); String zip = sc.nextLine(); arr[6] = zip; return arr; } public String getFirstName() { return this.firstName; } public String userToBeEdited() { System.out.println("enter the username you want to edit"); Scanner uname = new Scanner(System.in); String name = uname.nextLine(); return name; } public void removeElement(contactPersonNew[] array , int index) { for (int i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; } } public void display() { System.out.println("Id: "+this.id); System.out.println("FirstName: "+this.firstName); System.out.println("LastName: "+this.lastName); System.out.println("Address: "+this.address); System.out.println("City: "+this.city); System.out.println("State: "+this.state); System.out.println("Zip: "+this.zip); System.out.println("PhoneNumber: "+this.phoneNumber); } } public class addressBook { public static void main(String args[]) { System.out.println("enter the number of user you want to enter"); Scanner num = new Scanner(System.in); int n = num.nextInt(); int comp = (int)n; contactPersonNew Storage[] = new contactPersonNew[n]; contactPersonNew ob = new contactPersonNew(); for(int i = 0;i<Storage.length;i++) { String res[] = ob.userInput(); String firstName = res[0]; String lastName = res[1]; String address = res[2]; String city = res[3]; String state = res[4]; String zip = res[5]; String phoneNumber = res[6]; int uid = i; Storage[i] = new contactPersonNew(firstName, lastName, address, city, state, zip, phoneNumber, uid); System.out.println(" "); if(comp > 1) { System.out.println("enter deatils of next user "); } } String get = ob.userToBeEdited(); for(int i = 0; i<Storage.length; i++) { if( Storage[i].getFirstName().equals(get)) { String res[] = ob.userInput(); String firstName = res[0]; String lastName = res[1]; String address = res[2]; String city = res[3]; String state = res[4]; String zip = res[5]; String phoneNumber = res[6]; int uid = i; Storage[i] = new contactPersonNew(firstName, lastName, address, city, state, zip, phoneNumber, uid); System.out.println(" "); } // Storage[i].display(); // System.out.println(" "); } for(int i = 0; i<Storage.length; i++) { if( Storage[i].getFirstName().equals(get)) { ob.removeElement(Storage,i); } } } }
/* * 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 randomnumbergenerator; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * * @author blaszczyk */ public class Buffer { private int[] buffer = new int[5000]; private int position = 0; Lock lock = new ReentrantLock(); Condition writeCondition = lock.newCondition(); Condition readCondition = lock.newCondition(); public void AddToBuffer(int number) { lock.lock(); try { while(position == 5000) { System.out.println("Oczekuje na zwolnienie bufora"); writeCondition.await(); } buffer[position++] = number; if(position == 5000) { readCondition.signal(); } } catch(Exception e) { System.out.println(e.getLocalizedMessage()); } finally { lock.unlock(); } } public int[] ReturnFromBuffer() { lock.lock(); try { while(position < 5000) { System.out.println("Oczekuje na zapełnienie bufora"); readCondition.await(); } int[] b = buffer; buffer = new int[5000]; position = 0; System.out.println("Bufor wyczyszczony"); writeCondition.signalAll(); return b; } catch(Exception e) { System.out.println(e.getLocalizedMessage()); return null; } finally { lock.unlock(); } } }
package me.basiqueevangelist.datapackify.mixins; import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.village.TradeOffer; import net.minecraft.village.TradeOffers; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import java.util.Random; @Mixin(TradeOffers.SellItemFactory.class) public class SellItemFactoryMixin { @Shadow @Final private ItemStack sell; @Shadow @Final private int count; @Shadow @Final private int price; @Shadow @Final private int maxUses; @Shadow @Final private int experience; @Shadow @Final private float multiplier; /** * @reason Gave up trying to do this with Redirect. * @author BasiqueEvangelist */ @Overwrite public TradeOffer create(Entity e, Random r) { ItemStack newIs = this.sell.copy(); newIs.setCount(this.count * newIs.getCount()); return new TradeOffer(new ItemStack(Items.EMERALD, price), newIs, maxUses, experience, multiplier); } }
package com.github.viniciusfcf; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Table; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import io.quarkus.hibernate.orm.panache.PanacheEntity; @Entity @Table(name = "PRODUTO") public class Produto extends PanacheEntity { public String nome; public String descricao; public BigDecimal valor; @CreationTimestamp public Date dataCriacao; @UpdateTimestamp public Date dataAtualizacao; }
package com.pdd.pop.sdk.http.api.request; import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty; import com.pdd.pop.sdk.http.api.response.PddAdDeleteBidResponse; import com.pdd.pop.sdk.http.HttpMethod; import com.pdd.pop.sdk.http.PopBaseHttpRequest; import com.pdd.pop.sdk.common.util.JsonUtil; import java.util.Map; import java.util.TreeMap; public class PddAdDeleteBidRequest extends PopBaseHttpRequest<PddAdDeleteBidResponse>{ /** * 推广类型 2-展示推广 */ @JsonProperty("scene_type") private Integer sceneType; /** * 单元ID */ @JsonProperty("unit_id") private Long unitId; /** * 定向ID,不能删除全体人群定向。 List<Long>的json string。示例[111,222,333] */ @JsonProperty("bid_ids") private String bidIds; @Override public String getVersion() { return "V1"; } @Override public String getDataType() { return "JSON"; } @Override public String getType() { return "pdd.ad.delete.bid"; } @Override public HttpMethod getHttpMethod() { return HttpMethod.POST; } @Override public Class<PddAdDeleteBidResponse> getResponseClass() { return PddAdDeleteBidResponse.class; } @Override public Map<String, String> getParamsMap() { Map<String, String> paramsMap = new TreeMap<String, String>(); paramsMap.put("version", getVersion()); paramsMap.put("data_type", getDataType()); paramsMap.put("type", getType()); paramsMap.put("timestamp", getTimestamp().toString()); if(sceneType != null) { paramsMap.put("scene_type", sceneType.toString()); } if(unitId != null) { paramsMap.put("unit_id", unitId.toString()); } if(bidIds != null) { paramsMap.put("bid_ids", bidIds.toString()); } return paramsMap; } public void setSceneType(Integer sceneType) { this.sceneType = sceneType; } public void setUnitId(Long unitId) { this.unitId = unitId; } public void setBidIds(String bidIds) { this.bidIds = bidIds; } }
package com.vitaltech.bioink; import java.util.Random; public class DataSimulatorDP { private DataProcess dp; public DataSimulatorDP(DataProcess dp){ this.dp = dp; } public void run(){ try { //rangeOverview(500, 40, true); //randomRange(1000); randomRangeFast(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void randomRangeFast(int interval) throws InterruptedException{ float hr1 = 100; float re1 = 15; float rr1 = 600; float hr2 = 100; float re2 = 15; float rr2 = 600; float hr3 = 100; float re3 = 15; float rr3 = 600; float hr4 = 100; float re4 = 15; float rr4 = 600; float count = 0; float sign = 1; float sec_interval = 250 / interval; while(true){ Thread.sleep(interval); generateUserF("user1", hr1, re1, sign * rr1); generateUserF("userdos", hr2, re2, sign * rr2); generateUserF("userthree", hr3, re3, sign * rr3); generateUserF("user4", hr4, re4, sign * rr4); count++; if(count > sec_interval){ sign = -1 * sign; count = 0; rr1 = rr1 + randomFloatAdd4(2, 5, 20, 60); rr1 = Math.max(Math.min(rr1, 800), 400); rr2 = rr2 + randomFloatAdd4(2, 5, 20, 60); rr2 = Math.max(Math.min(rr2, 800), 400); rr3 = rr3 + randomFloatAdd4(2, 5, 20, 60); rr3 = Math.max(Math.min(rr3, 800), 400); rr4 = rr4 + randomFloatAdd4(2, 5, 20, 60); rr4 = Math.max(Math.min(rr4, 800), 400); } hr1 = hr1 + randomFloatAdd(2,6); hr1 = Math.max(Math.min(hr1, 180), 40); re1 = re1 + randomFloatAdd(1,3); re1 = Math.max(Math.min(re1, 40), 5); hr2 = hr2 + randomFloatAdd(1,4); hr2 = Math.max(Math.min(hr2, 160), 60); re2 = re2 + randomFloatAdd(1,2); re2 = Math.max(Math.min(re2, 35), 10); hr3 = hr3 + randomFloatAdd(2,6); hr3 = Math.max(Math.min(hr3, 180), 40); re3 = re3 + randomFloatAdd(1,3); re3 = Math.max(Math.min(re3, 40), 5); hr4 = hr4 + randomFloatAdd(2,7); hr4 = Math.max(Math.min(hr4, 190), 30); re4 = re4 + randomFloatAdd(1,3); re4 = Math.max(Math.min(re4, 40), 0); } } public float randomFloatAdd(float a, float b){ Random r = new Random(); float rando = r.nextFloat(); float addition = 0; if(rando < 0.33f) addition = a; else if(rando < 0.66f) addition = -a; else if(rando < 0.825f) addition = b; else addition = -b; return addition; } public float randomFloatAdd4(float a, float b, float c, float d){ Random r = new Random(); float rando = r.nextFloat(); float addition = 0; if(rando < 0.25f) addition = a; else if(rando < 0.5f) addition = -a; else if(rando < 0.625f) addition = b; else if(rando < 0.75f) addition = -b; else if(rando < 0.8125f) addition = c; else if(rando < 0.875f) addition = -c; else if(rando < 0.9375f) addition = d; else addition = -d; return addition; } //randomizes parameters over the entire range of values public void randomRange(int interval) throws InterruptedException{ float rri1 = 600; float rri2 = 600; float rri3 = 600; float rri4 = 600; while(true){ rri1 = generateRandomUser("user1", rri1); Thread.sleep(interval); rri2 = generateRandomUser("user2", rri2); Thread.sleep(interval); rri2 = generateRandomUser("user3", rri3); Thread.sleep(interval); rri2 = generateRandomUser("user4", rri4); Thread.sleep(interval); } } public float generateRandomUser(String uid, float ddd){ Random r = new Random(); float old = ddd; float hr1 = r.nextFloat() * dp.MAX_HR; float rr1 = r.nextFloat() * dp.MAX_RESP; dp.push(uid, BiometricType.HEARTRATE, hr1); dp.push(uid, BiometricType.RESPIRATION, rr1); old = generateRR(old); dp.push(uid, BiometricType.RR, old); old = generateRR(old); dp.push(uid, BiometricType.RR, -old); old = generateRR(old); dp.push(uid, BiometricType.RR, old); old = generateRR(old); dp.push(uid, BiometricType.RR, -old); return old; } public void generateUserF(String uid, float hr, float re, float rr){ dp.push(uid, BiometricType.HEARTRATE, hr); dp.push(uid, BiometricType.RESPIRATION, re); dp.push(uid, BiometricType.RR, rr); } public static float generateRR(float old){ Random r = new Random(); float rando = r.nextFloat(); float neeu = 0; if(rando < 0.125f){ neeu = 2f; }else if(rando < 0.25f){ neeu = 4f; }else if(rando < 0.375f){ neeu = -8f; }else if(rando < 0.50f){ neeu = -4f; }else if(rando < 0.625f){ neeu = -2f; }else if(rando < 0.75f){ neeu = 8f; }else if(rando < 0.825f){ neeu = -64f; }else if(rando < 0.8125f){ neeu = -32f; }else if(rando < 0.8375f){ neeu = 32f; }else{ neeu = 64f; } neeu = old + neeu; neeu = Math.max(Math.min(neeu, 800), 400); return neeu; } public void rangeOverview(int interval, int steps, boolean axis) throws InterruptedException{ float hr1 = 0; float rr1 = 0; float hr2 = 0; float rr2 = 0; float hr3 = 0; float rr3 = 0; float hr4 = 0; float rr4 = 0; float hv1 = 0; float hv2 = 0; float hv3 = 0; float hv4 = 0; Thread.sleep(1000); while(true){ for(int i = 0; i <= steps; i++){ hr1 = i * dp.MAX_HR / steps; hr4 = hr3 = hr2 = hr1; rr1 = 0 * dp.MAX_RESP / 3; rr2 = 1 * dp.MAX_RESP / 3; rr3 = 2 * dp.MAX_RESP / 3; rr4 = 3 * dp.MAX_RESP / 3; hv1 = dp.MAX_HRV / 2; hv4 = hv3 = hv2 = hv1; dp.push("user1", BiometricType.HEARTRATE, hr1); dp.push("user1", BiometricType.RESPIRATION, rr1); dp.push("user2", BiometricType.HEARTRATE, hr2); dp.push("user2", BiometricType.RESPIRATION, rr2); dp.push("user3", BiometricType.HEARTRATE, hr3); dp.push("user3", BiometricType.RESPIRATION, rr3); dp.push("user4", BiometricType.HEARTRATE, hr4); dp.push("user4", BiometricType.RESPIRATION, rr4); if(axis){ dp.push("user1", BiometricType.HRV, hv1); dp.push("user2", BiometricType.HRV, hv2); dp.push("user3", BiometricType.HRV, hv3); dp.push("user4", BiometricType.HRV, hv4); } Thread.sleep(interval); } Thread.sleep(2 * interval); for(int i = 0; i <= steps; i++){ hr1 = 0 * dp.MAX_HR / 3; hr2 = 1 * dp.MAX_HR / 3; hr3 = 2 * dp.MAX_HR / 3; hr4 = 3 * dp.MAX_HR / 3; rr1 = i * dp.MAX_RESP / steps; rr4 = rr3 = rr2 = rr1; hv1 = dp.MAX_HRV / 2; hv4 = hv3 = hv2 = hv1; dp.push("user1", BiometricType.HEARTRATE, hr1); dp.push("user1", BiometricType.RESPIRATION, rr1); dp.push("user2", BiometricType.HEARTRATE, hr2); dp.push("user2", BiometricType.RESPIRATION, rr2); dp.push("user3", BiometricType.HEARTRATE, hr3); dp.push("user3", BiometricType.RESPIRATION, rr3); dp.push("user4", BiometricType.HEARTRATE, hr4); dp.push("user4", BiometricType.RESPIRATION, rr4); if(axis){ dp.push("user1", BiometricType.HRV, hv1); dp.push("user2", BiometricType.HRV, hv2); dp.push("user3", BiometricType.HRV, hv3); dp.push("user4", BiometricType.HRV, hv4); } Thread.sleep(interval); } Thread.sleep(2 * interval); for(int i = 0; i <= steps; i++){ hv1 = i * dp.MAX_HR / steps; hv4 = hv3 = hv2 = hv1; rr1 = 0 * dp.MAX_RESP / 3; rr2 = 1 * dp.MAX_RESP / 3; rr3 = 2 * dp.MAX_RESP / 3; rr4 = 3 * dp.MAX_RESP / 3; hr1 = dp.MAX_HRV / 2; hr4 = hr3 = hr2 = hr1; dp.push("user1", BiometricType.HEARTRATE, hr1); dp.push("user1", BiometricType.RESPIRATION, rr1); dp.push("user2", BiometricType.HEARTRATE, hr2); dp.push("user2", BiometricType.RESPIRATION, rr2); dp.push("user3", BiometricType.HEARTRATE, hr3); dp.push("user3", BiometricType.RESPIRATION, rr3); dp.push("user4", BiometricType.HEARTRATE, hr4); dp.push("user4", BiometricType.RESPIRATION, rr4); if(axis){ dp.push("user1", BiometricType.HRV, hv1); dp.push("user2", BiometricType.HRV, hv2); dp.push("user3", BiometricType.HRV, hv3); dp.push("user4", BiometricType.HRV, hv4); } Thread.sleep(interval); } } } }
/* * 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 PPI.Controladores; import PPI.Modelos.ModeloSesion; import PPI.Modelos.ModeloUsuario; import PPI.Utils.Archivo; import PPI.Utils.Sesion; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * * @author Personal */ public class ControladorIniciarSesion { public File archivo; Gson gson; Archivo utilArchivo = new Archivo(); public ControladorIniciarSesion(){ archivo = new File("usuario.txt"); gson = new Gson(); } public boolean iniciarSesion (ModeloUsuario usuario){ String informacionDelArchivo = utilArchivo.obtenerInformacionArchivo(archivo); List<ModeloUsuario> listFromGson = new ArrayList<ModeloUsuario>(); if (informacionDelArchivo != null) { Type userListType = new TypeToken<List<ModeloUsuario>>() { }.getType(); listFromGson = gson.fromJson(informacionDelArchivo, userListType); } if (listFromGson.size()!= 0) { for (int i = 0; i < listFromGson.size(); i++) { if (listFromGson.get(i).getCorreo().equals(usuario.getCorreo()) && listFromGson.get(i).getContrasena().equals(usuario.getContrasena())) { ModeloSesion sesion = new ModeloSesion(); sesion.setCorreo(listFromGson.get(i).getCorreo()); sesion.setNick(listFromGson.get(i).getNick()); sesion.setIdUsuario(listFromGson.get(i).getIdUsuario()); sesion.settipoUsuario(listFromGson.get(i).getTipoUsuario()); sesion.setSesionActiva(true); Sesion actualizar = new Sesion(); actualizar.ActualizarSesion(sesion); return true; } } return false; } return false; } }
/* * CLASSE : Impressao * Função : Gerenciar tudo relacionado a impressão de cupom/relatórios. */ package scp.models; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.List; import scp.persistence.AcoesSQL; import scp.utils.BrowserLaunch; public class Impressao { private static final String PATH_TXT = new File("").getAbsolutePath() + "\\print\\etiqueta.txt"; private static final String PATH_HTML = new File("").getAbsolutePath() + "\\print\\PRINT.HTML"; private static final String PATH_HTML_REPORT = new File("").getAbsolutePath() + "\\print\\report.html"; private static final String FONTE = Propriedades.getFonte(); private static final String[] substituir = new String[]{"$NOMEEMPRESA","$ENDERECOEMPRESA","$TELEMPRESA","$ID", "$PECA", "$DESCRICAO", "$QTDAMOSTRAS", "$PMP", "$DATA", "$HORA", "$PESO", "$PCONTADAS"}; public static void gerarHtml(){ try { AcoesSQL acao = new AcoesSQL(); RegistroContagem reg = acao.getUltimoRegistro(); //ARQUIVO DE LEITURA BufferedReader buffRead = new BufferedReader(new InputStreamReader(new FileInputStream(PATH_TXT), StandardCharsets.ISO_8859_1)); String linha = ""; //ARQUIVO DE ESCRITA OutputStreamWriter buffWrite = new OutputStreamWriter(new FileOutputStream(PATH_HTML), StandardCharsets.UTF_8); buffWrite.write(""); buffWrite.append("<!DOCTYPE html><html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head><body><pre style='font-size:"+FONTE+"px'><center>"); while (true) { if (linha != null) { for (String str : substituir) { //VERIFICA SE A LINHA TEM A VARIAVEL DE SUBSTITUIÇÃO E COLOCA UM VALOR NO LOCAL if (linha.contains(str)) { linha = colocarValores(linha, str, reg); } } buffWrite.append(linha + "<br>"); } else { break; } linha = buffRead.readLine(); } for(int i = 1; i <= Integer.parseInt(Propriedades.getAltura()); i++){ buffWrite.append("&nbsp"+"<br>"); } buffWrite.append("</pre><script>print()</script></body></html>"); buffRead.close(); buffWrite.close(); BrowserLaunch.openURL(PATH_HTML); } catch (IOException iEx) { System.out.println(iEx.getMessage()); } } public static void recriarHtml(int id){ try { AcoesSQL acao = new AcoesSQL(); RegistroContagem reg = acao.getRegistro(id); //ARQUIVO DE LEITURA BufferedReader buffRead = new BufferedReader(new InputStreamReader(new FileInputStream(PATH_TXT), StandardCharsets.ISO_8859_1)); String linha = ""; //ARQUIVO DE ESCRITA OutputStreamWriter buffWrite = new OutputStreamWriter(new FileOutputStream(PATH_HTML), StandardCharsets.UTF_8); buffWrite.write(""); buffWrite.append("<!DOCTYPE html><html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head><body><pre style='font-size:"+FONTE+"px'><center>"); while (true) { if (linha != null) { for (String str : substituir) { //VERIFICA SE A LINHA TEM A VARIAVEL DE SUBSTITUIÇÃO E COLOCA UM VALOR NO LOCAL if (linha.contains(str)) { linha = colocarValores(linha, str, reg); } } buffWrite.append(linha + "<br>"); } else { break; } linha = buffRead.readLine(); } for(int i = 1; i <= Integer.parseInt(Propriedades.getAltura()); i++){ buffWrite.append("&nbsp"+"<br>"); } buffWrite.append("</pre><script>print()</script></body></html>"); buffRead.close(); buffWrite.close(); BrowserLaunch.openURL(PATH_HTML); } catch (IOException iEx) { System.out.println(iEx.getMessage()); } } public static void fazerEtiquetaHtml(int id) { //FAZER O ETIQUETA/CUPOM EM HTML PARA IMPRESSÃO try { AcoesSQL acao = new AcoesSQL(); RegistroContagem reg = acao.getRegistro(id); //ARQUIVO DE LEITURA BufferedReader buffRead = new BufferedReader(new InputStreamReader(new FileInputStream(PATH_TXT), StandardCharsets.ISO_8859_1)); String linha = ""; //ARQUIVO DE ESCRITA OutputStreamWriter buffWrite = new OutputStreamWriter(new FileOutputStream(PATH_HTML), StandardCharsets.UTF_8); buffWrite.write(""); buffWrite.append("<!DOCTYPE html><html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head><body><pre style='font-size:"+FONTE+"px'><center>"); while (true) { if (linha != null) { for (String str : substituir) { //VERIFICA SE A LINHA TEM A VARIAVEL DE SUBSTITUIÇÃO E COLOCA UM VALOR NO LOCAL if (linha.contains(str)) { linha = colocarValores(linha, str, reg); } } buffWrite.append(linha + "<br>"); } else { break; } linha = buffRead.readLine(); } for(int i = 1; i <= Integer.parseInt(Propriedades.getAltura()); i++){ buffWrite.append("&nbsp"+"<br>"); } buffWrite.append("</pre><script>print()</script></body></html>"); buffRead.close(); buffWrite.close(); BrowserLaunch.openURL(PATH_HTML); } catch (IOException iEx) { System.out.println(iEx.getMessage()); } } //LISTA OS RELATÓRIOS DO BANCO DE DADOS DE UM PERIODO EM UM ARQUIVO HTML public static void fazerRelatorioHtml(List<RegistroContagem> registros, LocalDate inicio, LocalDate fim) { try { String data_ini = inicio.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)); String data_fim = fim.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)); String linha = ""; //ARQUIVO PARA ESCRITA OutputStreamWriter buffWrite = new OutputStreamWriter(new FileOutputStream(PATH_HTML_REPORT), StandardCharsets.UTF_8); buffWrite.write(""); buffWrite.append("<!DOCTYPE html><html>\n" + "<head>" + "<style type=\"text/css\">" + "@media print {br.pb {page-break-after:always}}" + "body {font-family:verdana; font-size: 9px}" + "th {font-family:verdana; font-size: 10px; text-align: left}" + "td {font-family:verdana; font-size: 9px}" + "</style>" + "</head>" + "<body> <table>" + "<tr><td style=\"font-size: 12px\">REGISTROS DE CONTAGEM</td></tr>" + "</table>" + "<br><table width=\"100%\">" + "<tr><th>ID</th><th>PECA</th><th>DESCRICAO</th><th>QTD.AMOSTRAS</th><th>PMP</th><th>DATA</th><th>HORA</th><th>PESO</th><th>PECAS CONTADAS</th></tr>"); for (RegistroContagem reg : registros) { //A CADA REGISTRO ENCONTRADO buffWrite.append("<tr><td>" + reg.getId() + "</td><td>" + reg.getNome_peca() + "</td><td>" + reg.getDesc_peca() + "</td><td>" + reg.getQtd_amostras() + "</td><td>" + reg.getPmp() + "</td><td>" + reg.getData() + "</td><td>" + reg.getHora() + "</td><td>" + reg.getPeso() + reg.getGrandeza() + "</td><td>" + reg.getPecas_contadas() + "</td></tr>"); } buffWrite.append("</table></body></html>"); buffWrite.close(); BrowserLaunch.openURL(PATH_HTML_REPORT); } catch (IOException ex){ System.out.println(ex.getMessage()); } } //TROCA OS VALORES DOS CAMPOS SUBSTITUIVEIS PELOS DADOS DO REGISTRO public static String colocarValores(String linha, String var, RegistroContagem reg) { switch (var) { case "$NOMEEMPRESA": linha = linha.replace(var, Propriedades.getNomeempresa()); break; case "$ENDERECOEMPRESA": linha = linha.replace(var, Propriedades.getEnderecoempresa()); break; case "$TELEMPRESA": linha = linha.replace(var, Propriedades.getTelempresa()); break; case "$ID": linha = linha.replace(var, Integer.toString(reg.getId())); break; case "$PECA": linha = linha.replace(var, reg.getNome_peca()); break; case "$DESCRICAO": linha = linha.replace(var, reg.getDesc_peca()); break; case "$QTDAMOSTRAS": linha = linha.replace(var, reg.getQtd_amostras()); break; case "$PMP": linha = linha.replace(var, reg.getPmp()+reg.getGrandeza()); break; case "$DATA": linha = linha.replace(var, reg.getData()); break; case "$HORA": linha = linha.replace(var, reg.getHora()); break; case "$PESO": linha = linha.replace(var, reg.getPeso()+reg.getGrandeza()); break; case "$PCONTADAS": linha = linha.replace(var, reg.getPecas_contadas()); break; } return linha; } //GETTERS public static String getPath_txt() { return PATH_TXT; } public static String getPath_html() { return PATH_HTML; } public static String getPath_html_report() { return PATH_HTML_REPORT; } }
package pm9.trackingserver.dao.impl; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import pm9.trackingserver.dao.BaseDao; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import java.util.List; /** * Implementation of BaseDao. It provides common methods to interact with the MySQL database. * There is currently no need for this. We are using CRUDRepository to perform database operations, * and not this class. */ @Primary @Repository public class BaseDaoImpl implements BaseDao { @Autowired EntityManager entityManager; private final Logger logger = LoggerFactory.getLogger(getClass()); @Transactional @Override public Session getSession() { return entityManager.unwrap(Session.class); } @Override @Transactional public Object save(Object entity) { Session session = getSession(); Object updatedEntity = null; try { updatedEntity = session.merge(entity); session.flush(); } catch (Exception exception) { logger.error("exception occurred in BaseDao save ",exception); } return updatedEntity; } @Override @Transactional public void saveOrUpdate(Object entity) { getSession().saveOrUpdate(entity); } @Override @Transactional public void delete(Object object){ Session session = getSession(); session.delete(object); //session.flush(); //session.clear(); } @Override @Transactional public <T> List<T> getAll(Class<T> class_){ Session session = getSession(); CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaQuery<T> criteria = builder.createQuery(class_); criteria.from(class_); List<T> list = session.createQuery(criteria).getResultList(); return list; } }
package csmen.group.project.dao; import csmen.group.project.entity.AdminInfo; import java.util.List; public interface AdminDao { List<AdminInfo> findAll(); List<AdminInfo> findByname(String name); AdminInfo login(AdminInfo admin); int addAdmin(AdminInfo admin); int delAdmin(Integer id); AdminInfo findByid(Integer id); int updateAdmin(AdminInfo admin); }
package com.fbse.recommentmobilesystem.XZHL0220; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.fbse.recommentmobilesystem.R; import com.fbse.recommentmobilesystem.XZHL0210.XZHL0210_Constants; import com.fbse.recommentmobilesystem.XZHL0210.XZHL0210_Utils; import android.annotation.SuppressLint; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; /** * 自定义填空题ListView的Adapter * * @author F0717 * */ public class XZHL0220_ListItemBlankAdapter extends BaseAdapter { class ViewHolder { private EditText et; } LayoutInflater inflater; List<String> options; int Itemposition; int index; Context context; CharSequence temp; // 重写构造器初始化参数 public XZHL0220_ListItemBlankAdapter(Context context, List<String> options, ListView listView, int position, int index) { this.inflater = LayoutInflater.from(context); setOptions(options); this.Itemposition = position; this.index = index; this.context = context; } @Override public int getCount() { return 1; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } // 轮询Item条目给相应的控件附上数据 @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = inflater.inflate(R.layout.xzhl0220_blank, null); holder = new ViewHolder(); holder.et = (EditText) convertView.findViewById(R.id.et_edittext_0220); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // 遍历保存数据的Map集合,找到当前填空题所对应的数据并赋值 if (XZHL0220_MapData.datas.get(index).containsKey(Itemposition)) { HashMap<Integer, String> blankInfo = XZHL0220_MapData.datas.get(index).get(Itemposition); holder.et.setText(blankInfo.get(0)); } final EditText et = holder.et; // 给当前编辑框注册监听器 holder.et.addTextChangedListener(new TextWatcher() { @SuppressLint("UseSparseArrays") // 重写在text改变后的事件方法 @Override public void afterTextChanged(Editable s) { if (temp.length() > 30) { XZHL0210_Utils.showToast2(context, XZHL0210_Constants.YICHAOCHANG, Toast.LENGTH_SHORT); int length = et.getText().length(); s.delete(30, length); et.setText(s); et.setSelection(et.getText().length()); } String str = et.getText().toString(); HashMap<Integer, String> blankInfo = new HashMap<Integer, String>(); blankInfo.put(position, str); XZHL0220_MapData.datas.get(index).put(Itemposition, blankInfo); XZHL0220_MapData.answers.put(index * 5 + Itemposition, str); Log.v("test", XZHL0220_MapData.datas.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } // 重写当Text正在编辑时的事件方法 @Override public void onTextChanged(CharSequence s, int start, int before, int count) { temp = s; } }); return convertView; } public void setOptions(List<String> options) { if (options != null) { this.options = options; } else { this.options = new ArrayList<String>(); } } }
package com.example.root.rahul; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Surface; import android.view.SurfaceView; import android.widget.Toast; import org.opencv.android.CameraBridgeViewBase; import org.opencv.android.JavaCameraView; import org.opencv.android.OpenCVLoader; import org.opencv.core.Mat; public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 { CameraBridgeViewBase cameraBridgeViewBase; Mat mat1,mat2,mat3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cameraBridgeViewBase =(JavaCameraView)findViewById(R.id.myCameraView); cameraBridgeViewBase.setVisibility(SurfaceView.VISIBLE); cameraBridgeViewBase.setCvCameraViewListener(this); } @Override public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) { mat1=inputFrame.rgba(); return mat1; } @Override public void onCameraViewStopped() { mat1.release(); mat2.release(); mat3.release(); } @Override public void onCameraViewStarted(int width, int height) { mat1 =new Mat(width,height,cvType.cv_8UC4); mat1 =new Mat(width,height,cvType.cv_8UC4); mat1 =new Mat(width,height,cvType.cv_8UC4); } @Override protected void onPause() { super.onPause(); if(cameraBridgeViewBase!=null){ cameraBridgeViewBase.disableView(); } } @Override protected void onResume() { super.onResume(); if(OpenCVLoader.initDebug()){ Toast.makeText(getApplicationContext(),"there is problem",Toast.LENGTH_SHORT).show(); } } @Override protected void onDestroy() { super.onDestroy(); if(cameraBridgeViewBase!=null){ cameraBridgeViewBase.disableView(); } } }
package com.github.olly.workshop.imageholder; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; import org.springframework.cloud.openfeign.FeignAutoConfiguration; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @DataMongoTest @Import({ MetricsAutoConfiguration.class, CompositeMeterRegistryAutoConfiguration.class }) @ImportAutoConfiguration({ FeignAutoConfiguration.class }) public class ImageholderApplicationTests { @Test public void contextLoads() { } }
package com.runner; import org.junit.runner.RunWith; import io.cucumber.junit.CucumberOptions; import net.serenitybdd.cucumber.CucumberWithSerenity; @RunWith(CucumberWithSerenity.class) @CucumberOptions(features="src/test/resources/features", glue="com.stepDefinition") public class CucumberTestSuite { }
package com.union.express.web.privilege.jpa.dao; import com.union.express.web.privilege.model.Privilege; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; /** * Created by wq on 2016/9/18. */ public interface IPrivilegeRepository extends PagingAndSortingRepository<Privilege,String> { @Query("from Privilege p where p.weekDay = :weekDay") public Privilege getPrivilegeByWeekDay(@Param("weekDay") String weekDay); // Privilege findByWeekDay(@Param("weekDay") Date weekDay); }
package plats; import std.Transition; import std.TransitionEventListener; @SuppressWarnings("serial") public class Transport extends Transition<Ant> { private int cost = 0; public Transport() { super(); this.addTransitionEventListener(new TransitionEventListener<Ant>() { public void onTransit(Ant s) { doTransit(s); } public boolean isElegible(Ant s) { return s.getSelectedTransport() == Transport.this; } }); } protected void doTransit(Ant s) { s.addCost(cost); } public int getCost() { return cost; } public void setCost(int cost) { this.cost = cost; } }
package com.alevohin.demo; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.math.BigDecimal; @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class CalculatorResult { @JsonProperty("value") private BigDecimal value; @JsonProperty("error") private String error; private CalculatorResult() { } private CalculatorResult(final BigDecimal value, final String error) { this.value = value; this.error = error; } public BigDecimal getValue() { return value; } public String getError() { return error; } public static CalculatorResult of(BigDecimal value) { return new CalculatorResult(value.stripTrailingZeros(), null); } public static CalculatorResult error(String message) { return new CalculatorResult(null, message); } }
package my.yrzy.business.model; import com.google.common.base.Objects; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * Created by yangzefeng on 14/12/2 */ @Data public class Business implements Serializable { private static final long serialVersionUID = 4490869091615832608L; private Long id; private String name; //生意名称 private Long shopId; //店铺id private String shopName; //店铺名称 private String userName; //商家名称 private Long userId; //发布生意的商家id private String discountInfo; //生意信息(json) private Integer status; //生意的状态 private String mainImage; //描述图片 private Date createdAt; private Date updatedAt; public static enum Status { INIT(0, "未上架"), ON_SHELF(1, "上架"), OFF_SHELF(-1, "下架"), DELETED(-3, "删除"); private int value; private String desc; private Status(int value, String desc) { this.value = value; this.desc = desc; } public int value() { return value; } public static Status from(int number) { for (Status status : Status.values()) { if (Objects.equal(status.value, number)) { return status; } } return null; } @Override public String toString() { return desc; } } }
import javax.swing.*; import javax.swing.Timer; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class Panel extends JPanel { private JFrame jFrame; private Button startButton; private Timer paintTimer; private Timer gameTimer; private ConcurrentHashMap<Location, Cell> grid = new ConcurrentHashMap<>(); private int cellSize; private int numCells; private int numRows; private int numCols; private int width; private int height; private Queue<Cell> setAlive = new LinkedList<Cell>(); private Queue<Cell> setDead = new LinkedList<Cell>(); public Panel() { setCellSize(20); setWidth(1280); setHeight(700); //JPanel setPreferredSize(new Dimension(getWidth(), getHeight())); setVisible(true); setBackground(Color.WHITE); //Button startButton = new Button("start"); startButton.setBounds(0, 700, 100, 20); startButton.addActionListener(e -> { if (!gameTimer.isRunning()) { gameTimer.start(); startButton.setLabel("stop"); } else { gameTimer.stop(); startButton.setLabel("start"); } }); //JFrame jFrame = new JFrame("Grid"); jFrame.add(this); jFrame.pack(); jFrame.setLayout(null); jFrame.setSize(new Dimension(1280, 750)); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.setLocationRelativeTo(null); jFrame.setVisible(true); jFrame.setResizable(false); jFrame.add(startButton); addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { clicked(coordinateToLocation(e.getX(), e.getY())); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); setPaintTimer(new Timer(100, e -> { if (e.getSource() == getPaintTimer()) { repaint(); } })); setGameTimer(new Timer(500, e -> { update(); })); paintTimer.start(); fillCells(); } private void fillCells() { for (int r = 0; r < getNumRows(); r++) { for (int c = 0; c < getNumCols(); c++) { grid.put(new Location(r, c), new Cell()); } } } public void clicked(Location loc) { grid.get(loc).setAlive(true); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); drawCells(g); drawGrid(g); } private void update() { for (Location loc : grid.keySet()) { Cell cell = grid.get(loc); int aliveNeighbors = getNumAliveNeighbors(loc); if (cell.isAlive()) { if (aliveNeighbors <= 1) { setDead.add(cell); } if (aliveNeighbors >= 4) { setDead.add(cell); } } else { if (aliveNeighbors == 3) { setAlive.add(cell); } } } for (Cell c : setAlive) { c.setAlive(true); } for (Cell c : setDead) { c.setAlive(false); } setAlive.clear(); setDead.clear(); } public int getNumAliveNeighbors(Location loc) { int numAlive = 0; ArrayList<Cell> neighbors = getNeighbors(loc); for (Cell neighbor : neighbors) { if (neighbor.isAlive()) { numAlive++; } } return numAlive; } public ArrayList<Location> getAliveLocation() { ArrayList<Location> alive = new ArrayList<>(); for (Location loc : grid.keySet()) { if (grid.get(loc).isAlive()) { alive.add(loc); } } return alive; } public ArrayList<Cell> getNeighbors(Location loc) { ArrayList<Cell> neighbors = new ArrayList<>(); int[][] adj = new int[][]{ {-1, 0},//N {-1, 1},//NE {0, 1},//E {1, 1,},//SE {1, 0},//S {1, -1},//SW {0, -1},//W {-1, -1},//NW }; for (int[] dir : adj) { Location newLoc = new Location(loc.getRow() + dir[0], loc.getCol() + dir[1]); if (isValid(newLoc)) { neighbors.add(grid.get(newLoc)); } } return neighbors; } private boolean isValid(Location loc) { if (loc.getRow() >= 0 && loc.getCol() >= 0 && loc.getRow() < getNumRows() && loc.getCol() < getNumCols()) { return true; } return false; // return loc.getRow() < getNumRows() && loc.getRow() > -1 && loc.getCol() < getNumCols() && loc.getCol() > -1; } public void drawCells(Graphics g) { for (Location location : grid.keySet()) { drawCell(location, grid.get(location), g); } } public void drawCell(Location loc, Cell cell, Graphics g) { Color color = Color.DARK_GRAY; if (cell.isAlive()) { color = Color.ORANGE; } g.setColor(color); int x = getCellSize() * loc.getCol(); int y = getCellSize() * loc.getRow(); g.fillRect(0, 0, getCellSize(), getCellSize()); g.fillRect(x, y, getCellSize(), getCellSize()); } public void drawGrid(Graphics g) { g.setColor(Color.BLACK); for (int r = 0; r < getNumRows(); r++) { int x1 = 0; int y1 = r * getCellSize(); int x2 = getWidth(); int y2 = y1; g.drawLine(x1, y1, x2, y2); } for (int c = 0; c < getNumCols(); c++) { int x1 = c * getCellSize(); int y1 = 0; int x2 = x1; int y2 = getHeight(); g.drawLine(x1, y1, x2, y2); } } public Location coordinateToLocation(int x, int y) { int row = y / cellSize; int col = x / cellSize; return new Location(row, col); } //GETTERS AND SETTERS public int getNumRows() { return getHeight() / getCellSize(); } public int getCellSize() { return cellSize; } public int getNumCols() { return getWidth() / getCellSize(); } public int getNumCells() { return getNumRows() * getNumCols(); } @Override public int getWidth() { return width; } @Override public int getHeight() { return height; } public static void main(String[] args) { new Panel(); } public Timer getPaintTimer() { return paintTimer; } public void setPaintTimer(Timer paintTimer) { this.paintTimer = paintTimer; } public void setCellSize(int cellSize) { this.cellSize = cellSize; } public void setNumCells(int numCells) { this.numCells = numCells; } public void setNumRows(int numRows) { this.numRows = numRows; } public void setNumCols(int numCols) { this.numCols = numCols; } public void setWidth(int width) { this.width = width; } public void setHeight(int height) { this.height = height; } public Timer getGameTimer() { return gameTimer; } public void setGameTimer(Timer gameTimer) { this.gameTimer = gameTimer; } }
package PropertiesFile; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Properties_11_04_2018 { static WebDriver driver; public static void main(String[] args) throws IOException, InterruptedException { Properties prop=new Properties(); FileInputStream fis=new FileInputStream("C:\\Users\\guptaav\\Mars_workspace\\SeleniumDemo\\src\\main\\java\\PropertiesFile\\Config_Properties_Data_File_11_04_2018"); prop.load(fis); System.out.println(prop.getProperty("Url")); System.out.println(prop.getProperty("Username")); System.out.println(prop.getProperty("Password")); System.out.println(prop.getProperty("1stbrowser")); System.out.println(prop.getProperty("2 ndbrowser")); System.setProperty("webdriver.chrome.driver", "C:\\Avi Gupta\\Automation\\Automation Software\\chromedriver_win32\\chromedriver.exe"); driver=new ChromeDriver(); driver.manage().window().maximize(); String Url=prop.getProperty("Url"); driver.get(Url); driver.findElement(By.xpath(prop.getProperty("UsernameXpath"))).sendKeys(prop.getProperty("UsernameData")); driver.findElement(By.xpath(prop.getProperty("PasswordXpath"))).sendKeys(prop.getProperty("PasswordData")); driver.findElement(By.xpath(prop.getProperty("LogInButton"))).click(); Thread.sleep(2000); driver.quit(); } }
package com.technicaltest.prices.project; import static org.hamcrest.CoreMatchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import java.text.SimpleDateFormat; import java.util.Date; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.technicaltest.prices.project.business.PricesManager; import com.technicaltest.prices.project.controller.dto.RequestDTO; import com.technicaltest.prices.project.model.Prices; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc class PricesManagerIntegrationTests { @Autowired private MockMvc mockMvc; @Autowired private PricesManager pricesManager; @Test public void checkPriceTest1() throws Exception { Integer brandId = 1; Integer productId = 35455; String dateString = "2020-06-14 10:00:00"; Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateString); RequestDTO request = new RequestDTO(); request.setBrandId(brandId); request.setProductId(productId); request.setDate(date); Prices price1 = pricesManager.getPrice(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); String requestJson=ow.writeValueAsString(request); this.mockMvc.perform(post("/v1/prices/checkPrice").contentType(MediaType.APPLICATION_JSON_VALUE).content(requestJson)).andExpect(jsonPath("$.price", is (price1.getPrice()))); } @Test public void checkPriceTest2() throws Exception { Integer brandId = 1; Integer productId = 35455; String dateString = "2020-06-14 16:00:00"; Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateString); RequestDTO request = new RequestDTO(); request.setBrandId(brandId); request.setProductId(productId); request.setDate(date); Prices price1 = pricesManager.getPrice(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); String requestJson=ow.writeValueAsString(request); this.mockMvc.perform(post("/v1/prices/checkPrice").contentType(MediaType.APPLICATION_JSON_VALUE).content(requestJson)).andExpect(jsonPath("$.price", is (price1.getPrice()))); } @Test public void checkPriceTest3() throws Exception { Integer brandId = 1; Integer productId = 35455; String dateString = "2020-06-14 21:00:00"; Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateString); RequestDTO request = new RequestDTO(); request.setBrandId(brandId); request.setProductId(productId); request.setDate(date); Prices price1 = pricesManager.getPrice(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); String requestJson=ow.writeValueAsString(request); this.mockMvc.perform(post("/v1/prices/checkPrice").contentType(MediaType.APPLICATION_JSON_VALUE).content(requestJson)).andExpect(jsonPath("$.price", is (price1.getPrice()))); } @Test public void checkPriceTest4() throws Exception { Integer brandId = 1; Integer productId = 35455; String dateString = "2020-06-15 10:00:00"; Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateString); RequestDTO request = new RequestDTO(); request.setBrandId(brandId); request.setProductId(productId); request.setDate(date); Prices price1 = pricesManager.getPrice(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); String requestJson=ow.writeValueAsString(request); this.mockMvc.perform(post("/v1/prices/checkPrice").contentType(MediaType.APPLICATION_JSON_VALUE).content(requestJson)).andExpect(jsonPath("$.price", is (price1.getPrice()))); } @Test public void checkPriceTest5() throws Exception { Integer brandId = 1; Integer productId = 35455; String dateString = "2020-06-16 21:00:00"; Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateString); RequestDTO request = new RequestDTO(); request.setBrandId(brandId); request.setProductId(productId); request.setDate(date); Prices price1 = pricesManager.getPrice(request); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); String requestJson=ow.writeValueAsString(request); this.mockMvc.perform(post("/v1/prices/checkPrice").contentType(MediaType.APPLICATION_JSON_VALUE).content(requestJson)).andExpect(jsonPath("$.price", is (price1.getPrice()))); } }
package com.mingrisoft; import java.util.Arrays; public class ArrayExceptionTest { public static void main(String[] args) { int[] array = new int[5]; // 声明一个长度为5的整型数组 Arrays.fill(array, 8); // 将新声明的数组所有元素赋值为8 for (int i = 0; i < 6; i++) {// 遍历输出所有数组元素 System.out.println("array[" + i + "] = " + array[i]); } } }
package cn.itcast.core.controller; import cn.itcast.core.pojo.entity.Sale; import cn.itcast.core.service.SaleService; import com.alibaba.dubbo.config.annotation.Reference; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/Sale") public class SaleController { @Reference private SaleService saleService; @RequestMapping("/getsale") public List<Sale> getsale(){ return saleService.getsale(); } }
package com.kwik.infra.cache.exception; public class KwikCacheException extends RuntimeException { private static final long serialVersionUID = 2683936024168506918L; public KwikCacheException(String message, Throwable e) { super(message, e); } }
package Yandex; import java.io.*; import java.util.*; /* Аркадий реализовал интерактивную систему автодополнения, которая должна позволить ему быстрее набирать тексты университетских работ, в том числе и дипломной. Система запоминает все слова, которые уже есть в тексте. Если Аркадий набирает очередное слово, введенная непустая часть которого совпадает с префиксом ровно одного из уже введенных слов, то после нажатия специальной комбинации клавиш введенную часть можно мгновенно дополнить имеющимся словом. Например, Аркадий уже ввел слова дипломная работа и автодополнение в различных системах. Рассмотрим несколько вариантов очередного слова, которое ему нужно ввести: диплом — после ввода первого символа система предложит принять автодополнение дипломная, но оно не подходит; работа — после ввода первого и второго символа система не будет ничего предлагать, т.к. есть два различных слова в тексте, которые начинаются с текущего префикса, но после ввода третьего символа останется только одно слово (предложенное автодополнение следует принять); различие — вновь вариант с автодополнением появится только после ввода третьего символа, но в этот раз принимать предложенный вариант не следует. У Аркадия не работает клавиша удаления введенных символов, поэтому удалять символы из текста он не может. Аркадий также решил, что не будет использовать автодополнение, если предлагаемое слово является началом набираемого, но не совпадает с ним целиком. Помогите Аркадию определить, сколько раз он воспользуется функцией автодополнения, если хочет максимально уменьшить количество нажатий на клавиши клавиатуры, соответствующие буквенным символам. Формат ввода В первой строке входных данных записано одно целое число n (1 ≤ n ≤ 100 000) — количество слов, которые собирается набрать Аркадий. Во второй строке записаны n слов si (1 ≤ |si| ≤ 1000). Все слова в строке состоят только из строчных букв английского алфавита и разделены одиночными пробелами. Суммарная длина всех слов не превосходит 1 000 000 символов. Формат вывода В единственной строке выведите одно целое число: количество нажатий буквенных клавиш на клавиатуре. Ввод 3 hello world hello Вывод 11 */ public class AutoCompletion { public static abstract class Either<A, B> { static <A, B> Either<A, B> left(A elem) { return new Left<A, B>(elem); } static <A, B> Either<A, B> right(B elem) { return new Right<A, B>(elem); } abstract public A getLeft(); abstract public B getRight(); abstract public boolean isLeft(); abstract public boolean isRight(); static class Left<A, B> extends Either<A, B> { private A elem; Left(A elem) { this.elem = elem; } public A getLeft() { return elem; } public B getRight() { throw new IllegalArgumentException("Either.Right"); } public boolean isLeft() { return true; } public boolean isRight() { return false; } } static class Right<A, B> extends Either<A, B> { private B elem; Right(B elem) { this.elem = elem; } public A getLeft() { throw new IllegalArgumentException("Either.Left"); } public B getRight() { return elem; } public boolean isLeft() { return false; } public boolean isRight() { return true; } } } static class Index { private Map<Character, Either<Index, String>> chars; Index(Map<Character, Either<Index, String>> chars) { this.chars = chars; } static Index empty() { return new Index(new HashMap<>()); } Integer lookupOrUpdate(String word) { if (word.isEmpty()) { return 0; } else { char c = word.charAt(0); String cs = word.substring(1); Either<Index, String> subIdx = chars.get(c); if (subIdx == null) { chars.put(c, Either.right(cs)); return word.length(); } else { if (subIdx.isLeft()) { return 1 + subIdx.getLeft().lookupOrUpdate(cs); } else if (subIdx.isRight() && subIdx.getRight().equals(cs)) { return 1; } else { chars.put(c, Either.left(combineSuffixes(cs, subIdx.getRight()))); return word.length(); } } } } private static Index combineSuffixes(String s1, String s2) { List<Character> commonPfx = commonPrefix(s1, s2); String _s1 = s1.substring(commonPfx.size()); String _s2 = s2.substring(commonPfx.size()); Map<Character, Either<Index, String>> tail = new HashMap<>(); if (!_s1.isEmpty()) tail.put(_s1.charAt(0), Either.right(_s1.substring(1))); if (!_s2.isEmpty()) tail.put(_s2.charAt(0), Either.right(_s2.substring(1))); Index tailIdx = new Index(tail); Collections.reverse(commonPfx); for (char c : commonPfx) { Map<Character, Either<Index, String>> m = new HashMap<>(); m.put(c, Either.left(tailIdx)); tailIdx = new Index(new HashMap<>(m)); } return tailIdx; } private static List<Character> commonPrefix(String s1, String s2) { List<Character> prefix = new ArrayList<>(); int i = 0; while (i < s1.length() && i < s2.length() && s1.charAt(i) == s2.charAt(i)) { prefix.add(s1.charAt(i)); ++i; } return prefix; } } private static Integer enterText(String text, Index index) { String[] words = text.split("\\s"); int sum = 0; for (String w : words) sum += index.lookupOrUpdate(w); return sum; } public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); stdin.readLine(); // пропускаем кол-во слов String text = stdin.readLine(); System.out.println(enterText(text, Index.empty())); } }
package cz.metacentrum.perun.spRegistration.common.models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import cz.metacentrum.perun.spRegistration.common.SpregUtils; import cz.metacentrum.perun.spRegistration.common.configs.AppBeansContainer; import cz.metacentrum.perun.spRegistration.common.enums.AttributeCategory; import cz.metacentrum.perun.spRegistration.common.enums.RequestAction; import cz.metacentrum.perun.spRegistration.common.enums.RequestStatus; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import lombok.ToString; /** * Class represents request made by user. It contains all the data that needs to be stored. * It also keeps track of the modification time. * * @author Dominik Frantisek Bucik <bucik@ics.muni.cz>; */ @Getter @Setter @ToString(exclude = {"attributes", "requester"}) @EqualsAndHashCode(exclude = {"attributes", "requester"}) public class RequestDTO { @NonNull private Long reqId; private Long facilityId; private Long reqUserId; private User requester; private ProvidedService providedService; @NonNull private RequestAction action; @NonNull private RequestStatus status; private Map<AttributeCategory, Map<String, PerunAttribute>> attributes = new HashMap<>(); private Timestamp modifiedAt; private Long modifiedBy; private User modifier; @JsonIgnore public Map<String, String> getFacilityName(String attrName) { return getMultiLanguageAttribute(attrName); } @JsonIgnore public Map<String, String> getFacilityDescription(String attrName) { return getMultiLanguageAttribute(attrName); } private Map<String, String> getMultiLanguageAttribute(String attrName) { if (attributes.containsKey(AttributeCategory.SERVICE)) { Map<String, PerunAttribute> serviceAttrs = attributes.get(AttributeCategory.SERVICE); if (serviceAttrs.containsKey(attrName)) { PerunAttribute attr = serviceAttrs.get(attrName); if (attr != null) { return attr.valueAsMap(); } } } return new HashMap<>(); } /** * Convert attributes to JSON format suitable for storing into DB. * @return JSON with attributes. */ @JsonIgnore public String getAttributesAsJsonForDb(AppBeansContainer appBeansContainer) { if (this.attributes == null || this.attributes.isEmpty()) { return ""; } ObjectNode root = JsonNodeFactory.instance.objectNode(); for (Map.Entry<AttributeCategory, Map<String, PerunAttribute>> categoryMapEntry : attributes.entrySet()) { ObjectNode obj = JsonNodeFactory.instance.objectNode(); AttributeCategory category = categoryMapEntry.getKey(); Map<String, PerunAttribute> attributeMap = categoryMapEntry.getValue(); for (Map.Entry<String, PerunAttribute> a : attributeMap.entrySet()) { PerunAttributeDefinition def = appBeansContainer.getAttrDefinition(a.getKey()); PerunAttribute attribute = a.getValue(); attribute.setDefinition(def); obj.set(a.getKey(), attribute.toJsonForDb()); } root.set(category.toString(), obj); } return root.toString(); } /** * Convert attributes to JSON format suitable for storing into Perun. * @return JSON with attributes or null. */ @JsonIgnore public ArrayNode getAttributesAsJsonArrayForPerun() { if (attributes == null || attributes.isEmpty()) { return null; } ArrayNode res = JsonNodeFactory.instance.arrayNode(); attributes.values().forEach(e -> e.values().forEach(a -> res.add(a.toJson()))); return res; } /** * Extract administrator contact from attributes * @param attrKey name of attribute containing administrator contact * @return Administrator contact */ public String getAdminContact(String attrKey) { if (attributes != null && attributes.containsKey(AttributeCategory.SERVICE) && attributes.get(AttributeCategory.SERVICE).containsKey(attrKey) && attributes.get(AttributeCategory.SERVICE).get(attrKey) != null) { return attributes.get(AttributeCategory.SERVICE).get(attrKey).valueAsString(); } return null; } public void updateAttributes(List<PerunAttribute> attrsToUpdate, boolean clearComment, AppBeansContainer appBeansContainer) { if (attrsToUpdate == null) { return; } if (this.attributes == null) { this.attributes = new HashMap<>(); } for (PerunAttribute attr: attrsToUpdate) { AttributeCategory category = appBeansContainer.getAttrCategory(attr.getFullName()); if (!this.attributes.containsKey(category)) { this.attributes.put(category, new HashMap<>()); } Map<String, PerunAttribute> categoryAttrsMap = this.attributes.get(category); if (categoryAttrsMap.containsKey(attr.getFullName())) { PerunAttribute old = categoryAttrsMap.get(attr.getFullName()); if (old.getDefinition() == null) { old.setDefinition(appBeansContainer .getAttributeDefinitionMap().get(attr.getFullName())); } old.setValue(old.getDefinition().getType(), attr.getValue()); old.setComment(clearComment ? null : attr.getComment()); } else { categoryAttrsMap.put(attr.getFullName(), attr); if (clearComment) { attr.setComment(null); } } } this.attributes = SpregUtils.filterInvalidAttributes(attributes, appBeansContainer.getAttributeDefinitionMap()); } @JsonIgnore public List<String> getAttributeNames() { Set<String> res = new HashSet<>(); if (this.attributes != null && !this.attributes.isEmpty()) { this.attributes.values().forEach( e -> e.values().forEach(a -> res.add(a.getFullName())) ); } return new ArrayList<>(res); } }
package org.point85.domain.plant; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; /** * KeyedObject is the base class for all persistent objects * * @author Kent Randall * */ @MappedSuperclass public abstract class KeyedObject { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long primaryKey; protected KeyedObject() { // nothing to initialize } /** * Get the database record's primary key * * @return Key */ public Long getKey() { return primaryKey; } /** * Set the database record's primary key * * @param key Key */ public void setKey(Long key) { this.primaryKey = key; } }
/** * */ package com.hotel.util; /** * @author User * */ public class IConstants { public static final String AVAILABLE = "Available"; public static final String BOOKED = "Booked"; public static final String CHECKEDOUT = "CheckedOut"; }
// Allen Boynton // JAV1 - 1702 // Member.java package edu.fullsail.aboynton.boyntonallen_ce12.object; public class Member { private int mId; private String mName; private String mParty; public Member() { this.mId = 0; this.mName = mParty = ""; } private Member(int _id) { this(); this.mId = _id; } private Member(int _id, String _name) { this(_id); this.mName = _name; } public Member(int _id, String _name, String _party) { this(_id, _name); this.mParty = _party; } public void setId(int mId) { this.mId = mId; } public int getId() { return mId; } public void setName(String _name) { this.mName = _name; } public String getName() { return mName; } public String getParty() { return mParty; } }
package com.meehoo.biz.core.basic.vo.security; import com.meehoo.biz.core.basic.domain.security.User; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * Created by CZ on 2018/9/5. */ @Getter @Setter @NoArgsConstructor public class UserAdVO { private String id; private String number; // 认证 private String name; private String phone; private String staffId; /** * 蓝牙地址 */ private String blueToothAddress; private String icon = "default"; /** * 所属机构名称 */ private String orgName; private String orgId; /** * 职务 */ private String title; /** * im签名 */ private String imSig; /** * im签名 */ private String userName; /** * 省市区 */ private String location; public UserAdVO(User user) throws Exception { this.id = user.getId(); this.staffId = user.getId(); this.number = user.getCode(); this.name = user.getName(); this.phone =user.getPhone(); this.userName = user.getUserName(); } }
package com.ngocdt.tttn.repository; import com.ngocdt.tttn.entity.DiscountDetail; import com.ngocdt.tttn.entity.DiscountDetailKey; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.Date; import java.util.Optional; public interface DiscountDetailRepository extends JpaRepository<DiscountDetail, DiscountDetailKey> { @Query(value = "select a.discountID, a.discountPercent, a.productID from (select * from DiscountDetail dd " + "where dd.productID = :id) a inner join (select d.discountID from Discount d " + "where d.startTime <= CAST(getdate() as date) and d.endTime >= CAST(getdate() as date)) b " + "on a.discountID = b.discountID", nativeQuery = true) Optional<DiscountDetail> findByProduct(@Param("id") int productID); @Query(value = "select a.discountID, a.discountPercent, a.productID from (select * from DiscountDetail dd " + "where dd.productID = :id) a inner join (select d.discountID from Discount d " + "where d.startTime <= CAST(:startTime as date) and d.endTime >= CAST(:startTime as date)) b " + "on a.discountID = b.discountID", nativeQuery = true) Optional<DiscountDetail> findByProductIDAndTime(@Param("id") int productID, @Param("startTime") Date startTime); }
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int maxPath; public int longestUnivaluePath(TreeNode root) { maxPath = 0; pathLength(root); return maxPath; } public int pathLength(TreeNode node) { if(node == null) return 0; int left = pathLength(node.left); int right = pathLength(node.right); int leftPathLength = 0; int rightPathLength = 0; if(node.left != null && node.left.val == node.val) { leftPathLength = left + 1; } if(node.right != null && node.right.val == node.val) { rightPathLength = right + 1; } maxPath = Math.max(maxPath, (leftPathLength + rightPathLength)); return Math.max(leftPathLength, rightPathLength); } }
/** * */ package com.sirma.itt.javacourse.chat.common.exceptions; /** * Basic chat exception. * * @author siliev * */ public class ChatException extends Exception { private static final long serialVersionUID = -6422086764162437854L; /** * Empty constructor. */ public ChatException() { } /** * Constructor with message and cause. * * @param message * the error message. * @param cause * the cause of the exception. */ public ChatException(String message, Throwable cause) { super(message, cause); } /** * Messaged constructor. * * @param message * the error message. */ public ChatException(String message) { super(message); } /** * Constructor with cause. * * @param cause * the cause of the exception. */ public ChatException(Throwable cause) { super(cause); } }
package com.icss.frame.manage; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Iterator; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import com.icss.dao.DeskDao; import com.icss.mwing.MTable; import com.icss.tool.Validate; /** * 餐桌管理窗体 * @author king * */ public class DeskNumDialog extends JDialog { private JTable table; private JOptionPane pane; private JTextField seatingTextField; private JTextField numTextField; private final Vector columnNameV = new Vector(); private Vector tableValueV ; //表格数据向量 private DefaultTableModel tableModel = new DefaultTableModel(); private JTable openedDeskTable; protected DeskDao dao = new DeskDao(); /** * Launch the application * * @param args */ public static void main(String args[]) { try { DeskNumDialog dialog = new DeskNumDialog(null); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } /** * Create the dialog */ public DeskNumDialog(JTable rightTable) { super(); setModal(true); getContentPane().setLayout(new BorderLayout()); setResizable(false); setTitle("台号管理"); setBounds(100, 100, 500, 375); this.openedDeskTable = rightTable; final JPanel operatePanel = new JPanel(); getContentPane().add(operatePanel, BorderLayout.NORTH); final JLabel numLabel = new JLabel(); operatePanel.add(numLabel); numLabel.setText("台 号:"); numTextField = new JTextField(); numTextField.setColumns(6); operatePanel.add(numTextField); final JLabel seatingLabel = new JLabel(); operatePanel.add(seatingLabel); seatingLabel.setText(" 座位数:"); seatingTextField = new JTextField(); seatingTextField.setColumns(5); operatePanel.add(seatingTextField); final JLabel topPlaceholderLabel = new JLabel(); topPlaceholderLabel.setPreferredSize(new Dimension(20, 40)); operatePanel.add(topPlaceholderLabel); final JButton addButton = new JButton();//创建添加台号按钮对象 addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String numDesk = numTextField.getText().trim(); // 获取台号,并去掉首尾空格 int numNum = Integer.parseInt(numDesk); String seatDesk = seatingTextField.getText().trim(); // 获取座位数,并去掉首尾空格 int seatNum = Integer.parseInt(seatDesk); if(numNum>0&&numDesk.length()<5){ // 查看用户是否输入了台号和座位数 // 查看台号的长度是否超过了5位 if(seatNum>1 && seatNum<99){ // 验证座位数是否在1——99之间 try { Vector<Vector<Object>> allDesk = dao.queryByNum(numNum); System.out.println(allDesk); if(allDesk.size()>0){ pane.showConfirmDialog(null, "该数据已存在","提示框",JOptionPane.DEFAULT_OPTION); }else{ dao.addDesk(numNum, seatNum); numTextField.setText(""); seatingTextField.setText("");//将台号文本框设置为空 ,将座位数文本框设置为空, 将新添加的台号信息保存到数据库中 } } catch (Exception e1) { e1.printStackTrace(); } } } // 获得当前拥有台号的个数 // 创建一个代表新台号的向量 // 添加添加序号 // 添加台号 // 添加座位数 // 将新台号信息添加到表格中 // 设置新添加的台号为选中的 // 关闭数据库连接 } }); addButton.setText("添加"); operatePanel.add(addButton); final JButton delButton = new JButton();//创建删除台号按钮对象 delButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); Object oNum = table.getValueAt(row, 1); // 获得选中的餐台 int oDeskNum = Integer.parseInt(oNum.toString()); Object oSeat = table.getValueAt(row, 2); if(row<=0){ // 未选中任何餐台给友情提示 System.out.println("未选中任何餐台"); }else{ // 查看该餐台是否正在被使用 // 该餐台正在被使用,不能删除,返回 // 组织确认信息 // 弹出确认提示 try { dao.delDesk(oDeskNum); // 确认删除 // 从数据库中删除 // 刷新表格 } catch (Exception e1) { e1.printStackTrace(); } } } }); delButton.setText("删除"); operatePanel.add(delButton); final JScrollPane scrollPane = new JScrollPane(); getContentPane().add(scrollPane); String columnNames[] = new String[] { "序 号", "台 号", "座位数" }; for (int i = 0; i < columnNames.length; i++) { columnNameV.add(columnNames[i]); } try { tableValueV = dao.queryAllDesk(); } catch (Exception e1) { e1.printStackTrace(); } tableModel = new DefaultTableModel(tableValueV, columnNameV); table = new MTable(tableModel); if (table.getRowCount() > 0) table.setRowSelectionInterval(0, 0); scrollPane.setViewportView(table); final JLabel leftPlaceholderLabel = new JLabel(); leftPlaceholderLabel.setPreferredSize(new Dimension(20, 20)); getContentPane().add(leftPlaceholderLabel, BorderLayout.WEST); final JPanel exitPanel = new JPanel(); final FlowLayout flowLayout = new FlowLayout(); flowLayout.setAlignment(FlowLayout.RIGHT); exitPanel.setLayout(flowLayout); getContentPane().add(exitPanel, BorderLayout.SOUTH); final JButton exitButton = new JButton(); exitPanel.add(exitButton); exitButton.setText("退出"); exitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); final JLabel bottomPlaceholderLabel = new JLabel(); bottomPlaceholderLabel.setPreferredSize(new Dimension(10, 40)); exitPanel.add(bottomPlaceholderLabel); final JLabel rightPlaceholderLabel = new JLabel(); rightPlaceholderLabel.setPreferredSize(new Dimension(20, 20)); getContentPane().add(rightPlaceholderLabel, BorderLayout.EAST); // } }
package com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.navigationFragment; public interface ILoadMore { void onLoadMore(); }
package com.dinh.customdate.api; import com.dinh.customdate.model.CategoryModel; import com.dinh.customdate.model.Product; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; public interface APIService { @GET("category/list") Call<List<CategoryModel>> getAllCategory(); @GET("product/list") Call<List<Product>> getAllProduct(); }
package network.warzone.tgm.modules.death; import network.warzone.tgm.match.Match; import network.warzone.tgm.match.MatchModule; import network.warzone.tgm.modules.team.MatchTeam; import network.warzone.tgm.player.event.TGMPlayerDeathEvent; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import static org.bukkit.event.entity.EntityDamageEvent.DamageCause; public class DeathMessageModule extends MatchModule implements Listener { private DeathModule deathModule; public void load(Match match) { deathModule = match.getModule(DeathModule.class); } @EventHandler(priority = EventPriority.HIGHEST) public void onTGMDeath(TGMPlayerDeathEvent event) { DeathInfo deathInfo = deathModule.getPlayer(event.getVictim()); if (deathInfo.playerTeam.isSpectator()) return; //stupid spectators String message; ItemStack weapon = deathInfo.item; DamageCause cause = deathInfo.cause; MatchTeam playerTeam = deathInfo.playerTeam; MatchTeam killerTeam = deathInfo.killerTeam; if (deathInfo.killer != null && deathInfo.killerName != null) { if (cause.equals(DamageCause.FALL)) { if (weapon != null && weapon.getType().equals(Material.BOW)) message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " was shot off a high place by " + killerTeam.getColor() + deathInfo.killerName + ChatColor.GRAY; else message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " was thrown off a high place by " + killerTeam.getColor() + deathInfo.killerName + ChatColor.GRAY + " using " + itemToString(weapon); } else if (cause.equals(DamageCause.VOID)) { if (weapon != null && weapon.getType().equals(Material.BOW)) message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " was shot into the void by " + killerTeam.getColor() + deathInfo.killerName + ChatColor.GRAY; else if (!deathInfo.playerName.equals(deathInfo.killerName)) { message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " was thrown into the void by " + killerTeam.getColor() + deathInfo.killerName + ChatColor.GRAY + " using " + itemToString(weapon); } else { message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " fell into the void"; } } else if (cause.equals(DamageCause.PROJECTILE)) { int distance = ((Double) deathInfo.killerLocation.distance(deathInfo.playerLocation)).intValue(); message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " was shot by " + killerTeam.getColor() + deathInfo.killerName + ChatColor.GRAY + " from " + distance + (distance == 1 ? " block" : " blocks"); } else if (cause.equals(DamageCause.FIRE) || cause.equals(DamageCause.FIRE_TICK)) { if (!deathInfo.playerName.equals(deathInfo.killerName)) { message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " was burned to death by " + killerTeam.getColor() + deathInfo.killerName +ChatColor.GRAY; } else { message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " burned to death"; } } else { if (!deathInfo.playerName.equals(deathInfo.killerName)) { message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " was killed by " + killerTeam.getColor() + deathInfo.killerName + ChatColor.GRAY + " using " + (cause.equals(DamageCause.ENTITY_ATTACK) ? itemToString(weapon) : "the environment"); } else { message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " died to the environment"; } } if (deathInfo.killer != null) deathInfo.killer.playSound(deathInfo.killer.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 3, 1.4f); } else { if (cause.equals(DamageCause.FALL)) { message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " fell from a high place"; } else if (cause.equals(DamageCause.VOID)) { message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " fell into the void"; } else if (cause.equals(DamageCause.FIRE) || cause.equals(DamageCause.FIRE_TICK)) { message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " burned to death"; } else { message = playerTeam.getColor() + deathInfo.playerName + ChatColor.GRAY + " died to the environment"; } } deathInfo.player.getWorld().playSound(deathInfo.playerLocation, Sound.ENTITY_IRON_GOLEM_DEATH, 2, 2); if (message.length() > 0) { broadcastDeathMessage(deathInfo.player, deathInfo.killer, message); deathInfo.killer = null; deathInfo.killerName = null; } } private String itemToString(ItemStack item) { if (item == null || item.getType().equals(Material.AIR)) { return "their hands"; } StringBuilder stringBuilder = new StringBuilder(); if (item.hasItemMeta() && item.getItemMeta().hasEnchants()) stringBuilder.append("Enchanted "); String materialName = item.getType().toString(); for (String word : materialName.split("_")) { word = word.toLowerCase(); word = word.substring(0, 1).toUpperCase() + word.substring(1) + " "; stringBuilder.append(word); } return stringBuilder.toString().trim(); } private void broadcastDeathMessage(Player dead, Player killer, String message) { for (Player player : Bukkit.getOnlinePlayers()) { /* TODO make look better and also fix //bold messages when the player is involved if (dead == player || (killer != null && killer == player)) { message = message.replaceAll(dead.getName() + ChatColor.GRAY, ChatColor.BOLD + dead.getName() + ChatColor.GRAY + ChatColor.BOLD); if (killer != null) { if (message.contains(killer.getName() + ChatColor.GRAY)) { message = message.replaceAll(killer.getName() + ChatColor.GRAY, ChatColor.BOLD + killer.getName() + ChatColor.GRAY + ChatColor.BOLD); } else { message = message.replaceAll(killer.getName(), ChatColor.BOLD + killer.getName()); } } } */ player.getPlayer().sendMessage(message); } } @EventHandler public void onBukkitDeath(org.bukkit.event.entity.PlayerDeathEvent event) { event.setDeathMessage(""); } }
package robustgametools.adapter; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.loopj.android.http.AsyncHttpResponseHandler; import org.apache.http.Header; import java.util.ArrayList; import butterknife.ButterKnife; import butterknife.InjectView; import robustgametools.model.TrophyGuide; import robustgametools.playstation_guide.R; import robustgametools.util.GuideDownloader; import robustgametools.util.Storage; public class TrophyGuideListAdapter extends BaseAdapter { private ArrayList<TrophyGuide> mGuides; private ArrayList<String> mDownloadedGuides; private Context mContext; private LayoutInflater mInflater; private ProgressDialog mDownloadDialog; private GuideDownloader mDownloader; public TrophyGuideListAdapter(Context context, ArrayList<TrophyGuide> guides, ArrayList<String> downloadedGuide) { mContext = context; mGuides = guides; mInflater = LayoutInflater.from(mContext); mDownloadedGuides = downloadedGuide; mDownloader = GuideDownloader.getInstance(mContext); } @Override public int getCount() { return mGuides.size(); } @Override public TrophyGuide getItem(int i) { return mGuides.get(i); } @Override public long getItemId(int i) { return 0; } @Override public View getView(final int position, View view, ViewGroup viewGroup) { final ViewHolder holder; if (view == null) { view = mInflater.inflate(R.layout.list_available_guide, viewGroup, false); holder = new ViewHolder(view); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } holder.guideTitle.setText(mGuides.get(position).getTitle()); if (mDownloadedGuides.contains(mGuides.get(position).getTitle())) { holder.downloadIcon.setImageResource(R.drawable.ic_delete); holder.downloadIcon.setTag(R.drawable.ic_delete); } else { holder.downloadIcon.setImageResource(R.drawable.ic_file_download); holder.downloadIcon.setTag(R.drawable.ic_file_download); } holder.downloadIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int tag = (int) holder.downloadIcon.getTag(); if (tag == R.drawable.ic_file_download) { downloadGuide(position); } else { deleteGuide(mGuides.get(position).getTitle()); Toast.makeText(mContext, "Guide deleted", Toast.LENGTH_LONG).show(); } } }); return view; } private void downloadGuide(final int position) { downloadGuide(mGuides.get(position).getTitle()); mDownloadDialog = new ProgressDialog(mContext); mDownloadDialog.setMessage("Downloading..."); mDownloadDialog.show(); mDownloadDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mDownloadDialog.dismiss(); mDownloader.cancelOngoingDownload(); deleteGuide(mGuides.get(position).getTitle()); } }); } private void deleteGuide(String title) { mDownloadedGuides.remove(title); Storage storage = Storage.getInstance(mContext); storage.deleteGuide(title); notifyDataSetChanged(); } private void downloadGuide(final String title) { mDownloader.downloadGuide(title, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { mDownloadDialog.dismiss(); Toast.makeText(mContext, "Download complete", Toast.LENGTH_LONG).show(); mDownloadedGuides.add(title); notifyDataSetChanged(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { Toast.makeText(mContext, "Error downloading guide. Check your network" + "and try again.", Toast.LENGTH_LONG).show(); mDownloadDialog.dismiss(); } }); } static class ViewHolder { @InjectView(R.id.download) ImageView downloadIcon; @InjectView(R.id.title) TextView guideTitle; public ViewHolder(View view) { ButterKnife.inject(this, view); } } }
package formation.formation.service.rest; import formation.domain.ParamtypeQuestion; import formation.formation.service.itf.ParamtypeQuestionItf; import javax.ejb.EJB; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; /** * Created by victor on 12/12/2015. */ @Path("/paramtypeQuestion") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public class ParamtypeQuestionRestService { @EJB ParamtypeQuestionItf service; @GET public Response get(){ List<ParamtypeQuestion> list = service.getAll(); if(list == null){ throw new NotFoundException("ParamtypeQuestion is not found"); } return Response.ok(list).build(); } }
package ivge; public interface Marker { void mark(); }
package thesis.entity; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; @DataObject(generateConverter = true) public class DummyObject { private String id; private String name; private int hp; private int stamina; private int x, y; public DummyObject(String id, String name, int hp, int stamina, int x, int y) { this.id = id; this.name = name; this.hp = hp; this.stamina = stamina; this.x = x; this.y = y; } public DummyObject(JsonObject o){ DummyObjectConverter.fromJson(o, this); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getStamina() { return stamina; } public void setStamina(int stamina) { this.stamina = stamina; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public JsonObject toJson(){ JsonObject o = new JsonObject(); DummyObjectConverter.toJson(this, o); return o; } }
package lab8; import java.util.ArrayList; import java.util.Scanner; import lab6.SV; public class main { public static void main(String[] args) { Scanner scanner= new Scanner(System.in); NhanVien nv; ArrayList<NhanVien> arr = new ArrayList<>(); for(int i = 0; i < 1; i++) { nv = new NhanVien(); nv.nhap(); arr.add(nv); } for(NhanVien nv1: arr) { nv1.xuat(); } } }
package mx.redts.adendas.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import mx.redts.adendas.dto.UsuarioDTO; import mx.redts.adendas.model.Role; import mx.redts.adendas.model.User; import org.hibernate.Session; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * * User DAO * * @author Andres Cabrera * @since 25 Mar 2012 * @version 1.0.0 * */ // @Repository("userDao") public class UserDAO extends BaseDAO implements IUserDAO { @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addRole(Role rol) { this.getSession().save(rol); } /** * Add User * * * @param User * user */ @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void addUser(User user) { this.getSession().save(user); } /** * Delete User * * @param User * user */ @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void deleteUser(User user) { this.getSession().delete(user); } @SuppressWarnings("unchecked") @Override public List<Role> getRoles() { return (List<Role>) createQuery(Messages.getString("UserDAO.3")); //$NON-NLS-1$ } /** * Get User * * @param int User Id * @return User */ public User getUserById(int id) { List<Integer> param = new ArrayList<Integer>(); param.add(0, id); return (User) createQuery(Messages.getString("UserDAO.4"), param); //$NON-NLS-1$ } /** * Get User List * * @return List - User list */ @SuppressWarnings("unchecked") @Override public List<UsuarioDTO> getUsers() { return (List<UsuarioDTO>) createQueryToBean( Messages.getString("UserDAO.5"), //$NON-NLS-1$ UsuarioDTO.class); } @SuppressWarnings("unchecked") public List<Role> loadRolForUsername(final String username) { System.out.println(Messages.getString("UserDAO.6") + username); //$NON-NLS-1$ Session ses = this.getSession(); List<Role> roles = (List<Role>) ses .createQuery(Messages.getString("UserDAO.7")).setParameter(0, username.trim()).list(); //$NON-NLS-1$ ses.close(); System.out.println(Messages.getString("UserDAO.8") + roles.size()); //$NON-NLS-1$ return roles; } public User loadUserByUsername(final String username) { System.out.println(Messages.getString("UserDAO.9") + username); //$NON-NLS-1$ Session ses = this.getSession(); User user = (User) ses .createQuery(Messages.getString("UserDAO.10")).setParameter(0, username.trim()).uniqueResult(); //$NON-NLS-1$ ses.close(); return user; } public void lockUser(String user) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put(Messages.getString("UserDAO.11"), new Boolean(true)); //$NON-NLS-1$ parametros.put(Messages.getString("UserDAO.12"), user.trim()); //$NON-NLS-1$ System.out .println(Messages.getString("UserDAO.13") + parametros.toString()); //$NON-NLS-1$ createUpdQry(Messages.getString("UserDAO.14"), parametros); //$NON-NLS-1$ } public void updadePassword(String user, String password) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put(Messages.getString("UserDAO.15"), password); //$NON-NLS-1$ parametros.put(Messages.getString("UserDAO.16"), user.trim()); //$NON-NLS-1$ System.out .println(Messages.getString("UserDAO.17") + parametros.toString()); //$NON-NLS-1$ createUpdQry(Messages.getString("UserDAO.18"), parametros); //$NON-NLS-1$ } /** * Update User * * @param User * user */ public void updateUser(UsuarioDTO user) { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put( Messages.getString("UserDAO.19"), (Boolean) user.isBloqueado()); //$NON-NLS-1$ parametros .put(Messages.getString("UserDAO.20"), (Boolean) user.isHabilitado()); //$NON-NLS-1$ parametros.put( Messages.getString("UserDAO.21"), user.getUsuario().trim()); //$NON-NLS-1$ System.out .println(Messages.getString("UserDAO.22") + parametros.toString()); //$NON-NLS-1$ createUpdQry(Messages.getString("UserDAO.23"), parametros); //$NON-NLS-1$ } }
package com.pago.core.quotes.dao.config; import io.dropwizard.db.DataSourceFactory; public interface DaoConfiguration { public DataSourceFactory getDataSourceFactory(); }
package com.crunchshop.util; import com.google.gson.Gson; import java.util.Map; public final class JSON { private static final Gson gson = new Gson(); private JSON() { } public static Object parse(String jsonString, Class classType) { return gson.fromJson(jsonString, classType); } public static Map parse(String jsonString) { return gson.fromJson(jsonString, Map.class); } public static String stringify(Object jsonObject) { return gson.toJson(jsonObject); } }
package a13solutions.androidstudiol2c; import android.app.Activity; import android.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends Activity { private Controller controller; private ViewerFragment viewerFragment; private ButtonFragment buttonFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); instantiateController(); } private void instantiateController() { FragmentManager fm = getFragmentManager(); viewerFragment = (ViewerFragment) fm.findFragmentById(R.id.fragViewer); buttonFragment = (ButtonFragment) fm.findFragmentById(R.id.fragButton); controller = new Controller(viewerFragment, buttonFragment); } }
package serve.serveup.utils.adapters; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import serve.serveup.R; import serve.serveup.dataholder.MealInfo; import serve.serveup.dataholder.RestaurantInfo; import serve.serveup.utils.Utils; import serve.serveup.views.restaurant.PickedMealActivity; public class MealsAdapter extends RecyclerView.Adapter<MealsAdapter.MealsHolder> { private ArrayList<MealInfo> meals; private MealInfo pickedMeal; private RestaurantInfo pickedRestaurant; // Define the View Holder static class MealsHolder extends RecyclerView.ViewHolder { LinearLayout cardMealContainer; TextView cardMealTitle; TextView cardMealDescription; TextView cardMealPrice; MealsHolder(final View itemView) { super(itemView); // Initialize the parameters based on the Card layout names cardMealContainer = itemView.findViewById(R.id.cardMealContainer); cardMealTitle = itemView.findViewById(R.id.mealTitleText); cardMealDescription = itemView.findViewById(R.id.mealDescriptionText); cardMealPrice = itemView.findViewById(R.id.mealPriceText); } } public MealsAdapter(ArrayList<MealInfo> meals, RestaurantInfo pickedRestaurant) { this.meals = meals; this.pickedRestaurant = pickedRestaurant; } @NonNull @Override public MealsHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Find and inflate the appropriate card layout. View cardMeal = LayoutInflater.from(parent.getContext()) .inflate(R.layout.card_meal, parent, false); return new MealsHolder(cardMeal); } @Override public void onBindViewHolder(@NonNull final MealsHolder holder, int position) { MealInfo meal = this.meals.get(position); holder.cardMealTitle.setText(meal.getImeJedi()); holder.cardMealDescription.setText(meal.getOpisJedi()); holder.cardMealPrice.setText(String.valueOf(meal.getCena()) + " €"); holder.cardMealContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { pickedMeal = meals.get(holder.getAdapterPosition()); if (pickedMeal != null) { Intent myIntent = new Intent(view.getContext(), PickedMealActivity.class); myIntent.putExtra("picked_meal", pickedMeal); myIntent.putExtra("picked_restaurant", pickedRestaurant); view.getContext().startActivity(myIntent); //((Activity) view.getContext()).finish(); } else Utils.logInfo("Picked meal doesnt exist"); } }); } @Override public int getItemCount() { return meals.size(); } }
package algorithms.mazeGenerators; import algorithms.maze.Maze3d; /** * @author User * This interface uses us as a general way to create many kinds of generators. * it will create a maze3D according to the implementing class */ public interface Maze3dGenerator { /** * This method measures how long does it take to create a maze3d * @return the time it took in String */ public String measureAlgorithmTime(); /** * This method generates a maze3d * @return a maze according t the class implementing */ public Maze3d generate(); }
package com.blurack.activities; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.StringRequest; import com.blurack.AppController; import com.blurack.R; import com.blurack.constants.Constants; import com.blurack.utils.Preferences; import com.blurack.utils.ToastUtils; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.GraphRequest; import com.facebook.GraphResponse; import com.facebook.Profile; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class MainLoginActivity extends AppCompatActivity implements FacebookCallback<LoginResult> { private CallbackManager callbackManager; private static final String TAG = "LOG_IN: %s"; private static final String TAG_LOG_IN = "LOG_IN"; private View mProgressView; private View mLoginFormView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_login); callbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(callbackManager, this); Button mSignUpButton = (Button) findViewById(R.id.sign_up_button); Button mSignInButton = (Button) findViewById(R.id.sign_in_button); Button mFacebookButton = (Button) findViewById(R.id.sign_in_facebook); mSignUpButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent mainIntent = new Intent(MainLoginActivity.this, SignUpActivity.class); startActivity(mainIntent); } }); mSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent mainIntent = new Intent(MainLoginActivity.this, LoginActivity.class); startActivity(mainIntent); finish(); } }); mFacebookButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { LoginManager.getInstance().logInWithReadPermissions(MainLoginActivity.this, Arrays.asList("public_profile","email")); } }); mLoginFormView = findViewById(R.id.main_login_form); mProgressView = findViewById(R.id.sign_up_progress); } @Override protected void onResume() { super.onResume(); Preferences prefs = Preferences.getInstance(MainLoginActivity.this); String apiKey = prefs.getString(Constants.TAG_API_KEY); if(apiKey!=null){ Intent mainIntent = new Intent(MainLoginActivity.this, HomeActivity.class); startActivity(mainIntent); finish(); } } @Override public void onSuccess(LoginResult loginResult) { Log.d("FBSuccess","Token:"+loginResult.getAccessToken()); requestFBProfileData(loginResult.getAccessToken()); } @Override public void onCancel() { Log.d("FBCancel","Login canceled"); } @Override public void onError(FacebookException error) { Log.d("FBError","Error"+error.getMessage()); } private void requestFBProfileData(final AccessToken accessToken){ showProgress(true); // Facebook Email address GraphRequest request = GraphRequest.newMeRequest( accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted( JSONObject object, GraphResponse response) { try { String FEmail = object.getString("email"); Profile profile = Profile.getCurrentProfile(); if (profile!=null) { Log.e("FNAME",profile.getFirstName()); Log.e("LNAME",profile.getLastName()); HashMap<String, String> params = new HashMap<String, String>(); params.put("first_name", profile.getFirstName()); params.put("last_name", profile.getLastName()); params.put("email", FEmail); params.put("accesstoken", accessToken.getToken()); fbLoginTask(params); } } catch (JSONException e) { showProgress(false); e.printStackTrace(); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name,email,gender, birthday"); request.setParameters(parameters); request.executeAsync(); } /** * Represents an asynchronous login/registration task used to authenticate * the user. */ private void fbLoginTask(final HashMap<String,String > dataToSend){ StringRequest jsonObjReq = new StringRequest(Request.Method.POST, Constants.FB_LOGIN_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, response); try { JSONObject responseObj = new JSONObject(response); if(responseObj.has("type") && "success".equalsIgnoreCase(responseObj.getString("type"))) { Preferences prefs = Preferences.getInstance(MainLoginActivity.this); prefs.setString(Constants.TAG_API_KEY,responseObj.getString("api_key")); prefs.setString(Constants.TAG_USER_DATA,responseObj.get("user").toString()); startActivity(new Intent(MainLoginActivity.this,HomeActivity.class)); finish(); } if(responseObj.has("message")){ ToastUtils.showToast(responseObj.getString("message")); } } catch (JSONException e) { e.printStackTrace(); ToastUtils.showToast(R.string.error_500); } showProgress(false); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); ToastUtils.showToast("Sign In failed please try again"); showProgress(false); } }) { @Override protected Map<String, String> getParams() { return dataToSend; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, TAG_LOG_IN); } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); mLoginFormView.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mProgressView.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } } }
import java.util.*; public class Ch17_09 { private static int maxGain(List<Integer> coins) { return coins.size() != 0 ? maxGainHelper(coins, 0, coins.size() - 1) : 0; } private static int maxGainHelper(List<Integer> coins, int a, int b) { //base cases if (a >= b) { } //iterative cases } public static void main(String []args) { List<Integer> coins = Arrays.asList(1, 5, 10, 20); System.out.println(maxGain(coins)); } }
package com.sam.sec.service; import java.util.ListIterator; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.sam.helper.RepoException; import com.sam.helper.SagaHelper; import com.sam.helper.SamException; import com.sam.helper.TxStatusEnums; import com.sam.mdm.model.Saga; import com.sam.mdm.model.Saga.Step; import com.sam.mdm.service.MDMService; import com.sam.sec.model.StepData; import com.sam.sec.repo.SECRepo; @Service public class SECService { private Logger logger = LogManager.getLogger(SECService.class); private static final ObjectMapper mapper = new ObjectMapper(); static { mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); } @Autowired private MDMService sagaService; @Autowired private SECRepo secRepo; @Autowired private RestTemplate restTemplate; public void execute(String saga, String payload) throws RepoException, SamException { logger.debug("Executing :: {}", saga); Optional<Object> preStep = secRepo.preProcess(saga, payload); Boolean stepsSuccess = this.executeSteps(saga, preStep, payload); secRepo.postProcess(payload, stepsSuccess, preStep); if (!stepsSuccess) throw new SamException("Unable to complete SAGA."); } public Boolean executeSteps(String saga, Optional<Object> preStepData, String payload) throws RepoException { Optional<Saga> sagaObj = sagaService.getSaga(saga); Boolean executionSuccess = Boolean.FALSE; if (sagaObj.isPresent()) { ListIterator<Step> iterator = sagaObj.get().getSteps().listIterator(); while (iterator.hasNext()) { Step step = iterator.next(); logger.debug("Executing s.tep :: {} ", step.getName()); executionSuccess = this.executeStep(step, preStepData, payload); logger.debug("Step success :: {}", executionSuccess); if (!executionSuccess) { logger.debug("All the previous steps will be attempted to be roll backed"); while (iterator.hasPrevious()) { Step prevStep = iterator.previous(); logger.debug("Executing previous step :: {} ", prevStep.getName()); this.executeCompStep(prevStep, preStepData); } break; } } } return executionSuccess; } public Boolean executeStep(Step step, Optional<Object> preStepData, String payload) { Boolean isTxSuccess = false; StepData stepData = new StepData(); stepData.setStatus(TxStatusEnums.Step.STARTED); stepData.setApiPayload(payload); try { secRepo.preExecuteStep(step, stepData, preStepData); try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> httpEntity = new HttpEntity<String>(payload, headers); ResponseEntity<String> response = restTemplate.exchange("http:/" + step.getApi().getPath(), HttpMethod.resolve(step.getApi().getMethod()), httpEntity, String.class); stepData.setApiResponse(response.hasBody() ? response.getBody() : ""); stepData.setApiResponseStatus(response.getStatusCode()); stepData.setStatus(TxStatusEnums.Step.SUCCESS); secRepo.setStepData(step, stepData, preStepData); isTxSuccess = Boolean.TRUE; } catch (HttpClientErrorException clientErrorException) { stepData.setApiResponse("{apierror:" + clientErrorException.getResponseBodyAsString() + "}"); stepData.setApiResponseStatus(clientErrorException.getStatusCode()); stepData.setStatus(TxStatusEnums.Step.FAILED); secRepo.setStepData(step, stepData, preStepData); } catch (Exception th) { logger.error("Step {} has thrown exception", step.getName(), th); stepData.setStatus(TxStatusEnums.Step.FAILED); secRepo.setStepData(step, stepData, preStepData); } } catch (RepoException exception) { logger.error("Step {} has thrown exception", step.getName(), exception); } return isTxSuccess; } public void executeCompStep(Step step, Optional<Object> preStepData) { StepData stepData = null; try { try { stepData = secRepo.getStepData(step, preStepData); SagaHelper.createCAPIPayload(stepData); stepData.setStatus(TxStatusEnums.Step.COMPTXSTARTED); secRepo.setStepData(step, stepData, preStepData); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> httpEntity = new HttpEntity<String>(stepData.getCapiPayload(), headers); ResponseEntity<String> response = restTemplate.exchange("http:/" + step.getCapi().getPath(), HttpMethod.resolve(step.getCapi().getMethod()), httpEntity, String.class); stepData.setCapiResponse(response.hasBody() ? response.getBody() : ""); stepData.setCapiResponseStatus(response.getStatusCode()); stepData.setStatus(TxStatusEnums.Step.COMPTXSUCCESS); secRepo.setStepData(step, stepData, preStepData); } catch (HttpClientErrorException clientErrorException) { stepData.setCapiResponse("{capierror:" + clientErrorException.getResponseBodyAsString() + "}"); stepData.setCapiResponseStatus(clientErrorException.getStatusCode()); stepData.setStatus(TxStatusEnums.Step.COMPTXFAILED); secRepo.setStepData(step, stepData, preStepData); } catch (Exception ex) { if (stepData != null) { stepData.setStatus(TxStatusEnums.Step.COMPTXFAILED); secRepo.setStepData(step, stepData, preStepData); } else { logger.error( "Previous step {} comp action has thrown exception and step data is not available.Cannot update the step data . Status of the transaction is unknown!!", step.getName(), ex); } } } catch (RepoException exception) { logger.error("Previous step {} comp action has thrown exception.Status of the transaction is unknown!!", step.getName(), exception); } } }
package com.itheima.mysql_day04.jdbc_demo_01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class Demo_01 { public static void main(String[] args) throws Exception { //1.导入驱动jar包 //2.注册驱动 Class.forName("com.mysql.jdbc.Driver"); //3. 获取数据库连接对象 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaweb_db02", "root", "dingjie0822"); //4. 定义sql语句 String sql = "update salarygrade set losalary = 30000 where grade = 5"; //5. 获取执行sql的对象 Statement Statement stmt = conn.createStatement(); //6. 执行sql int i = stmt.executeUpdate(sql); //7. 处理结果 System.out.println(i); //8. 释放资源 stmt.close(); conn.close(); } }
package controller.funcionario; import controller.*; import controller.cliente.*; import entity.Carrinho; import entity.Funcionario; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.layout.AnchorPane; public class TelaFuncionarioController implements Initializable { @FXML AnchorPane painelCentral; private Funcionario funcionario; private Carrinho carrinho; private TelaPrincipalController telaPrincipalController; @Override public void initialize(URL url, ResourceBundle rb) { irTelaInicialFuncionario(); carrinho = new Carrinho(); } public void setTelaPrincipalController(TelaPrincipalController telaPrincipalController) { this.telaPrincipalController = telaPrincipalController; } public void irTelaInicialFuncionario() { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/funcionario/TelaInicialFuncionario.fxml")); AnchorPane telaIncialFuncionario = loader.load(); TelaInicialFuncionarioController controller = loader.getController(); controller.setFuncionario(funcionario); controller.setCarrinho(carrinho); controller.setTelaPrincipalController(telaPrincipalController); controller.atualizar(); painelCentral.getChildren().clear(); painelCentral.getChildren().add(telaIncialFuncionario); } catch (IOException ex) { }//fim do catch } public void irCadastrarPet(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/funcionario/TelaCadastrarPetFuncionario.fxml")); AnchorPane telaCadastrarPet = loader.load(); TelaCadastrarPetController controller = loader.getController(); controller.setFuncionario(funcionario); controller.setCarrinho(carrinho); controller.setTelaFuncionarioController(this); controller.setTelaPrincipalController(telaPrincipalController); painelCentral.getChildren().clear(); painelCentral.getChildren().add(telaCadastrarPet); } catch (IOException ex) { }//fim do catch }//fim do metodo public void irRemoverPet(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/funcionario/TelaRemoverPetFuncionario.fxml")); AnchorPane telaRemoverPet = loader.load(); TelaRemoverPetController controller = loader.getController(); controller.setFuncionario(funcionario); controller.setCarrinho(carrinho); controller.setTelaFuncionarioController(this); controller.setTelaPrincipalController(telaPrincipalController); //tira todos os elementos da tela painelCentral.getChildren().clear(); //adiciona a nova tela painelCentral.getChildren().add(telaRemoverPet); } catch (IOException ex) { ex.printStackTrace(); } }//fim do metodo public void irServicos(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/cliente/TelaServicos.fxml")); AnchorPane telaServicos = loader.load(); TelaServicosController controller = loader.getController(); controller.setCarrinho(carrinho); controller.setTelaFuncionarioController(this); controller.setTelaPrincipalController(telaPrincipalController); //tira todos os elementos da tela painelCentral.getChildren().clear(); //adiciona a nova tela painelCentral.getChildren().add(telaServicos); } catch (IOException ex) { } }//fim do metodo public void irPetiscos(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/TelaPetiscos.fxml")); AnchorPane telaPetiscos = loader.load();//carrega a tela TelaPestiscosController controller = loader.getController(); //obtem o controller da tela //controller.setParent(root); controller.atualizar(); controller.setCarrinho(carrinho); controller.setTelaPrincipalController(telaPrincipalController); controller.setTelaFuncionarioController(this); painelCentral.getChildren().clear(); painelCentral.getChildren().add(telaPetiscos); } catch (IOException ex) { Logger.getLogger(TelaInicialClienteController.class.getName()).log(Level.SEVERE, null, ex); } }//fim do metodo public void irAcessorios(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/TelaAcessorios.fxml")); AnchorPane telaAcessorios = loader.load();//carrega a nova tela TelaAcessoriosController controller = loader.getController();//obtem o cntroller da tela //controller.setParent(root); controller.setCarrinho(carrinho); controller.atualizar(); controller.setTelaFuncionarioController(this); controller.setTelaPrincipalController(telaPrincipalController); painelCentral.getChildren().clear(); painelCentral.getChildren().add(telaAcessorios); } catch (IOException ex) { Logger.getLogger(TelaInicialClienteController.class.getName()).log(Level.SEVERE, null, ex); } }//fim do metodo public void irHigiene(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/TelaHigiene.fxml")); AnchorPane telaHigiene = loader.load();//carrega a nova tela TelaHigieneController controller = loader.getController();//obtem o cntroller da tela //controller.setParent(root); controller.setCarrinho(carrinho); controller.atualizar(); controller.setTelaFuncionarioController(this); controller.setTelaPrincipalController(telaPrincipalController); painelCentral.getChildren().clear(); painelCentral.getChildren().add(telaHigiene); } catch (IOException ex) { Logger.getLogger(TelaInicialClienteController.class.getName()).log(Level.SEVERE, null, ex); } }//fim do metodo public void irBrinquedos(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/TelaBrinquedos.fxml")); AnchorPane telaBrinquedos = loader.load();//carrega a nova tela TelaBrinquedosController controller = loader.getController();//obtem o cntroller da tela //controller.setParent(root); controller.setCarrinho(carrinho); controller.atualizar(); controller.setTelaFuncionarioController(this); controller.setTelaPrincipalController(telaPrincipalController); painelCentral.getChildren().clear(); painelCentral.getChildren().add(telaBrinquedos); } catch (IOException ex) { } }//fim do metodo public void irPlanos(ActionEvent event) { }//fim do metodo public void irConsultar(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/funcionario/TelaConsultarCliente.fxml")); AnchorPane telaConsultar = loader.load(); TelaConsultarClienteController controller = loader.getController(); controller.setTelaPrincipalController(telaPrincipalController); controller.setTelaFuncionarioController(this); painelCentral.getChildren().clear(); painelCentral.getChildren().add(telaConsultar); } catch (IOException ex) { } }//fim do metodo public void irAlterarInformacoes(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/funcionario/TelaAlterarInformacoes.fxml")); AnchorPane telaAlterarInformacoes = loader.load(); TelaAlterarInformacoesController controller = loader.getController(); controller.setTelaPrincipalController(telaPrincipalController); controller.setTelaFuncionarioController(this); painelCentral.getChildren().clear(); painelCentral.getChildren().add(telaAlterarInformacoes); } catch (IOException ex) { ex.printStackTrace(); } }//fim do metodo public void irFarmacia(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/TelaFarmacia.fxml")); AnchorPane telaFarmacia = loader.load(); TelaFarmaciaController controller = loader.getController(); controller.atualizar(); controller.setTelaFuncionarioController(this); controller.setTelaPrincipalController(telaPrincipalController); //controller.setParent(root); controller.setCarrinho(carrinho); painelCentral.getChildren().clear(); painelCentral.getChildren().add(telaFarmacia); } catch (IOException ex) { } }//fim do metodo public void irRacao(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/TelaRacao.fxml")); AnchorPane telaRacao = loader.load(); TelaRacaoController controller = loader.getController(); controller.atualizar(); controller.setTelaFuncionarioController(this); controller.setTelaPrincipalController(telaPrincipalController); //controller.setParent(root); controller.setCarrinho(carrinho); painelCentral.getChildren().clear(); painelCentral.getChildren().add(telaRacao); } catch (IOException ex) { ex.printStackTrace(); } }//fim do metodo public void irEstoque(ActionEvent event) { try { FXMLLoader loader = new FXMLLoader(TelaPrincipalController.class.getResource("/view/TelaEstoque.fxml")); AnchorPane telaCadastrarProduto = loader.load(); TelaEstoqueController controller = loader.getController(); controller.setFuncionario(funcionario); controller.setTelaPrincipalController(telaPrincipalController); controller.atualizar(); controller.setTelaFuncionarioController(this); painelCentral.getChildren().clear(); painelCentral.getChildren().add(telaCadastrarProduto); } catch (IOException ex) { ex.printStackTrace(); } }//fim do metodo public void setFuncionario(Funcionario funcionario) { this.funcionario = funcionario; } }
// Author: Olexiy Burov, oburov@ucsc.edu // // $Id: month.java,v 1.4 2015-01-18 19:10:13-08 - - $ // // Describes a calendar month. import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; public class month { // Change date for British Empire. static final GregorianCalendar CHANGE_DATE = new GregorianCalendar(1752, Calendar.SEPTEMBER, 14); static final int WEEKS_IN_MONTH = 6; static final int DAYS_IN_WEEK = 7; // Array which stores all the days in. private int[][] month = null; // Calendar which iterates through dates. private GregorianCalendar calendar = new GregorianCalendar(); // Locale which affects the language used to print dates. private static Locale locale = Locale.getDefault(); // Helper method for getting first 2 letter of the day of the week. private static String prefix (String string, int length) { return length > string.length () ? string : string.substring (0, length); } // Sets locale. public static void set_locale(Locale new_locale) { locale = new_locale; } // Constructor for month, creates specified month. public month(int calmonth, int calyear) { // Sets change. calendar.setGregorianChange(CHANGE_DATE.getTime()); // Initializes array of days of the month. month = new int[WEEKS_IN_MONTH][DAYS_IN_WEEK]; // Starting from the first day, we fill up the month. calendar.set(calyear, calmonth, 1); while (calmonth == calendar.get(GregorianCalendar.MONTH)) { int calday = calendar.get(GregorianCalendar.DAY_OF_MONTH); int weekday = calendar.get(GregorianCalendar.DAY_OF_WEEK) - 1; int week = calendar.get(GregorianCalendar.WEEK_OF_MONTH) - 1; month[week][weekday] = calday; calendar.add(GregorianCalendar.DAY_OF_MONTH, 1); } calendar.set(calyear, calmonth, 1); } // Returns a string containing day names of the week. public String daynames() { StringBuffer string_buffer = new StringBuffer(); calendar.set(Calendar.DAY_OF_WEEK,1); for (int i = 0;i < DAYS_IN_WEEK - 1;i++) { string_buffer.append( prefix(String.format(locale,"%tA",calendar),2)+" "); calendar.add(Calendar.DAY_OF_MONTH,1); } string_buffer.append( prefix(String.format(locale,"%tA",calendar),2)); return string_buffer.toString(); } // Returns centrally aligned string containing name of the month. public String monthname() { return misclib.central_align(String.format(locale, " %tB", calendar), 20); } // Returns month name followed by a year. public String month_year() { return String.format(locale, "%tB %d", calendar, calendar.get(Calendar.YEAR)); } // Returns string which represent one of six weeks in the month. public String week_by_index(int index) { StringBuffer string_buffer = new StringBuffer(); for (int i = 0; i < DAYS_IN_WEEK; i++) { int dayOfWeek = month[index][i]; // First week empty days count as two whitespaces. if (dayOfWeek == 0 && index < 1) string_buffer.append(" "); // Any other week empty days do not count as symbols at all. else if (dayOfWeek == 0) string_buffer.append(""); else string_buffer.append(String.format("%2d ", dayOfWeek)); } // Trims the weeks, so that the are no extra whitespaces left in // the end of the line. try { string_buffer.deleteCharAt(string_buffer.lastIndexOf(" ")); } catch (Exception ex) { } return string_buffer.toString(); } // toString implementation for the month class. // returns string which represents month, year and all the days of // that month in columns. @Override public String toString() { StringBuffer string_buffer = new StringBuffer(); string_buffer.append(String.format("%s%n%s%n", misclib.central_align(month_year(), 20), daynames())); for (int i = 0; i < 6; i++) { string_buffer.append(String.format("%s%n", this.week_by_index(i))); } return string_buffer.toString(); } }
package Problem_1182; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { static int N, S; static int cnt; static int[] arr; static boolean[] isSelected; public static void ans(int idx) { if(idx == N) { int sum = 0; for(int i = 0; i <N; i++) { if(isSelected[i]) sum+=arr[i]; } if(sum==S) cnt++; } else { isSelected[idx] =true; ans(idx+1); isSelected[idx] =false; ans(idx+1); } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String buffer = br.readLine(); N = Integer.parseInt(buffer.split(" ")[0]); S = Integer.parseInt(buffer.split(" ")[1]); arr = new int[N]; isSelected = new boolean[N]; buffer = br.readLine(); for(int i = 0 ; i < N; i++) { arr[i] = Integer.parseInt(buffer.split(" ")[i]); } ans(0); if(S == 0) cnt--; System.out.println(cnt); } }
package com.ideaheap; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * The five puzzle consists of a 3 x 2 grid that consists of five numbers. * The goal is to move these numbers into a grid of: * 1 2 3 * 4 5 0 * * 0 represents the empty space. In order to do this, we will use Iterative * Deepening search, which is an extension of Depth Limited Search. * * This search requires a way to test for goal state, and a way to generate the * next available states. This is broken up into the following: * * idsSearch -> calls the recursive dlsSearch in order to find a path up to a * maximum depth "depth" * * dlsSearch -> calls the given SearchTool function to expand a node and test * for goals * * SearchTool -> offers an expand() function, along with a isGoal() function to * be used by whatever search function is calling it. * */ public class FivePuzzle { public static final int MAX_DEPTH = 12; /** * Main algorithm from a puzzle. * This uses iterative deepening search. * @throws Exception */ public List<String> getMoves(String start, final String end) throws Exception { /* * Puzzle-based implementation of generic function tool for use with search algorithms. */ SearchTool<Puzzle,String> tool = new SearchTool<Puzzle, String>() { Puzzle goal = new Puzzle(end, 3, 2); @Override public Map<String, Puzzle> expand(Puzzle source) { Map<String,Puzzle> moves = new HashMap<String, Puzzle>(); for (String m : source.expandMoves()) { moves.put(m, source.doMove(m)); } return moves; } @Override public Integer cost(Puzzle source) { return 0; } @Override public Integer stepCost(Puzzle source, String m) { return 1; } @Override public boolean isGoal(Puzzle source) { return source.toString().equals(goal.toString()); } }; Puzzle s = new Puzzle(start, 3, 2); return SearchAlgorithms.idsSearch(s, MAX_DEPTH, tool); } /** * UI Wrapper code. * @param args */ public static void main( String[] args ) { FivePuzzle puzzle = new FivePuzzle(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { // Parse the input. System.out.println("Enter in your start state as a six integers."); System.out.println("(e.g. 123450)"); System.out.print("Start: "); String start = reader.readLine(); String goal = "123450"; // State our goal to the user. System.out.println("Goal: " + goal); // Call the cool function. try { List<String> moves = puzzle.getMoves(start, goal); // Show how we get there. for (String m : moves) { System.out.print(m); } } catch (Exception e) { e.printStackTrace(); } System.out.println(); } catch (IOException e) { e.printStackTrace(); } } }
package org.giddap.dreamfactory.cc150; /** * */ public class Q1706MinimumSequenceToBeSorted { public int[] findMinimumSequenceToBeSorted(int[] nums) { final int len = nums.length; // figure out sorted left int sortedLeftEnd = 0; while (sortedLeftEnd < len - 1 && (nums[sortedLeftEnd] <= nums[sortedLeftEnd + 1])) { sortedLeftEnd++; } // figure out sorted right int sortedRightEnd = len - 1; while (sortedRightEnd > 0 && (nums[sortedRightEnd] >= nums[sortedRightEnd - 1])) { sortedLeftEnd++; } if (sortedLeftEnd + 1 == sortedRightEnd) { // already sorted return new int[2]; } // figure out the min value after sortedLeftEnd int minAfterSortedLeftEndIdx = 0; int minAfterSortedLeftEnd = Integer.MAX_VALUE; for (int i = sortedLeftEnd + 1; i < sortedRightEnd; i++) { if (nums[i] < minAfterSortedLeftEnd) { minAfterSortedLeftEnd = nums[i]; minAfterSortedLeftEndIdx = i; } } // figure out the max value before sortedLeftEnd int maxBeforeSortedRightEndIdx = 0; int maxBeforeSortedRightEnd = Integer.MIN_VALUE; for (int i = sortedRightEnd - 1; i > sortedLeftEnd; i--) { if (nums[i] > maxBeforeSortedRightEnd) { maxBeforeSortedRightEnd = nums[i]; maxBeforeSortedRightEndIdx = i; } } //int m = 0; return new int[2]; } }
package com.example.chat.service; import com.example.chat.dto.request.LoginRequest; import com.example.chat.dto.request.SignUpRequest; import com.example.chat.dto.response.UserSummary; import com.example.chat.model.User; import com.example.chat.model.UserPrincipal; import org.springframework.http.ResponseEntity; import java.util.List; public interface UserService { ResponseEntity<?> registerUser(SignUpRequest signUpRequest); ResponseEntity<?> authenticateUser(LoginRequest loginRequest); UserSummary findByUserId(String userId); List<UserSummary> findAllUserSummaries(UserPrincipal currentUser); }
package com.test.base; /** * Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. * (The occurrences may overlap.) * * Return any duplicated substring that has the longest possible length. * (If S does not have a duplicated substring, the answer is "".) * * @author YLine * * 2019年11月21日 下午2:03:18 */ public interface Solution { public String longestDupSubstring(String S); }
package com.gsccs.sme.center.controller; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.gsccs.sme.api.domain.ActEnroll; import com.gsccs.sme.api.domain.Account; import com.gsccs.sme.api.domain.base.Datagrid; import com.gsccs.sme.api.domain.base.JsonMsg; import com.gsccs.sme.api.exception.ApiException; import com.gsccs.sme.api.service.ActivityServiceI; import com.gsccs.sme.api.service.CorpServiceI; import com.gsccs.sme.api.service.AccountServiceI; import com.gsccs.sme.web.api.service.RedisService; /** * 企业活动管理 * * @author x.d zhang * */ @Controller(value="ActivityCtl") @RequestMapping(value = "/cp/activity") public class ActivityController { @Autowired private AccountServiceI accountAPI; @Autowired private CorpServiceI corpAPI; @Autowired private ActivityServiceI activityAPI; @Autowired private RedisService redisService; /** * 报名活动列表 * * @param model * @param response * @return */ @RequestMapping(method = RequestMethod.GET) public String activitylist(Model model, HttpServletResponse response) { return "activity/activitylist"; } @ResponseBody @RequestMapping(value = "/list", method = RequestMethod.POST) public Datagrid activitylist(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int pagesize, Model model, HttpServletResponse response) { Subject subject = SecurityUtils.getSubject(); String username = (String) subject.getPrincipal(); Datagrid datagrid = new Datagrid(); try { Account user = accountAPI.getAccount(username); datagrid = activityAPI.queryEnrollActList(user.getId(), "addtime desc", page, pagesize); } catch (ApiException e) { e.printStackTrace(); } return datagrid; } /** * 企业活动报名 * * @param model * @param response * @return */ @RequestMapping(value = "/enroll", method = RequestMethod.GET) public String activityEnroll(Model model, HttpServletResponse response) { return "activity/activityform"; } /** * 提交参加活动信息 * * @param model * @param response * @return */ @ResponseBody @RequestMapping(value = "/enroll", method = RequestMethod.POST) public JsonMsg activityJoin(ActEnroll actEnroll, Model model, HttpServletResponse response) { JsonMsg jsonMsg = new JsonMsg(); Subject subject = SecurityUtils.getSubject(); String username = (String) subject.getPrincipal(); try { if (null != actEnroll) { Account user = accountAPI.getAccount(username); if (null != user) { actEnroll.setCorpid(user.getOrgid()); actEnroll.setUserid(user.getId()); activityAPI.addActEnroll(actEnroll); } jsonMsg.setSuccess(true); jsonMsg.setMsg("活动报名成功。"); }else{ jsonMsg.setSuccess(false); jsonMsg.setMsg("活动报名失败,请确认报名信息正确"); } } catch (ApiException e) { jsonMsg.setSuccess(false); jsonMsg.setMsg("活动报名失败。"); } return jsonMsg; } }
package com.byraphaelmedeiros.samples.solid.ocp.good; /** * @author Raphael Medeiros (raphael.medeiros@gmail.com) * @since 05/06/2020 */ public class Circle extends Shape { @Override public void draw() { System.out.println("Circle!"); } }
package com.dromedicas.dto; // Generated 28/03/2017 05:43:08 PM by Hibernate Tools 5.1.2.Final import java.util.Date; /** * Existencias generated by hbm2java */ public class Existencias implements java.io.Serializable { private ExistenciasId id; private double cantidad; private Date ultcambio; public Existencias() { } public Existencias(ExistenciasId id, double cantidad, Date ultcambio) { this.id = id; this.cantidad = cantidad; this.ultcambio = ultcambio; } public ExistenciasId getId() { return this.id; } public void setId(ExistenciasId id) { this.id = id; } public double getCantidad() { return this.cantidad; } public void setCantidad(double cantidad) { this.cantidad = cantidad; } public Date getUltcambio() { return this.ultcambio; } public void setUltcambio(Date ultcambio) { this.ultcambio = ultcambio; } }
package com.bnebit.sms.controller; import java.sql.SQLException; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.bnebit.sms.service.ConsultingService; import com.bnebit.sms.service.DailyReportService; import com.bnebit.sms.vo.DailyReport; import jdk.nashorn.internal.ir.RuntimeNode.Request; @Controller public class DailyReportController { @Autowired private DailyReportService dailyReportService; // 일일보고 목록조회 @RequestMapping(value = "/dailyReport/selectDailyReportList", method = {RequestMethod.GET, RequestMethod.POST}) public ModelAndView selectDailyReportListForUser(HttpServletRequest request) throws SQLException { ModelAndView mav = new ModelAndView(); mav = dailyReportService.selectDailyReportListForUser(request); return mav; } // 일일보고 내용조회, 상담일지 목록조회 @RequestMapping(value = "/dailyReport/selectDailyReportView", method = {RequestMethod.GET, RequestMethod.POST}) public ModelAndView selectDailyReportView(HttpServletRequest request) throws SQLException, ParseException { ModelAndView mav = new ModelAndView(); mav = dailyReportService.selectDailyReportView(request); return mav; } /* * @RequestMapping(value="/dailyReport/selectDailyReportView") public * ModelAndView selectDailyReportView(@RequestParam("dailyReport") * DailyReport dailyReport, HttpServletRequest request) throws SQLException * { ModelAndView mav = * dailyReportService.selectDailyReportView(dailyReport); //mav = * dailyReportService.selectConsultingList(request); return mav; } */ // 일일보고 결재 @RequestMapping(value = "/dailyReport/updateDailyReportConfirm", method = RequestMethod.POST) @ResponseBody public void updateDailyReportConfirm(DailyReport dailyReport) throws SQLException { dailyReportService.updateDailyReportConfirm(dailyReport); } // 일일보고 작성 페이지로 이동 @RequestMapping(value = "/dailyReport/insertDailyReportForm") public ModelAndView insertDailyReportForm(HttpServletRequest request) throws SQLException { ModelAndView mav = new ModelAndView(); mav = dailyReportService.insertDailyReportForm(request); return mav; } // 일일보고 작성 @RequestMapping(value = "/dailyReport/insertDailyReport") public ModelAndView insertDailyReport(DailyReport dailyReport) throws SQLException { ModelAndView mav = new ModelAndView(); mav = dailyReportService.insertDailyReport(dailyReport); return mav; } // 일일보고 수정 페이지로 이동 @RequestMapping(value = "/dailyReport/updateDailyReportForm") public ModelAndView updateDailyReportForm(HttpServletRequest request) throws SQLException { ModelAndView mav = new ModelAndView(); mav = dailyReportService.updateDailyReportForm(request); return mav; } // 일일보고 수정 @RequestMapping(value = "/dailyReport/updateDailyReport") public ModelAndView updateDailyReportWorker(DailyReport dailyReport) throws SQLException { ModelAndView mav = new ModelAndView(); mav = dailyReportService.updateDailyReportWorker(dailyReport); return mav; } }
package com.sjj.util; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.apache.spark.streaming.kafka.OffsetRange; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import com.sjj.service.impl.OperateHiveWithSpark; import kafka.common.TopicAndPartition; import lombok.extern.slf4j.Slf4j; @Slf4j @Component public class RedisUtil { private static final String KAFKA_PATITION_REDIS_KEY_SUFFIX = ".partition"; private static final String KAFKA_OFFSET_REDIS_KEY_SUFFIX = ".offset"; @Resource RedisTemplate<String, String> redisTemplate; public Map<TopicAndPartition, Long> getOffset(Set<String> topics) { return getOffsetFromRedis(topics); } public void setOffset(OffsetRange offsetRange) { setOffsetToRedis(offsetRange); } private Map<TopicAndPartition, Long> getOffsetFromRedis(Set<String> topics) { Map<TopicAndPartition, Long> offsets = new HashMap<TopicAndPartition, Long>(); for (String topic : topics) { try { Integer partation = Integer .parseInt(redisTemplate.opsForValue().get(topic + KAFKA_PATITION_REDIS_KEY_SUFFIX)); Long offset = Long.parseLong(redisTemplate.opsForValue().get(topic + KAFKA_OFFSET_REDIS_KEY_SUFFIX)); if (null != partation && null != offset) { log.info("### get kafka offset in redis for kafka ### " + topic + KAFKA_OFFSET_REDIS_KEY_SUFFIX + " >>> " + partation + " | " + offset); offsets.put(new TopicAndPartition(topic, partation), offset); } } catch (NumberFormatException e) { log.error("### Topic: " + topic + " offset exception ###"); } } return offsets; } private void setOffsetToRedis(OffsetRange offsetRange) { redisTemplate.opsForValue().set(offsetRange.topic() + KAFKA_PATITION_REDIS_KEY_SUFFIX, String.valueOf(offsetRange.partition())); redisTemplate.opsForValue().set(offsetRange.topic() + KAFKA_OFFSET_REDIS_KEY_SUFFIX, String.valueOf(offsetRange.fromOffset())); log.info("### update kafka offset in redis ### " + offsetRange.topic() + KAFKA_PATITION_REDIS_KEY_SUFFIX + " >>> " + offsetRange); } }
package com.xyz.jdbnk.security; import com.xyz.jdbnk.model.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; public class AppUserDetails implements UserDetails { private static final long serialVersionUID = -1444372312588440649L; private User user; private Collection<? extends GrantedAuthority> authorities; public AppUserDetails() { super(); } public AppUserDetails(User user) { super(); this.user = user; List<String> roles=new ArrayList<>(); roles.add(user.getRole()); this.authorities=roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getEmail(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
/* * @lc app=leetcode.cn id=61 lang=java * * [61] 旋转链表 */ // @lc code=start /** * Definition for singly-linked list. public class ListNode { int val; ListNode * next; ListNode(int x) { val = x; } } */ class Solution { public ListNode rotateRight(ListNode head, int k) { int len = 0; ListNode tail = null; ListNode tmp = head; if(head == null){ return null; } while (tmp != null) { if (tmp.next == null) tail = tmp; tmp = tmp.next; len++; } k = k % len; if (k == 0) return head; ListNode end = get(head, len - k - 1); ListNode start = get(head, len - k); end.next = null; tail.next = head; return start; } public ListNode get(ListNode head, int index) { for (int i = 1; i <= index; i++) { head = head.next; } return head; } } // @lc code=end
package com.example.alex.allthewage; import android.app.Activity; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.Bundle; import android.provider.SyncStateContract; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.support.v7.app.ActionBar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.*; import com.google.firebase.database.*; /** * Created by Alex on 11/1/2017. */ public class employer_home extends AppCompatActivity { //GRABBING AN INSTANCE OF FIREBASEAUTH FirebaseAuth auth = FirebaseAuth.getInstance(); //Getting the reference to the database DatabaseReference ref = FirebaseDatabase.getInstance().getReference(); //Getting the reference to the employers personal location DatabaseReference empref = ref.child("EMPLOYERS").child("Companies").child(auth.getUid()); DatabaseReference numEmpRef = ref.child("EMPLOYERS").child("Companies").child(auth.getUid()).child("Second Test Company"); long count; private TextView welcomeMessage; private TextView numberOfemp; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.employer_home); welcomeMessage = (TextView) findViewById(R.id.employerWelcome); numberOfemp = (TextView) findViewById(R.id.employerNumberEmployees); // Find the toolbar view inside the activity layout Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // Sets the Toolbar to act as the ActionBar for this Activity window. // Make sure the toolbar exists in the activity and is not null setSupportActionBar(toolbar); DataSnapshot dataSnapshot; //DESCRIPTION // Allows us to display the custom welcome message for each company depending on // their own company name empref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot child: dataSnapshot.getChildren()) { globalVars.GlobalCompanyName = child.getKey(); System.out.println("Welcome, " + globalVars.GlobalCompanyName); count = dataSnapshot.getChildrenCount(); welcomeMessage.setText("Welcome, " + globalVars.GlobalCompanyName); } } @Override public void onCancelled(DatabaseError databaseError) { } }); numEmpRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot child: dataSnapshot.getChildren()) { globalVars.GlobalCompanyName = child.getKey(); count = dataSnapshot.getChildrenCount(); numberOfemp.setText("Number of Employees: " + count); } } @Override public void onCancelled(DatabaseError databaseError) { } }); final Button button = (Button) findViewById(R.id.Geo_Fence_Button); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Code here executes on main thread after user presses button Toast.makeText( getApplicationContext(), "You Clicked : " + button, Toast.LENGTH_SHORT ).show(); startActivity(new Intent(employer_home.this, geo_fence_class.class)); } }); } public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.mymenu, menu); return true; } public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.employeesMenu: Intent empIntent = new Intent(employer_home.this, employee_info.class); startActivity(empIntent); return true; case R.id.paychecksMenu: Intent paycheckIntent = new Intent(employer_home.this, paychecks.class); startActivity(paycheckIntent); return true; case R.id.sethoursMenu: Intent setHoursIntent = new Intent (employer_home.this, set_hours.class); startActivity(setHoursIntent); return true; case R.id.setpayrateMenu: Intent setPayIntent = new Intent (employer_home.this, set_pay_rate.class); startActivity(setPayIntent); return true; case R.id.forumMenu: Intent forumIntent = new Intent (employer_home.this, forum.class); startActivity(forumIntent); return true; case R.id.helpMenu: Intent helpIntent = new Intent (employer_home.this, help.class); startActivity(helpIntent); return true; case R.id.signoutMenu: auth.signOut(); Intent signOutIntent = new Intent(employer_home.this, MainActivity.class); startActivity(signOutIntent); return true; } return true; } }
package com.algonquincollege.mad9132.ictlabschedules; /** * Define the schedule's Periods. * * @author Gerald.Hurdle@AlgonquinCollege.com * */ public enum Periods { H0800, H0900, H1000, H1100, H1200, H1300, H1400, H1500, H1600, H1700, }
/* * 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 crawlers.publishers.aNacaoCv; import crawlers.publishers.exceptions.ArticlesNotFoundException; import crawlers.publishers.exceptions.AuthorsNotFoundException; import crawlers.FlexNewsCrawler; import crawlers.Logos; import db.news.NewsSource; import db.news.Tag; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * * @author zua */ public class ANacaoCVCrawler extends FlexNewsCrawler { public ANacaoCVCrawler() { } @Override public void crawl() { try { crawlWebsite(getMySource().getUrl(), getMySource()); } catch (Exception e) { getLogger().error(String.format("Exception thrown %s", e.getMessage())); } } @Override public NewsSource getMySource() { String sourceId = "a-nacao"; String name = "A Nação"; String description = ""; String url = "http://anacao.cv"; String category = "geral"; String language = "pt"; String country = "CV"; NewsSource source = new NewsSource(); source.setCountry(country); source.setDescription(description); source.setLanguage(language); source.setLogoUrl(Logos.getLogo(sourceId)); source.setName(name); source.setSourceId(sourceId); source.setUrl(url); source.setCategory(new Tag(category)); return source; } @Override public Elements getArticles(Document document) throws ArticlesNotFoundException { if (document == null) { throw new IllegalArgumentException("Document cannot be null"); } Elements articles = document.select("div.masonry_post"); if (!articles.isEmpty()) { return articles; } return null; } @Override protected String getUrlValue(Element article) { if (article == null) { throw new IllegalArgumentException("Article cannot be null"); } Elements urls = article.select("a.link_title"); if (!urls.isEmpty() && !urls.attr("href").isEmpty()) { return urls.attr("href"); } return null; } @Override protected String getTitleValue(Document document) { if (document == null) { throw new IllegalArgumentException("Document cannot be null"); } Elements titles = document.select("div.single_title > h1"); if (!titles.isEmpty() && !titles.text().isEmpty()) { return titles.text(); } return null; } @Override protected String getImageUrlValue(Document document) { if (document == null) { throw new IllegalArgumentException("Document cannot be null"); } Elements images = document.select("div.single_thumbnail > a"); if (!images.isEmpty() && !images.attr("href").isEmpty()) { return images.attr("href"); } return null; } @Override protected String getContentValue(Document document) { if (document == null) { throw new IllegalArgumentException("Document cannot be null"); } Elements contents = document.select("#single_excerpt_post_title"); if (!contents.isEmpty() && !contents.text().isEmpty()) { return contents.text(); } return null; } @Override protected String getAuthorsValue(Document document) throws AuthorsNotFoundException { if (document == null) { throw new IllegalArgumentException("Document cannot be null"); } Elements paragraphs = document.select("div.single_text > p"); if (!paragraphs.isEmpty() && paragraphs.last() != null && !paragraphs.last().text().isEmpty()) { return paragraphs.last().text(); } return getMySource().getName(); } @Override protected String getTimeValue(Document document) { if (document == null) { throw new IllegalArgumentException("Document cannot be null"); } Elements times = document.select("div.post_meta_line div.post_time"); if (!times.isEmpty() && times.first() != null && !times.first().text().isEmpty()) { return times.first().text(); } return null; } }
package com.example.hrmsEightDay.core.utilities.adapters; public class FakeMernisService { public boolean ValidateByPersonalInfo(String identityNumber, String firstName, String lastName, int birthYear) { System.out.println(firstName + " " + lastName + " is valid person." ); return true; } }
package com.xi.util; import java.io.File; import java.util.*; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; public class SendMail { private String to; private String from_username="sd61ts1@163.com"; private String from_nickname="xisir"; private String subject; private String content; private boolean isHTML=true; private HashMap<String,File> attachment=new HashMap<String,File>(); private HashMap<String,File> htmlFile=new HashMap<String,File>(); public SendMail(String mail,Map<String,Object> obj) { this.to=mail; this.subject=obj.get("subject").toString(); this.content=obj.get("content").toString(); } public void setHtml(boolean isHTML){ this.isHTML=isHTML; } public void addAttachment(File file){ attachment.put(file.getName(),file); } public void addAttachment(String filename,File file){ attachment.put(filename,file); } public void setLocalFileToHTMLContect(String content_id,File file){ htmlFile.put(content_id, file); } public boolean send() { JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); MimeMessage mailMessage = senderImpl.createMimeMessage(); try { MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"UTF-8"); messageHelper.setTo(to); messageHelper.setFrom(from_username,from_nickname); messageHelper.setSubject(new String(subject.getBytes("UTF-8"), "UTF-8")); messageHelper.setText(content,this.isHTML); if(this.isHTML&&htmlFile.size()>0){ Iterator<String> keys=htmlFile.keySet().iterator(); while(keys.hasNext()){ String key=keys.next(); messageHelper.addInline(key,htmlFile.get(key)); } } if(attachment.size()>0){ Iterator<String> keys= attachment.keySet().iterator(); while(keys.hasNext()){ String key=keys.next(); messageHelper.addAttachment(MimeUtility.encodeWord(key),attachment.get(key)); } } senderImpl.setHost("smtp.163.com"); senderImpl.setUsername("sd61ts1@163.com");//PropertiesUtils.getProperty("email") senderImpl.setPassword("sd61ts");//PropertiesUtils.getProperty("password") senderImpl.send(mailMessage); return true; } catch (Exception e) { return false; } } public static void main(String[] args) { Map<String,Object> obj =new HashMap<String,Object>(); String subject="subject"; obj.put("subject",subject); String content="content"; obj.put("content",content); SendMail sm=new SendMail("157309341@qq.com",obj); // sm.send(); if(sm.send()){ System.out.println(" send sucess"); }else{ System.out.println("send fail"); } } public void mySendEmail(String email,String subject,String content){ // email="157309341@qq.com"; Map<String,Object> obj=new HashMap<String, Object>(); obj.put("subject",subject); obj.put("content",content); SendMail sm=new SendMail(email,obj); if(sm.send()){ System.out.println(" send sucess"); }else{ System.out.println("send fail"); } } }
package com.example.fiszking; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import androidx.appcompat.app.AppCompatActivity; public class EditWord extends AppCompatActivity { String Id; String word; String meaning; private EditText wordEditText; private EditText meaningEditText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_word); wordEditText = (EditText) findViewById(R.id.word); meaningEditText = (EditText) findViewById(R.id.meaning); Id = getIntent().getStringExtra("EXTRA_ID"); word = getIntent().getStringExtra("EXTRA_WORD"); meaning = getIntent().getStringExtra("EXTRA_MEANING"); wordEditText.setText(word); meaningEditText.setText(meaning); } public void saveWord(View view) { DatabaseHelper myDB = new DatabaseHelper(EditWord.this); word = wordEditText.getText().toString().trim(); meaning = meaningEditText.getText().toString().trim(); myDB.updateData(Id, word, meaning); // String editedNoteName = noteNameEditText.getText().toString(); // String editedNoteContent = noteContentEditText.getText().toString(); finish(); } public void goBack(View view) { finish(); } }