text stringlengths 10 2.72M |
|---|
/*
Power Of Numbers
Given a number and its reverse. Find that number raised to the power of its own reverse.
Note: As answers can be very large, print the result modulo 109 + 7.
Example 1:
Input:
N = 2
Output: 4
Explanation: The reverse of 2 is 2
and after raising power of 2 by 2
we get 4 which gives remainder as
4 by dividing 1000000007.
Example 2:
Input:
N = 12
Output: 864354781
Explanation: The reverse of 12 is 21
and 1221 , when divided by 1000000007
gives remainder as 864354781.
Your Task:
You don't need to read input or print anything. You just need to complete the function pow() that takes two parameters N and R denoting the input number and its reverse and returns power of (N to R)mod(109 + 7).
Expected Time Complexity: O(LogN).
Expected Auxiliary Space: O(LogN).
Constraints:
1 <= N <= 105
*/
// { Driver Code Starts
//Initial Template for Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class Main {
class Solution {
Dictionary<Integer, Long> result = new Hashtable<Integer, Long>();
long power(int N,int R) {
if (R == 1) {
return N;
}
if (result.get(R) != null) {
return result.get(R);
} else {
long part1 = power(N, R/2);
long part2 = power(N, R-R/2);
result.put(R/2, part1);
result.put(R-R/2, part2);
return part1 * part2 % 1000000007;
}
}
}
|
package com.zkp.controller;
import com.api.api;
import com.zkp.Goods;
import com.zkp.Jifen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
/**
* @author admin
*/
@RestController
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping("save")
public Map save(){
//远程调用goods服务,获取goods信息,发动http请求(httpclient)=>restTemplate spring封装好的
String service = "cloud-goods";
String url = "http://"+service+"/findById/3";
Goods goods = restTemplate.getForObject(url, Goods.class);
System.out.println(goods);
//保存订单
System.out.println("订单保存成功");
return new HashMap(){
{
put("code","200");
put("msg","成功");
}
};
}
@RequestMapping("test")
public String test(){
String service = "cloud-goods";
String url = "http://"+service+"/save";
Goods goods = new Goods("华为",4);
HashMap hashMap = restTemplate.postForObject(url, goods, HashMap.class);
System.out.println(hashMap);
return "success";
}
@RequestMapping("test1")
public String test1(){
String service = "cloud-goods";
String url = "http://"+service+"/save";
Goods goods = new Goods("华为",4);
ResponseEntity<HashMap> result = restTemplate.postForEntity(url, goods, HashMap.class);
System.out.println(result.getBody());
System.out.println(result.getStatusCode());
return "success";
}
@RequestMapping("test2")
public Map test2(){
//远程调用goods服务,获取goods信息,发动http请求(httpclient)=>restTemplate spring封装好的
String service = "cloud-goods";
String url = "http://"+service+"/findById/3";
ResponseEntity<Goods> forEntity = restTemplate.getForEntity(url, Goods.class);
System.out.println(forEntity.getBody());
System.out.println(forEntity.getStatusCode());
//保存订单
System.out.println("订单保存成功");
return new HashMap(){
{
put("code","200");
put("msg","成功");
}
};
}
@Autowired
private com.api.api api;
@RequestMapping("feign1")
public Map feign1(){
Jifen jifen = new Jifen(1,10,"2");
Map save = api.save(jifen);
return save;
}
@RequestMapping("feign2")
public Map update() {
Jifen jifen = new Jifen(10,11,"update");
Map update = api.update(jifen);
return update;
}
@GetMapping(value = "/feign3")
public Map deleteById() {
//url http://cloud-jifen/jifen/delete?jifenId=1
int jifenId = 99;
Map deleteById =api.deleteById(jifenId);
return deleteById;
}
@RequestMapping("test4")
public Jifen test4(){
int jifenId = 10;
Jifen jifenById = api.findJifenById(100);
return jifenById;
}
}
|
package com.tt.miniapp.msg;
import android.app.Activity;
import com.tt.frontendapiinterface.b;
import com.tt.miniapp.follow.FollowMethodImpl;
import com.tt.miniapp.follow.FollowResultCallback;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.AppbrandContext;
import com.tt.miniapphost.MiniappHostBase;
import com.tt.option.e.e;
import org.json.JSONObject;
public class ApiFollowOfficialAccount extends b {
public ApiFollowOfficialAccount(String paramString, int paramInt, e parame) {
super(paramString, paramInt, parame);
}
private void startFollowProcedure(Activity paramActivity) {
(new FollowMethodImpl(new FollowResultCallback() {
public void callBackResult(int param1Int, String param1String) {
JSONObject jSONObject = new JSONObject();
boolean bool = false;
try {
jSONObject.put("errCode", param1Int);
} finally {
Exception exception = null;
}
if (bool) {
ApiFollowOfficialAccount.this.callbackOk(param1String, jSONObject);
return;
}
ApiFollowOfficialAccount.this.callbackFail(param1String, jSONObject);
}
})).startFollow(paramActivity);
}
public void act() {
AppBrandLogger.d("ApiHandler", new Object[] { "ApiFollowOfficialAccount" });
MiniappHostBase miniappHostBase = AppbrandContext.getInst().getCurrentActivity();
if (miniappHostBase == null) {
callbackFail("activity is null");
return;
}
startFollowProcedure((Activity)miniappHostBase);
}
public String getActionName() {
return "followOfficialAccount";
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\ApiFollowOfficialAccount.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package it.usi.xframe.xas.bfimpl;
import java.text.MessageFormat;
import it.usi.xframe.xas.bfutil.XASException;
/**
* Bean implementation class for Enterprise Bean: XasSendsms
*/
public class XasSendsmsBean
extends it.usi.xframe.xas.bfimpl.XasSendsmsServiceFacade
implements javax.ejb.SessionBean {
private static final long serialVersionUID = 1L;
private javax.ejb.SessionContext mySessionCtx;
/**
* getSessionContext
*/
public javax.ejb.SessionContext getSessionContext() {
return mySessionCtx;
}
/**
* setSessionContext
*/
public void setSessionContext(javax.ejb.SessionContext ctx) {
mySessionCtx = ctx;
}
/**
* ejbCreate
*/
public void ejbCreate() throws javax.ejb.CreateException {
initializeSupport(getSessionContext());
initializationCleanup();
}
/**
* ejbActivate
*/
public void ejbActivate() {
}
/**
* ejbPassivate
*/
public void ejbPassivate() {
}
/**
* ejbRemove
*/
public void ejbRemove() {
}
}
|
package com.garande.tech.chatapp.repositories;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.garande.tech.chatapp.model.User;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
public class SplashRepository {
private FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
private CollectionReference userRef = FirebaseFirestore.getInstance().collection(User.KeyTableName);
private User user = new User();
public MutableLiveData<User> verifyUserAuthentication() {
MutableLiveData<User> isUserAuthenticatedMutableLiveData = new MutableLiveData<>();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if(firebaseUser == null){
user.isAuthenticated = false;
}else {
user.isAuthenticated = true;
}
isUserAuthenticatedMutableLiveData.setValue(user);
return isUserAuthenticatedMutableLiveData;
}
}
|
/*
* 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 missile;
import data.Entity;
import data.GameData;
import data.World;
import entityparts.LifePart;
import entityparts.MovingPart;
import entityparts.PositionPart;
import entityparts.ProjectilePart;
import entityparts.TimerPart;
import services.IGamePluginService;
import commonprojectile.Projectile;
import java.io.File;
import org.openide.util.lookup.ServiceProvider;
import org.openide.util.lookup.ServiceProviders;
/**
*
* @author magnusm
*/
@ServiceProviders(value = {
@ServiceProvider(service = IGamePluginService.class),})
public class MissilePlugin implements IGamePluginService {
private Entity missile;
private String imageurl = new File("").getAbsolutePath() + "/Missile/target/Missile-1.0-SNAPSHOT.jar!/images/assets/missile.png";
private String soundurl = new File("").getAbsolutePath() + "/Missile/target/Missile-1.0-SNAPSHOT.jar!/images/assets/MissileSound.mp3";
@Override
public void start(GameData gameData, World world) {
world.addEntity(createMissile(0,0,0,imageurl));
}
@Override
public void stop(GameData gameData, World world) {
for (Entity m : world.getEntities(Projectile.class)){
world.removeEntity(m);
}
}
private Entity createMissile(float x, float y, float radians, String uuid) {
Entity m = new Projectile();
m.add(new PositionPart(x, y, radians));
m.add(new MovingPart(0, 5000, 800, 0));
m.add(new TimerPart(3));
m.add(new LifePart(1));
// Projectile Part only used for better collision detection
m.add(new ProjectilePart(uuid.toString()));
m.setRadius(2);
m.setSprite(imageurl);
m.setSpawnSound(soundurl);
float[] colour = new float[4];
colour[0] = 0.2f;
colour[1] = 0.5f;
colour[2] = 0.7f;
colour[3] = 1.0f;
m.setColour(colour);
return m;
}
}
|
package com.tencent.mm.wallet_core.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.wallet_core.a;
import com.tencent.mm.wallet_core.c;
class WalletBaseUI$4 implements OnClickListener {
final /* synthetic */ WalletBaseUI uYT;
WalletBaseUI$4(WalletBaseUI walletBaseUI) {
this.uYT = walletBaseUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
this.uYT.cDH();
c af = a.af(this.uYT);
if (af == null) {
this.uYT.finish();
} else if (!af.h(this.uYT, this.uYT.sy)) {
af.b(this.uYT, this.uYT.sy);
}
}
}
|
package com.framework.controller;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ResponseBody;
import com.framework.bean.common.JsTreeNodeBean;
import com.framework.bean.common.ResultMessage;
import com.framework.bean.vo.SysDepartmentTreeVo;
import com.framework.bean.vo.SysMenuVo;
import com.framework.model.SysDepartment;
import com.framework.service.DepartmentService;
import com.google.gson.reflect.TypeToken;
@Controller
@RequestMapping("dept")
public class DepartmentController extends BaseController {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private DepartmentService departmentService;
@RequestMapping("toDeptManage")
public String toDeptManage(){
return "system/dept/deptManage";
}
@RequestMapping("/getDeptWithUserJsTreeData")
@ResponseBody
public ResultMessage<JsTreeNodeBean> getDeptWithUserJsTreeData(){
ResultMessage<JsTreeNodeBean> resultMessage = new ResultMessage<>();
try{
JsTreeNodeBean root = departmentService.getDeptWithUserJsTreeData();
resultMessage.setModel(root);
resultMessage.setSuccess(true);
}catch(Exception e){
logger.error(e.getMessage(), e);
}
return resultMessage;
}
@RequestMapping("queryDeptListByPCode")
@ResponseBody
public List<SysDepartmentTreeVo> queryDeptListByPCode(String pCode){
List<SysDepartmentTreeVo> departmentTrees = new ArrayList<>();
try {
departmentTrees = departmentService.queryMenuListByPCode(pCode);
} catch (Exception e) {
e.printStackTrace();
}
return departmentTrees;
}
@RequestMapping("saveDepartment")
@ResponseBody
public ResultMessage<?> saveDepartment(String deptJson){
ResultMessage<?> resultMessage = new ResultMessage<>();
try{
List<SysDepartment> departments = gson.fromJson(deptJson, new TypeToken<List<SysDepartment>>(){}.getType());
departmentService.saveDepartment(departments);
resultMessage.setSuccess(true);
}catch(Exception e){
logger.error(e.getMessage(), e);
}
return resultMessage;
}
}
|
package br.org.funcate.glue.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import javax.swing.AbstractListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import br.org.funcate.glue.controller.Mediator;
import br.org.funcate.glue.main.AppSingleton;
import br.org.funcate.glue.model.canvas.CanvasState;
import br.org.funcate.glue.model.toolbar.ToolEnum;
import br.org.funcate.glue.model.toolbar.ToolService;
import br.org.funcate.glue.utilities.Utils;
public class ScreenRequetServices extends JDialog {
private static final long serialVersionUID = -7144045290502352908L;
public static ScreenRequetServices getInstance() {
if (instance == null) {
instance = new ScreenRequetServices();
}
return instance;
}
public static String getValue() {
return value;
}
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
ScreenRequetServices dialog = new ScreenRequetServices();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setValue(String value) {
ScreenRequetServices.value = value;
}
private final JPanel contentPanel = new JPanel();
private JList<String> list;
//private DefaultListModel<String> listModel;
private HashMap<String, String> requestMap;
private HashMap<String, String> descMap;
private JLabel lbl_url;
private JTextArea textAreaDesc;
private HashMap<String, String> idMap;
private static String value;
private static ScreenRequetServices instance;
private JLabel lblImage;
private JButton btnCleanMap;
private static String mapId;
/**
* Create the dialog.
*/
@SuppressWarnings({ "serial", "rawtypes", "unchecked" })
public ScreenRequetServices() {
setModal(false);
addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent arg0) {
requestMap = new HashMap<String, String>();
descMap = new HashMap<String, String>();
idMap = new HashMap<String, String>();
Toolbar.getBtnTileRequest().setEnabled(false);
idMap.put("OpenStreetMap", "0");
idMap.put("GoogleMaps", "2");
idMap.put("WMS", "3");
idMap.put("Bauru", "1");
idMap.put("Instituto Geográfico e Cartográfico", "4");
}
});
setBounds(100, 100, 404, 208);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBackground(new Color(255, 255, 255));
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
JButton btnApply = new JButton("Aplicar");
btnApply.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Mediator mediator = AppSingleton.getInstance().getMediator();
String value = list.getSelectedValue();
if (value != null && value != "") {
// if(!requestMap.get(list.getSelectedValue()).isEmpty())
mapId = idMap.get(list.getSelectedValue());
mediator.setToolBarSource(mapId);
} else {
GlueMessageDialog.show("selecione um opção de mapa", null,2);
}
ToolService.setSelectedTool(ToolEnum.GOOGLE);
ToolService.setToolEnabled(ToolEnum.GOOGLE, true);
AppSingleton singleton = AppSingleton.getInstance();
CanvasState state = singleton.getCanvasState();
state.setDataSource(getValue());
}
});
btnApply.setFont(new Font("SansSerif", Font.BOLD, 12));
btnApply.setBackground(new Color(255, 255, 255));
btnApply.setBounds(19, 128, 75, 30);
contentPanel.add(btnApply);
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.setBounds(10, 11, 389, 24);
contentPanel.add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel(
"Servi\u00E7o de Requisi\u00E7\u00E3o Web ");
lblNewLabel.setBackground(new Color(192, 192, 192));
lblNewLabel.setFont(new Font("SansSerif", Font.BOLD, 14));
lblNewLabel.setBounds(6, 1, 377, 22);
panel.add(lblNewLabel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(20, 51, 232, 75);
contentPanel.add(scrollPane);
list = new JList<String>();
list.setModel(new AbstractListModel() {
String[] values = new String[] {"OpenStreetMap","GoogleMaps","WMS","Bauru"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
list.setFont(new Font("SansSerif", Font.BOLD | Font.ITALIC, 12));
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
lbl_url.setText(requestMap.get(list.getSelectedValue()));
textAreaDesc.setText(descMap.get(list.getSelectedValue()));
setValue(list.getSelectedValue());
String idImage = idMap.get(list.getSelectedValue());
if (idImage.equals("0")) {
lblImage.setIcon(new ImageIcon(
ScreenRequetServices.class
.getResource("/br/org/funcate/glue/image/OpenStreetMap.png")));
} else if (idImage.equals("2")) {
lblImage.setIcon(new ImageIcon(
ScreenRequetServices.class
.getResource("/br/org/funcate/glue/image/rioHybrid.gif")));
GlueMessageDialog.show(
"Mapa de direitos autorais do Google.\nLeia os termos de serviço adicionais do Google:" +
"\nhttp://www.google.com/intl/pt-BR_ALL/help/terms_maps.html", "", 2);
} else { // set image cgi
lblImage.setIcon(new ImageIcon(
ScreenRequetServices.class
.getResource("/br/org/funcate/glue/image/World.gif")));
}
}
});
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane.setViewportView(list);
list.setBorder(new LineBorder(new Color(192, 192, 192)));
JPanel panel_1 = new JPanel();
panel_1.setVisible(false);
panel_1.setLayout(null);
panel_1.setBackground(new Color(192, 192, 192));
panel_1.setBounds(10, 164, 389, 24);
contentPanel.add(panel_1);
JLabel lblUrl = new JLabel("URL :");
lblUrl.setFont(new Font("SansSerif", Font.BOLD, 14));
lblUrl.setBackground(new Color(230, 230, 250));
lblUrl.setBounds(6, 1, 36, 22);
panel_1.add(lblUrl);
lbl_url = new JLabel("");
lbl_url.setForeground(new Color(0, 0, 128));
lbl_url.setFont(new Font("SansSerif", Font.ITALIC, 13));
lbl_url.setBounds(47, 5, 336, 16);
panel_1.add(lbl_url);
textAreaDesc = new JTextArea();
textAreaDesc.setVisible(false);
textAreaDesc.setBackground(new Color(255, 255, 255));
textAreaDesc.setLineWrap(true);
textAreaDesc.setFont(new Font("SansSerif", Font.ITALIC, 13));
textAreaDesc.setBounds(10, 211, 372, 44);
contentPanel.add(textAreaDesc);
JLabel lblDesc = new JLabel("Descri\u00E7\u00E3o:");
lblDesc.setVisible(false);
lblDesc.setFont(new Font("SansSerif", Font.BOLD, 12));
lblDesc.setBackground(new Color(230, 230, 250));
lblDesc.setBounds(10, 191, 75, 22);
contentPanel.add(lblDesc);
lblImage = new JLabel("");
lblImage.setBounds(264, 51, 106, 99);
contentPanel.add(lblImage);
lblImage.setHorizontalAlignment(SwingConstants.CENTER);
lblImage.setIcon(new ImageIcon(ScreenRequetServices.class
.getResource("/br/org/funcate/glue/image/World.gif")));
btnCleanMap = new JButton("Remover Camada");
btnCleanMap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Mediator mediator = AppSingleton.getInstance().getMediator();
mediator.setToolBarSource(null);
setMapId(null);
Toolbar.getWms().setEnabled(true);
ToolService.setToolEnabled(ToolEnum.WMS, true);
}
});
btnCleanMap.setFont(new Font("SansSerif", Font.BOLD, 12));
btnCleanMap.setBackground(Color.WHITE);
btnCleanMap.setBounds(95, 128, 137, 30);
contentPanel.add(btnCleanMap);
Utils.setScreenToCenter(this);
}
public String createLinkText(String text, String cor) {
text = "<html><font color=\"#" + cor + "\"><u>" + text
+ "</u></font></html>";
return text;
}
public static String getMapId() {
return mapId;
}
public static void setMapId(String mapId) {
ScreenRequetServices.mapId = mapId;
}
}
|
package com.chiriyankandath.englishvowelssounds.util;
/**
* Created by puannjoy on 9/5/2015.
*/
public class Constants {
public static final int SHORT_A_SOUND = 1;
public static final int LONG_A_SOUND = 2;
public static final int SHORT_E_SOUND = 3;
public static final int LONG_E_SOUND = 4;
public static final int SHORT_I_SOUND = 5;
public static final int LONG_I_SOUND = 6;
public static final int SHORT_O_SOUND = 7;
public static final int LONG_O_SOUND = 8;
public static final int SHORT_U_SOUND = 9;
public static final int LONG_U_SOUND = 10;
public static final String A_MALAYALAM_VOWEL = "\u0D05";
public static final String AA_MALAYALAM_VOWEL = "\u0D06";
public static final String E_MALAYALAM_VOWEL = "\u0D07";
public static final String EE_MALAYALAM_VOWEL = "\u0D08";
public static final String U_MALAYALAM_VOWEL = "\u0D09";
public static final String UU_MALAYALAM_VOWEL = "\u0D0A";
public static final String ERU_MALAYALAM_VOWEL = "\u0D0B";
public static final String AE_MALAYALAM_VOWEL = "\u0D0E";
public static final String AAE_MALAYALAM_VOWEL = "\u0D0F";
public static final String I_MALAYALAM_VOWEL = "\u0D10";
public static final String O_MALAYALAM_VOWEL = "\u0D12";
public static final String OO_MALAYALAM_VOWEL = "\u0D13";
public static final String OU_MALAYALAM_VOWEL = "\u0D14";
public static final String KA_MALAYALAM_SOUND = "\u0D15";
public static final String KHA_MALAYALAM_SOUND = "\u0D16";
public static final String GA_MALAYALAM_SOUND = "\u0D17";
public static final String GHA_MALAYALAM_SOUND = "\u0D18";
public static final String NGA_MALAYALAM_SOUND = "\u0D19";
public static final String CHA_MALAYALAM_SOUND = "\u0D1A";
public static final String ECHA_MALAYALAM_SOUND = "\u0D1B";
public static final String JA_MALAYALAM_SOUND = "\u0D1C";
public static final String EJA_MALAYALAM_SOUND = "\u0D1D";
public static final String NJA_MALAYALAM_SOUND = "\u0D1E";
}
|
package cefetiny;
import java.util.ArrayList;
import InterpretadorDoPrograma.*;
import Lista.*;
import Excecoes.*;
public class ManipuladorArquivo {
private InterpretadorDoPrograma LeituraSimbolos;
private ArrayList<Comando> LeituraComandos;
private SimbolosCefetiny LeituraEntrada;
public ManipuladorArquivo(String fileName) throws java.io.FileNotFoundException {
this.LeituraSimbolos = new InterpretadorDoPrograma(fileName);
this.LeituraComandos = new ArrayList<>();
}
public void run() {
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
if(this.LeituraEntrada.getToken() != ContantesDaLinguagem.START)
throw new FalhaErroDeSintaxe("Erro: bloco de comando invalido na linha "
+ this.LeituraSimbolos.getNumeroDaLinha() + ": era esperado begin");
do {
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
Comando cmd = null;
cmd = getComando(this.LeituraEntrada.getToken());
this.LeituraComandos.add(cmd);
} while (this.LeituraEntrada.getToken() != ContantesDaLinguagem.END);
this.executa();
}
public Comando getComando(int identificador){
Comando cmd;
switch (identificador) {
case ContantesDaLinguagem.FOR:
cmd = trataFor();
break;
case ContantesDaLinguagem.WHILE:
cmd = trataWhile();
break;
case ContantesDaLinguagem.ENDWHILE:
cmd = trataEndWhile();
break;
case ContantesDaLinguagem.ELSE:
cmd = trataElse();
break;
case ContantesDaLinguagem.ENDIF:
cmd = trataEndIf();
break;
case ContantesDaLinguagem.IF:
cmd = trataIf();
break;
case ContantesDaLinguagem.T_IDENTIFIER:
cmd = trataAtrib();
break;
case ContantesDaLinguagem.READINT:
cmd = trataComandoReadInt();
break;
case ContantesDaLinguagem.PRINTLN:
cmd = trataComandoPrintln();
break;
case ContantesDaLinguagem.PRINT:
cmd = trataComandoPrint();
break;
case ContantesDaLinguagem.END:
cmd = trataComandoEnd();
break;
default:
throw new FalhaErroDeSintaxe("Erro: bloco de comando invalido na linha "
+ this.LeituraSimbolos.getNumeroDaLinha() + ": foi encontrado '"
+ this.LeituraEntrada.getLexema() + "' ");
}
return cmd;
}
private Comando trataAtrib(){
LeituraSimbolos.usarUltimoSimbolo = false;
SimbolosCefetiny var = this.LeituraEntrada;
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
if (this.LeituraEntrada.getToken() != ContantesDaLinguagem.ATRIBOP) {
throw new FalhaErroDeSintaxe("Era esperado um := depois de uma variavel na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
Lista<SimbolosCefetiny> expressao = new Lista();
getExpressao(expressao);
return new ComandoDeAtribuicao(expressao, var.getLexema());
}
private void getExpressao(Lista<SimbolosCefetiny> exp){
boolean isOp = false;
Lista<SimbolosCefetiny> aux = exp;
int abriu=0;
while(isValid(this.LeituraEntrada.getToken())){
if(this.LeituraEntrada.getToken()==ContantesDaLinguagem.ABREPAR || this.LeituraEntrada.getToken()==ContantesDaLinguagem.FECHAPAR){
if(this.LeituraEntrada.getToken()==ContantesDaLinguagem.ABREPAR){
abriu++;
aux.add(this.LeituraEntrada);
}else if(this.LeituraEntrada.getToken()==ContantesDaLinguagem.FECHAPAR){
if(abriu>0){
abriu--;
aux.add(this.LeituraEntrada);
}
}
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
}
else if(this.LeituraEntrada.getToken()== ContantesDaLinguagem.T_IDENTIFIER || this.LeituraEntrada.getToken()== ContantesDaLinguagem.T_CONSTANT){
if(isOp){
break;
}
else{
aux.add(this.LeituraEntrada);
isOp=true;
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
}
}
else if(this.LeituraEntrada.getToken()==ContantesDaLinguagem.UNOP){
aux.add(this.LeituraEntrada);
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
Lista<SimbolosCefetiny> expressao = new Lista<>();
getExpressao(expressao);
for(int i=0;i<expressao.getTamanho();i++){
aux.add(expressao.get(i));
}
isOp = true;
}
else {
if(!isOp){
throw new FalhaErroDeSintaxe("Era esperado um operador apos um operando na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
aux.add(this.LeituraEntrada);
isOp=false;
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
}
}
LeituraSimbolos.ungetSimbol();
}
private boolean isValid(int a){
return(a== ContantesDaLinguagem.T_IDENTIFIER ||
a== ContantesDaLinguagem.T_CONSTANT ||
a== ContantesDaLinguagem.RELOP ||
a== ContantesDaLinguagem.ADDOP ||
a== ContantesDaLinguagem.MULOP ||
a== ContantesDaLinguagem.UNOP||
a== ContantesDaLinguagem.POWOP||
a== ContantesDaLinguagem.RELOP||
a== ContantesDaLinguagem.ABREPAR||
a== ContantesDaLinguagem.FECHAPAR);
}
private Comando trataEndWhile(){
return new ComandoEndWhile();
}
private Comando trataEndIf(){
return new ComandoEndIf();
}
private Comando trataElse(){
return new ComandoElse();
}
private Comando trataFor(){
LeituraSimbolos.usarUltimoSimbolo=false;
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
if(this.LeituraEntrada.getToken()!=ContantesDaLinguagem.ABREPAR){
throw new FalhaErroDeSintaxe("Era esperado '(' logo apos 'for' na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
Comando atrib = getComando(this.LeituraEntrada.getToken());
Lista<SimbolosCefetiny> condicao = new Lista();
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
if(this.LeituraEntrada.getToken()!=ContantesDaLinguagem.SEMICOLON){
throw new FalhaErroDeSintaxe("Era esperado um ; entre a atribuicao e a condicao do 'for' na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
getExpressao(condicao);
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
if(this.LeituraEntrada.getToken()!=ContantesDaLinguagem.SEMICOLON){
throw new FalhaErroDeSintaxe("Era esperado um ; entre a condicao e o incremento do 'for' na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
Comando inc = getComando(this.LeituraEntrada.getToken());
Lista<Comando> cmds = new Lista();
while(this.LeituraEntrada.getToken()!= ContantesDaLinguagem.ENDFOR){
cmds.add(getComando(this.LeituraEntrada.getToken()));
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
}
return new ComandoFor(condicao,cmds,inc,atrib);
}
private Comando trataWhile(){
LeituraSimbolos.usarUltimoSimbolo=false;
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
if(this.LeituraEntrada.getToken()!=ContantesDaLinguagem.ABREPAR){
throw new FalhaErroDeSintaxe("Era esperado '(' logo apos 'while' na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
Lista<SimbolosCefetiny> expressao = new Lista();
getExpressao(expressao);
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
if(!this.LeituraEntrada.getLexema().equals("do")){
throw new FalhaErroDeSintaxe("Era esperado 'do' logo apos a expressao do while na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
Lista<Comando> comandos = new Lista();
while(this.LeituraEntrada.getToken()!= ContantesDaLinguagem.ENDWHILE){
comandos.add(getComando(this.LeituraEntrada.getToken()));
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
}
return new ComandoWhile(expressao,comandos);
}
private Comando trataIf(){
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
if(this.LeituraEntrada.getToken()!=ContantesDaLinguagem.ABREPAR){
throw new FalhaErroDeSintaxe("Era esperado '(' logo apos 'if' na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
Lista<SimbolosCefetiny> expressao = new Lista();
getExpressao(expressao);
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
if(!this.LeituraEntrada.getLexema().equals("then")){
throw new FalhaErroDeSintaxe("Era esperado 'then' logo apos a expressao do if na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
Lista<Comando> comandos = new Lista();
while(this.LeituraEntrada.getToken()!= ContantesDaLinguagem.ENDIF){
comandos.add(getComando(this.LeituraEntrada.getToken()));
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
}
return new ComandoIf(expressao,comandos);
}
private Comando trataComandoReadInt(){
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
if (this.LeituraEntrada.getToken() != ContantesDaLinguagem.ABREPAR) {
throw new FalhaErroDeSintaxe("Era esperado um ( depois de 'readint' na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
this.LeituraEntrada =this.LeituraSimbolos.obterSimbolo();
if (this.LeituraEntrada.getToken() != ContantesDaLinguagem.T_IDENTIFIER) {
throw new FalhaErroDeSintaxe("O comando readint so aceita variaveis(linha "
+ this.LeituraSimbolos.getNumeroDaLinha() + ")");
}
String aux = this.LeituraEntrada.getLexema();
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
if (this.LeituraEntrada.getToken() != ContantesDaLinguagem.FECHAPAR) {
throw new FalhaErroDeSintaxe("Era esperado um ) depois de \"" + aux + "\" na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
return new ComandoReadInt(aux);
}
private Comando trataComandoPrint(){
LeituraSimbolos.usarUltimoSimbolo=false;
this.LeituraEntrada =this.LeituraSimbolos.obterSimbolo();
if (this.LeituraEntrada.getToken() != ContantesDaLinguagem.ABREPAR) {
throw new FalhaErroDeSintaxe("Era esperado um ( depois de print na linha "
+ this.LeituraSimbolos.getNumeroDaLinha());
}
this.LeituraEntrada = this.LeituraSimbolos.obterSimbolo();
Lista<SimbolosCefetiny> expressao = new Lista();
getExpressao(expressao);
return new ComandoPrint(expressao);
}
private Comando trataComandoEnd() {
return new ComandoEnd();
}
private Comando trataComandoPrintln() {
return new ComandoPrintln();
}
private void executa() {
for(Comando comando: this.LeituraComandos)
comando.executa();
}
} |
package com.simha.SpringOAuth2Demo2Example;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SecureController {
@RequestMapping("/")
public String test(OAuth2AuthenticationToken token)
{
OAuth2User pri = token.getPrincipal();
System.out.println(token.getName());
System.out.println(token.getCredentials());
return "secure.html";
}
}
|
package com.porsche.sell.logger;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 日志框架测试类
*
* @author XuHao
* Email 15229357319@sina.cn
* create on 2018/7/31
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class LoggerTest {
@Test
public void test1() {
String name = "XuHao";
String password = "123456";
log.debug("===============debug=============");
log.info("name: " + name + ", password: " + password);
// 使用{}占位符写法
log.info("name:{}, password:{}", name, password);
log.error("===============error=============");
log.warn("===============warn=============");
log.warn("===============warn=============");
log.warn("===============warn=============");
}
}
|
package ua.lviv.iot.uklon.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ua.lviv.iot.uklon.domain.OrderType;
import ua.lviv.iot.uklon.repository.OrderTypeRepository;
@Service
public class OrderTypeService extends AbstractService<OrderType> {
@Autowired
public OrderTypeService(OrderTypeRepository repository) {
super(repository);
}
} |
package napps.com.nearbycoffee;
import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* Created by "nithesh" on 7/15/2017.
*/
/*
We group the creation of singleton instances into one group to make sure that they are related.
Application module has application instance which gives context, which can be useful in instantiating sharedpreferences, system services
or any singleton classes that depend on context.
Make sure all the interdependent objects in the dependency/object graph are all created in one interface class.
The SharedPreferences was actually present in the NetworkModule which makes irrelevant given the type of objects created
in network module class. So it was moved here to have corresponding dependencies.
*/
@Module
public class AppModule {
private BaseApplication baseApplication;
public AppModule(BaseApplication baseApplication){
this.baseApplication = baseApplication;
}
@Provides
@Singleton
BaseApplication providesApplication(){
return baseApplication;
}
}
|
package com.tencent.mm.plugin.wallet_core.model;
public final class c {
public String lMW;
public String plH;
}
|
package com.marcotte.inheritance_balls;
import java.awt.Dimension;
import javax.swing.*;
public class Launcher {
public static void main(String[] args)
{
// launch our application
SwingUtilities.invokeLater( new Runnable() {
@Override
public void run()
{
// launch the main form
BallTestFrame app = new BallTestFrame("My Cool JFrame");
app.setPreferredSize(new Dimension(400,400));
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.pack();
app.setLocationRelativeTo(null);
app.setVisible(true);
}});
}
}
|
package com.incuube.bot.util;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class DateUserDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
long timestamp = jsonParser.getLongValue();
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.of("Z"));
}
}
|
package com.designPattern.behavioral.observer;
public interface Subject {
public void addObserver(Observer observer);
public void removeObserver(Observer observer);
public void updateAndNotify(String message);
} |
import java.util.Scanner;
public class PokemonMaster {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(); //포켓몬개수(1~100,000)
int M = sc.nextInt(); //맞춰야할문제수
String name, findName;
int num, findNum;
MyHashMap hmap = new MyHashMap();
//입력받아서 해시맵 만들기
for(int i = 1; i <= N; i++){
name = sc.next();
hmap.pushItem(name, i);
}
//문제답하기
for(int i = 0; i < M; i++){
name = sc.next();
//입력이 숫자일 경우
if(name.charAt(0) < 58 && 47<name.charAt(0)){
num = Integer.parseInt(name);
findName = hmap.findName(num);
System.out.println(findName);
}
//입력이 포켓몬 이름(문자열)일 경우
else{
findNum = hmap.findNumber(name);
System.out.println(findNum);
}
}//end for
}//end main
}
|
package cn.fuego.misp.webservice.up.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import cn.fuego.misp.webservice.json.MispBaseReqJson;
import cn.fuego.misp.webservice.json.MispBaseRspJson;
import cn.fuego.misp.webservice.up.model.LoginRsp;
import cn.fuego.misp.webservice.up.model.ModifyPwdReq;
import cn.fuego.misp.webservice.up.model.ModifyPwdRsp;
/**
*
* @ClassName: UserManageService
* @Description: TODO
* @author Tang Jun
* @date 2014-10-20 上午10:53:45
*
*/
@Path("/index.php")
@Produces("application/json")
@Consumes("application/json")
public interface MispUserManageRest
{
//APP登录验证
@POST
@Path("/Index/Login")
LoginRsp login(MispBaseReqJson req);
//APP退出
@POST
@Path("/Index/Logout")
LoginRsp logout(MispBaseReqJson req);
//APP修改密码
@POST
@Path("/Index/ModifyPassword")
ModifyPwdRsp modifyPassword(ModifyPwdReq req);
@POST
@Path("/Index/Register")
MispBaseRspJson register(MispBaseReqJson req);
@POST
@Path("/Index/ResetPassword")
MispBaseRspJson resetPassword(MispBaseReqJson req);
//短信发送验证码
@POST
@Path("/MispUtil/SendVerifyCode")
MispBaseRspJson sendVerifyCode(MispBaseReqJson req);
}
|
package kthsmallest;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Solution {
public int kthSmallest(int[] A, int [] B, int k) {
// aldx, bldx represents the xth element of the A or B
int a = A.length;
int b = B.length;
PriorityQueue <Cell> minheap = new PriorityQueue <Cell>(k, new Comparator<Cell>(){
@Override
public int compare(Cell c1, Cell c2) {
// TODO Auto-generated method stub
// use equals to
int sum1 = c1.aldx + c1.bldx;
int sum2 = c2.aldx + c2.bldx;
if(sum1 == sum2){
return 0;
}
return sum1 > sum2 ? 1 : -1;
}
});
// generated node to be true, 防止被再次取出
boolean [][] visited = new boolean [A.length][B.length];
minheap.offer(new Cell(0,0));
visited [0][0] = true;
for(int i=0; i<k-1; i++){
Cell cur = minheap.poll();
//base case:没有出界,没有被generated过!!!
if (cur.aldx < A.length && !visited[cur.aldx+1][cur.bldx]){
minheap.offer(new Cell(cur.aldx+1,cur.bldx));
visited[cur.aldx+1][cur.bldx]=true;
}
if (cur.bldx+1 < B.length && !visited[cur.aldx][cur.bldx+1]){
minheap.offer(new Cell(cur.aldx,cur.bldx+1));
visited[cur.aldx][cur.bldx+1]=true;
}
}
Cell p = minheap.peek();
return A[p.aldx]+B[p.bldx];
}
class Cell{
int aldx;
int bldx;
Cell(int aldx,int bldx){
this.aldx = aldx;
this.bldx = bldx;
}
}
} |
package Computer;
public interface Cpu {
String getPinPai();
double getZhuPin();
}
|
package br.com.finalcraft.gppskyblock.commands;
import br.com.finalcraft.evernifecore.FCBukkitUtil;
import br.com.finalcraft.evernifecore.argumento.MultiArgumentos;
import br.com.finalcraft.evernifecore.config.playerdata.PlayerController;
import br.com.finalcraft.evernifecore.config.playerdata.PlayerData;
import br.com.finalcraft.evernifecore.cooldown.Cooldown;
import br.com.finalcraft.evernifecore.fancytext.FancyText;
import br.com.finalcraft.gppskyblock.GPPSkyBlock;
import br.com.finalcraft.gppskyblock.Island;
import br.com.finalcraft.gppskyblock.Utils;
import net.kaikk.mc.gpp.Claim;
import net.kaikk.mc.gpp.ClaimPermission;
import net.kaikk.mc.gpp.GriefPreventionPlus;
import net.kaikk.mc.gpp.events.ClaimDeleteEvent;
import br.com.finalcraft.gppskyblock.PermissionNodes;
import br.com.finalcraft.gppskyblock.bossshop.BSPHook;
import br.com.finalcraft.gppskyblock.tasks.SpawnTeleportTask;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.block.Biome;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class CMDIsland implements CommandExecutor {
private Map<String,String> confirmations = new HashMap<String,String>();
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
// Passando os argumentos para um ArrayList
MultiArgumentos argumentos = FCBukkitUtil.parseBukkitArgsToMultiArgumentos(args);
switch (argumentos.get(0).toLowerCase()){
case "":
case "?":
case "help":
return help(label,sender,argumentos);
case "spawn":
case "home":
case "tp":
return spawn(label,sender,argumentos);
case "setspawn":
return setspawn(label,sender,argumentos);
case "biomelist":
return biomelist(label,sender,argumentos);
case "setbiome":
return setbiome(label,sender,argumentos);
case "private":
return privatec(label,sender,argumentos);
case "public":
return publicc(label,sender,argumentos);
case "reset":
return reset(label,sender,argumentos);
case "delete":
return delete(label,sender,argumentos);
case "setraio":
return setraio(label,sender,argumentos);
case "reload":
return reload(label,sender,argumentos);
}
sender.sendMessage("&cErro de parametros, por favor use /" + label + " help");
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------//
// Command Help
// -----------------------------------------------------------------------------------------------------------------------------//
public boolean help(String label, CommandSender sender, MultiArgumentos argumentos){
if (argumentos.get(0).isEmpty() && sender instanceof Player && BSPHook.isEnabled()){
Player player = (Player) sender;
BSPHook.openShop(player,"islands");
return true;
}
sender.sendMessage("§6§m------------§6( §a§lGPPSkyBlock§e §6)§m------------");
FancyText.sendTo(sender, new FancyText("§3§l ▶ §a/" + label + " help","§bMostra essa mensagem!","/" + label + " help",true));
FancyText.sendTo(sender, new FancyText("§3§l ▶ §a/" + label + " spawn [Player]","§bTeleporta para a sua ilha ou a de algum jogador!","/" + label + " spawn",true));
FancyText.sendTo(sender, new FancyText("§3§l ▶ §a/" + label + " setspawn","§bAltera a localização do Spawn da sua ilha!","/" + label + " setspawn",true));
FancyText.sendTo(sender, new FancyText("§3§l ▶ §a/" + label + " private","§bDeixa a sua ilha Privada!","/" + label + " private",true));
FancyText.sendTo(sender, new FancyText("§3§l ▶ §a/" + label + " public","§bDeixa a sua ilha Pública!","/" + label + " public",true));
FancyText.sendTo(sender, new FancyText("§3§l ▶ §a/" + label + " reset","§bReseta a sua ilha!(Apaga ela inteira!!!)","/" + label + " reset",true));
if (sender.hasPermission(PermissionNodes.COMMAND_SETRADIUS))
FancyText.sendTo(sender, new FancyText("§6§l ▶ §e/" + label + " setraio <Player> <Raio>","§bAltera o tamanho do raio da ilha!","/" + label + " setraio",true));
if (sender.hasPermission(PermissionNodes.COMMAND_SETBIOME)) {
FancyText.sendTo(sender, new FancyText("§3§l ▶ §b/" + label + " biomelist","§bMostra os possíveis biomas!","/" + label + " biomelist",true));
if (sender.hasPermission(PermissionNodes.COMMAND_SETBIOME_OTHER)){
FancyText.sendTo(sender, new FancyText("§3§l ▶ §b/" + label + " setbiome <Bioma> [Player]","§bDefine o bioma de toda a sua ilha!","/" + label + " setbiome ",true));
}else {
FancyText.sendTo(sender, new FancyText("§3§l ▶ §b/" + label + " setbiome <Bioma>","§bDefine o bioma de toda a sua ilha!","/" + label + " setbiome ",true));
}
}
if (sender.hasPermission("be.evernife")){
FancyText.sendTo(sender, new FancyText("§5§l ▶ §6/" + label + " delete <Player>","§bDeleta a ilha de algum jogador!\n\nNá pratica nao deleta fisicamente, apenas remove o claim!\nFazendo com que ele tenha que criar uma nova ilha em outro lugar.","/" + label + " biomelist",true));
}
sender.sendMessage("");
sender.sendMessage("§3§oPasse o mouse em cima dos comandos para ver a descrição!");
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------//
// Command spawn
// -----------------------------------------------------------------------------------------------------------------------------//
public boolean spawn(String label, CommandSender sender, MultiArgumentos argumentos){
if (FCBukkitUtil.isNotPlayer(sender)) {
return false;
}
Player thePlayer = (Player) sender;
Island island = null;
if (!argumentos.get(1).isEmpty()){
PlayerData playerData = argumentos.get(1).getPlayerData();
if (playerData == null){
sender.sendMessage("§4§l ▶ §cNão existem nenhum jogador chamado [" + argumentos.get(1) + "] !");
return true;
}
island = GPPSkyBlock.getInstance().getDataStore().getIsland(playerData.getUniqueId());
if (island == null) {
sender.sendMessage("§4§l ▶ §e" + playerData.getPlayerName() + "§c não possui uma ilha nesse servidor!");
return false;
}
if (island.getClaim().canEnter(thePlayer) != null) {
sender.sendMessage("§4§l ▶ §c Você não tem permissão para entrar nessa ilha!");
return false;
}
}else {
island = GPPSkyBlock.getInstance().getDataStore().getIsland(thePlayer.getUniqueId());
if (island==null) {
// this player doesn't have an island yet... so create a new island
try {
island = GPPSkyBlock.getInstance().getDataStore().createIsland(thePlayer.getUniqueId());
} catch (Exception e) {
sender.sendMessage(ChatColor.RED+ "Um erro ocorreu ao gerar sua ilha: " + e.getMessage());
e.printStackTrace();
return false;
}
return true;
}
}
if (!island.ready) {
sender.sendMessage("§4§l ▶ §cExiste alguma operação pendente nessa ilha!");
return false;
}
if (thePlayer.hasPermission("gppskyblock.nowarpup")){
sender.sendMessage("§3§l ▶ §aVocê foi teleportado para a ilha!");
SpawnTeleportTask.teleportTask(thePlayer, island, 0);
}else {
sender.sendMessage("§3§l ▶ §aVocê será teleportado em " + GPPSkyBlock.getInstance().config().tpCountdown + " segundos!");
SpawnTeleportTask.teleportTask(thePlayer, island, GPPSkyBlock.getInstance().config().tpCountdown);
}
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------//
// Command setspawn
// -----------------------------------------------------------------------------------------------------------------------------//
public boolean setspawn(String label, CommandSender sender, MultiArgumentos argumentos){
if (FCBukkitUtil.isNotPlayer(sender)) {
return false;
}
Player thePlayer = (Player) sender;
sender.sendMessage(ChatColor.RED + "ATENÇAO: Certifique-se de usar blocos inteiros para o spawn de sua ilha! Não use escadas ou lajes!");
Island island = GPPSkyBlock.getInstance().getDataStore().getIsland(thePlayer.getUniqueId());
if (island == null) {
sender.sendMessage("§4§l ▶ §cVocê ainda não possui uma ilha nesse servidor! Para criar uma, use \"/"+label+" spawn\"");
return false;
}
if (!island.getClaim().contains(thePlayer.getLocation(), true, false)) {
sender.sendMessage("§4§l ▶ §cVocê precisa estar dentro da sa ilha para usar esse comando!");
return false;
}
if (!island.ready) {
sender.sendMessage("§4§l ▶ §cExiste alguma operação pendente nessa ilha!");
return false;
}
try {
island.setSpawn(thePlayer.getLocation().add(0, 2, 0));
sender.sendMessage("§3§l ▶ §aSpawn da ilha definido com sucesso!");
} catch (SQLException e) {
e.printStackTrace();
sender.sendMessage(ChatColor.RED+"An error occurred while creating the island: data store issue.");
return false;
}
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------//
// Command biomelist
// -----------------------------------------------------------------------------------------------------------------------------//
public boolean biomelist(String label, CommandSender sender, MultiArgumentos argumentos){
StringBuilder sb = new StringBuilder(ChatColor.GOLD + "Biome list: " + ChatColor.AQUA);
if (GPPSkyBlock.getInstance().config().allowedBiomes.isEmpty()) {
sb.append(ChatColor.RED+"Nenhuma");
} else {
for (Biome biome : GPPSkyBlock.getInstance().config().allowedBiomes) {
if(!sender.hasPermission("gppskyblock.setbiome."+biome.toString())) {
continue;
}
sb.append(Utils.fromSnakeToCamelCase(biome.toString()));
sb.append(", ");
}
}
sender.sendMessage(sb.substring(0, sb.length()-2).toString());
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------//
// Command setbiome
// -----------------------------------------------------------------------------------------------------------------------------//
public boolean setbiome(String label, CommandSender sender, MultiArgumentos argumentos){
if ( !FCBukkitUtil.hasThePermission(sender,PermissionNodes.COMMAND_SETBIOME)){
return true;
}
PlayerData playerData;
if (sender.hasPermission(PermissionNodes.COMMAND_SETBIOME_OTHER) && !argumentos.get(2).isEmpty()){
playerData = argumentos.get(2).getPlayerData();
if (playerData == null){
sender.sendMessage("§4§l ▶ §cNão existem nenhum jogador chamado [" + argumentos.get(1) + "] !");
return true;
}
}else {
if ( !(sender instanceof Player) ){
FancyText.sendTo(sender, new FancyText("§3§l ▶ §b/" + label + " setbiome <Bioma> [Player]","§bDefine o bioma de toda a sua ilha!","/" + label + " setbiome ",true));
return true;
}
playerData = PlayerController.getPlayerData((Player) sender);
}
Biome biome = Utils.matchAllowedBiome(argumentos.get(1).toString());
if (biome == null) {
sender.sendMessage("§4§l ▶ §cNão existe nenhum bioma chamado §e" + argumentos.get(1) + ". Use /" + label + " biomelist");
return true;
}
if (!sender.hasPermission("gppskyblock.setbiome.all") && !FCBukkitUtil.hasThePermission(sender,"gppskyblock.setbiome." + argumentos.get(1).toLowerCase())){
return true;
}
Island island = GPPSkyBlock.getInstance().getDataStore().getIsland(playerData.getUniqueId());
if (island == null) {
sender.sendMessage("§4§l ▶ §e" + playerData.getPlayerName() + "§c não possui uma ilha nesse servidor!");
return false;
}
if (!island.ready) {
sender.sendMessage("§4§l ▶ §cExiste alguma operação pendente nessa ilha!");
return false;
}
island.setIslandBiome(biome);
sender.sendMessage("§3§l ▶ §aBioma alterado! Você vai precisar deslogar e logar para ver a diferença!");
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------//
// Command privatec
// -----------------------------------------------------------------------------------------------------------------------------//
public boolean privatec(String label, CommandSender sender, MultiArgumentos argumentos){
if (FCBukkitUtil.isNotPlayer(sender)){
return true;
}
Player player = (Player) sender;
Island island = GPPSkyBlock.getInstance().getDataStore().getIsland(player.getUniqueId());
if (island == null) {
sender.sendMessage("§4§l ▶ §cVocê ainda não possui uma ilha nesse servidor! Para criar uma, use \"/"+label+" spawn\"");
return false;
}
Claim claim = island.getClaim();
claim.setPermission(player.getUniqueId(), ClaimPermission.ENTRY);
claim.dropPermission(GriefPreventionPlus.UUID0);
sender.sendMessage("§6§l ▶ §eSua ilha está §9§lPrivada!");
sender.sendMessage("§7§oOu seja, apenas jogadores com §n/entrytrust §7podem entrar nela!");
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------//
// Command publicc
// -----------------------------------------------------------------------------------------------------------------------------//
public boolean publicc(String label, CommandSender sender, MultiArgumentos argumentos){
if (FCBukkitUtil.isNotPlayer(sender)){
return true;
}
Player player = (Player) sender;
Island island = GPPSkyBlock.getInstance().getDataStore().getIsland(player.getUniqueId());
if (island == null) {
sender.sendMessage("§4§l ▶ §cVocê ainda não possui uma ilha nesse servidor! Para criar uma, use \"/"+label+" spawn\"");
return false;
}
Claim claim = island.getClaim();
claim.dropPermission(player.getUniqueId());
claim.setPermission(GriefPreventionPlus.UUID0, ClaimPermission.ENTRY);
sender.sendMessage("§6§l ▶ §eSua ilha está §a§lPublica!");
sender.sendMessage("§7§oOu seja, qualquer um pode entrar nela!");
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------//
// Command reset
// -----------------------------------------------------------------------------------------------------------------------------//
public boolean reset(String label, CommandSender sender, MultiArgumentos argumentos){
if (FCBukkitUtil.isNotPlayer(sender)){
return true;
}
Player player = (Player) sender;
Island island = GPPSkyBlock.getInstance().getDataStore().getIsland(player.getUniqueId());
if (island == null) {
sender.sendMessage("§4§l ▶ §cVocê ainda não possui uma ilha nesse servidor! Para criar uma, use \"/"+label+" spawn\"");
return false;
}
if (!island.ready) {
sender.sendMessage("§4§l ▶ §cExiste alguma operação pendente nessa ilha!");
return false;
}
String conf = confirmations.remove(player.getName());
if (conf == null || !conf.equals("reset")) {
sender.sendMessage("§4§l ▶ §c§lCUIDADO: §cSua ilha inteira será APAGADA!\n§cSe você tem certeza disso, use \"/"+label+" reset\" novamente!");
this.confirmations.put(player.getName(), "reset");
return false;
}
Cooldown cooldown = Cooldown.getOrCreateCooldown("GPPSkyBlock-ISRESET",player.getName());
if (cooldown.isInCooldown()){
cooldown.warnPlayer(sender);
return true;
}
cooldown.setPermaCooldown(true);
cooldown.startWith(259200);//3 Dias
island.reset();
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------//
// Command delete
// -----------------------------------------------------------------------------------------------------------------------------//
public boolean delete(String label, CommandSender sender, MultiArgumentos argumentos){
if (!FCBukkitUtil.hasThePermission(sender,PermissionNodes.COMMAND_DELETE_OTHER)){
return true;
}
PlayerData playerData = argumentos.get(1).getPlayerData();
if (playerData == null){
sender.sendMessage("§4§l ▶ §cNão existem nenhum jogador chamado [" + argumentos.get(1) + "] !");
return true;
}
Island island = GPPSkyBlock.getInstance().getDataStore().getIsland(playerData.getUniqueId());
if (island == null) {
sender.sendMessage("§4§l ▶ §e" + playerData.getPlayerName() + "§c não possui uma ilha nesse servidor!");
return true;
}
if (!island.ready) {
if (!argumentos.getFlag("-force").isSet()){
sender.sendMessage("§4§l ▶ §cExiste alguma operação pendente nessa ilha!");
return true;
}else {
island.ready = true;
}
}
ClaimDeleteEvent event = new ClaimDeleteEvent(island.getClaim(), (sender instanceof Player ? (Player) sender : null) , ClaimDeleteEvent.Reason.DELETE);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
sender.sendMessage("§4§l ▶ §cEssa ilha não pode ser deletada!");
return true;
}
sender.sendMessage("§2§l ▶ §aIlha deletada com sucesso!");
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------//
// Command setraio
// -----------------------------------------------------------------------------------------------------------------------------//
public boolean setraio(String label, CommandSender sender, MultiArgumentos argumentos){
if (!FCBukkitUtil.hasThePermission(sender,PermissionNodes.COMMAND_SETRADIUS)) {
return true;
}
if (argumentos.get(1).isEmpty() || argumentos.get(2).isEmpty()){
FancyText.sendTo(sender, new FancyText("§6§l ▶ §e/" + label + " setraio <Player> <Raio>","§bAltera o tamanho do raio da ilha!","/" + label + " setraio",true));
return true;
}
PlayerData playerData = argumentos.get(1).getPlayerData();
if (playerData == null){
sender.sendMessage("§4§l ▶ §cNão existem nenhum jogador chamado [" + argumentos.get(1) + "] !");
return true;
}
Island island = GPPSkyBlock.getInstance().getDataStore().getIsland(playerData.getUniqueId());
if (island == null) {
sender.sendMessage("§4§l ▶ §e" + playerData.getPlayerName() + "§c não possui uma ilha nesse servidor!");
return true;
}
if (!island.ready) {
sender.sendMessage("§4§l ▶ §cExiste alguma operação pendente nessa ilha!");
return true;
}
Integer newRadius = argumentos.get(2).getInteger();
if (newRadius == null ){
sender.sendMessage("§4§l ▶ §c[" + argumentos.get(2) + "] deve ser um número inteiro positivo menor que 254!");
return true;
}
if (newRadius > 254 || newRadius < 2){
sender.sendMessage("§4§l ▶ §cO novo tamanho da ilha deve ser menor que 254!");
return true;
}
island.setRadius(newRadius);
sender.sendMessage("§3§l ▶ §aO novo raio da ilha foi definido para " + newRadius + " blocos de distancia!");
return true;
}
// -----------------------------------------------------------------------------------------------------------------------------//
// Command Reload
// -----------------------------------------------------------------------------------------------------------------------------//
public boolean reload(String label, CommandSender sender, MultiArgumentos argumentos){
if ( !FCBukkitUtil.hasThePermission(sender,PermissionNodes.COMMAND_RELOAD)){
return true;
}
sender.sendMessage("§aEsse plugin não pode ser recarregado!");
return true;
}
}
|
package com.travelportal.domain;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
@Entity
@Table(name="billing_information")
public class BillingInformation {
@Column(name="id")
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name="invoice_to_hotel")
private String invoiceToHotel;
@Column(name="Bankservice")
private String bankservice;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="title")
private String title;
@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private Salutation salutationCode;
@Column(name="email_addr")
private String emailAddr;
@Column(name="tel_no")
private int telNo;
@Column(name="tel_no_code")
private int telNoCode;
@Column(name="fax_no")
private int faxNo;
@Column(name="fax_no_code")
private int faxNoCode;
@Column(name="ext")
private int ext;
@Column(name="bank_name")
public String bankName;
@Column(name="account_no")
public Long accountNo;
@Column(name="account_type")
public String accountType;
@Column(name="Branch_name")
public String branchName;
@Column(name="swift_code")
public String swiftCode;
private int mainContactPhoneNo;
private long supplier_code;
/**
* @return the invoiceToHotel
*/
public long getSupplierCode() {
return supplier_code;
}
public void setSupplierCode(long supplier_code) {
this.supplier_code = supplier_code;
}
public String getInvoiceToHotel() {
return invoiceToHotel;
}
public void setInvoiceToHotel(String invoiceToHotel) {
this.invoiceToHotel = invoiceToHotel;
}
public String getBankservice() {
return bankservice;
}
public void setBankservice(String bankservice) {
this.bankservice = bankservice;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the emailAddr
*/
public String getEmailAddr() {
return emailAddr;
}
/**
* @param emailAddr the emailAddr to set
*/
public void setEmailAddr(String emailAddr) {
this.emailAddr = emailAddr;
}
/**
* @return the telNo
*/
public int getTelNo() {
return telNo;
}
/**
* @param telNo the telNo to set
*/
public void setTelNo(int telNo) {
this.telNo = telNo;
}
/**
* @return the faxNo
*/
public int getFaxNo() {
return faxNo;
}
/**
* @param faxNo the faxNo to set
*/
public void setFaxNo(int faxNo) {
this.faxNo = faxNo;
}
public int getTelNoCode() {
return telNoCode;
}
public void setTelNoCode(int telNoCode) {
this.telNoCode = telNoCode;
}
public int getFaxNoCode() {
return faxNoCode;
}
public void setFaxNoCode(int faxNoCode) {
this.faxNoCode = faxNoCode;
}
/**
* @return the ext
*/
public int getExt() {
return ext;
}
/**
* @param ext the ext to set
*/
public void setExt(int ext) {
this.ext = ext;
}
public Salutation getSalutationCode() {
return salutationCode;
}
public void setSalutationCode(Salutation salutationCode) {
this.salutationCode = salutationCode;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public Long getAccountNo() {
return accountNo;
}
public void setAccountNo(Long accountNo) {
this.accountNo = accountNo;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getBranchName() {
return branchName;
}
public void setBranchName(String branchName) {
this.branchName = branchName;
}
public String getSwiftCode() {
return swiftCode;
}
public void setSwiftCode(String swiftCode) {
this.swiftCode = swiftCode;
}
public static BillingInformation findById(long id) {
try
{
return (BillingInformation) JPA.em().createQuery("select c from BillingInformation c where c.supplier_code = ?1").setParameter(1, id).getSingleResult();
}
catch(Exception ex){
ex.printStackTrace();
return null;
}
}
@Transactional
public void save() {
JPA.em().persist(this);
JPA.em().flush();
}
@Transactional
public void delete() {
JPA.em().remove(this);
}
@Transactional
public void merge() {
JPA.em().merge(this);
}
@Transactional
public void refresh() {
JPA.em().refresh(this);
}
public int getMainContactPhoneNo() {
return mainContactPhoneNo;
}
public void setMainContactPhoneNo(int mainContactPhoneNo) {
this.mainContactPhoneNo = mainContactPhoneNo;
}
}
|
/*
* 文 件 名: UploadStaticConstant.java
* 描 述: UploadStaticConstant.java
* 时 间: 2013-7-1
*/
package com.babyshow.upload;
/**
* <一句话功能简述>
*
* @author ztc
* @version [BABYSHOW V1R1C1, 2013-7-1]
*/
public interface UploadStaticConstant
{
public static final int IMAGE_UPLOAD_STATUS_INIT = 0;
public static final String FILELIST_SESSION_STRING = "fileList";
/**
* 上传路径,位于"webapp/{工程}/upload"文件夹下
*/
public static final String UPLOAD_PATH = "/upload";
/**
* 分割符
*/
public static final String SEPARATOR = "/";
/**
* jquery删除已上传图片回调方法类型
*/
public static final String DELETE_TYPE = "DELETE";
/**
* 删除地址
*/
public static final String DELETE_URL = "../upload/";
/**
* 用户代码
*/
public static final String PARAM_USERCODE = "usercode";
/**
* 年月日
*/
public static final String PARAM_DATETIME = "datetime";
/**
* 小时、分钟
*/
public static final String PARAM_HOURTIME = "hourtime";
/**
* 喜欢次数
*/
public static final String PARAM_LIKETIMES = "liketimes";
/**
* 照片描述
*/
public static final String PARAM_DESCRIPTION = "descritpion";
}
|
package com.mideas.rpg.v2.callback.old;
/*package com.mideas.rpg.v2.callback;
public class GuildMotdCallback implements Callback {
@Override
public void handleCallback(Object ...obj) {
}
}*/
|
package presentacion.vistas.gui;
import presentacion.eventos.EventosMenu;
import presentacion.vistas.Empleado.VistaEmpleado;
import presentacion.vistas.Material.VistaMaterial;
import presentacion.vistas.cliente.VistaCliente;
import presentacion.vistas.departamento.VistaDepartamento;
import presentacion.vistas.editorial.VistaEditorial;
import presentacion.vistas.factura.VistaFactura;
import presentacion.vistas.libreria.VistaLibreria;
import presentacion.vistas.libro.VistaLibro;
import presentacion.vistas.menu.VistaMenu;
/**
* The Class FactoriaVistaPrincipalImp.
*/
public class FactoriaVistaPrincipalImp extends FactoriaVistaPrincipal {
/*
* (non-Javadoc)
*
* @see presentacion.vistas.gui.FactoriaVistaPrincipal#generarVista(int)
*/
@Override
public VistaPrincipal generarVista(final int evento) {
VistaPrincipal vistaPrincipal = null;
switch (evento) {
case EventosMenu.MOSTRAR_MENU_VISTA:
vistaPrincipal = new VistaMenu();
break;
case EventosMenu.MOSTRAR_CLIENTE_VISTA:
vistaPrincipal = new VistaCliente();
break;
case EventosMenu.MOSTRAR_EDITORIAL_VISTA:
vistaPrincipal = new VistaEditorial();
break;
case EventosMenu.MOSTRAR_LIBRO_VISTA:
vistaPrincipal = new VistaLibro();
break;
case EventosMenu.MOSTRAR_FACTURA_VISTA:
vistaPrincipal = new VistaFactura();
break;
case EventosMenu.MOSTRAR_EMPLEADO_VISTA:
vistaPrincipal = new VistaEmpleado();
break;
case EventosMenu.MOSTRAR_DEPARTAMENTO_VISTA:
vistaPrincipal = new VistaDepartamento();
break;
case EventosMenu.MOSTRAR_MATERIAL_VISTA:
vistaPrincipal = new VistaMaterial();
break;
case EventosMenu.MOSTRAR_LIBRERIA_VISTA:
vistaPrincipal = new VistaLibreria();
break;
}
return vistaPrincipal;
}
}
|
package ru.itis.springboot.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.itis.springboot.models.RefreshToken;
import java.util.Optional;
/**
* created: 18-04-2021 - 20:56
* project: SpringBoot
*
* @author dinar
* @version v0.1
*/
public interface TokenRepository extends JpaRepository<RefreshToken, Long> {
Optional<RefreshToken> findByToken(String token);
Optional<RefreshToken> findByFingerprint(String fingerprint);
}
|
package com.ntxdev.zuptecnico.api.callbacks;
import com.ntxdev.zuptecnico.entities.InventoryItem;
/**
* Created by igorlira on 5/11/14.
*/
public interface InventoryItemPublishedListener {
public void onInventoryItemPublished(int itemId, InventoryItem item);
}
|
package interviews.no_phone;
public class Kamcord {
}
|
package org.motechproject.server.model.db.hibernate.rct;
import org.motechproject.server.model.db.hibernate.EnumUserType;
import org.motechproject.server.model.rct.PhoneOwnershipType;
public class PhoneOwnershipEnumType extends EnumUserType<PhoneOwnershipType> {
public PhoneOwnershipEnumType(){
super(PhoneOwnershipType.class);
}
}
|
package com.olfu.meis.fragment;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.olfu.meis.R;
import com.olfu.meis.model.EarthquakeItem2;
import com.olfu.meis.model.LocationItem;
import com.olfu.meis.utils.TimeHelper2;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import static com.olfu.meis.model.EarthquakeItem2.getList;
import static com.olfu.meis.model.LocationItem.latitude;
import static com.olfu.meis.model.LocationItem.longitude;
/**
* A simple {@link Fragment} subclass.
*/
public class FragmentMap extends SupportMapFragment
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnInfoWindowClickListener,
GoogleMap.OnMapLongClickListener,
GoogleMap.OnMapClickListener,
GoogleMap.OnMarkerClickListener {
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
private final int[] MAP_TYPES = {GoogleMap.MAP_TYPE_SATELLITE,
GoogleMap.MAP_TYPE_NORMAL,
GoogleMap.MAP_TYPE_HYBRID,
GoogleMap.MAP_TYPE_TERRAIN,
GoogleMap.MAP_TYPE_NONE};
private final int CURRENT_MAP_TYPE = 0;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
initListeners();
getMap().setMyLocationEnabled(true);
// Location myLocation = getMyLocation();
//
if (latitude != 0 & longitude != 0) {
//
double x = latitude;
double y = longitude;
CameraPosition position = CameraPosition.builder()
.target(new LatLng(x, y))
.zoom(15f)
.bearing(0.0f)
.tilt(0.0f)
.build();
getMap().animateCamera(CameraUpdateFactory
.newCameraPosition(position), null);
latitude = 0;
longitude = 0;
} else {
CameraPosition position = CameraPosition.builder()
.target(new LatLng(14.646902, 121.120458))
.zoom(13f)
.bearing(0.0f)
.tilt(0.0f)
.build();
getMap().animateCamera(CameraUpdateFactory
.newCameraPosition(position), null);
}
Log.d("ZXC", latitude + " : " + LocationItem.longitude);
setupMarkers();
}
private void setupMarkers() {
ArrayList<EarthquakeItem2> items = getList();
for (int ctr = 0; ctr < items.size(); ctr++) {
EarthquakeItem2 item = items.get(ctr);
LatLng position = new LatLng(item.getLatitude(), item.getLongitude());
Calendar calEQ = TimeHelper2.setTime(item.getTimeStamp());
String snippet = "M" + item.getMagnitude() + " - " + TimeHelper2.getTimeStamp(calEQ);
getMap().addMarker(new MarkerOptions()
.position(position)
.title(item.getLocation())
.snippet(snippet)
.icon(BitmapDescriptorFactory.fromBitmap(markerCreator(item.getMagnitude())))
);
}
if (latitude != 0 & LocationItem.longitude != 0) {
//
CameraPosition position = CameraPosition.builder()
.target(new LatLng(latitude, latitude))
.zoom(15f)
.bearing(0.0f)
.tilt(0.0f)
.build();
getMap().animateCamera(CameraUpdateFactory
.newCameraPosition(position), null);
latitude = 0;
LocationItem.longitude = 0;
}
}
private Bitmap markerCreator(double magnitude) {
int size = (int) (magnitude + 25) * 8;
BitmapDrawable bitmapdraw;
if (magnitude <= 4.0)
bitmapdraw = (BitmapDrawable) getResources().getDrawable(R.drawable.wave_moderate);
else
bitmapdraw = (BitmapDrawable) getResources().getDrawable(R.drawable.wave_heavy);
Bitmap b = bitmapdraw.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, size, size, false);
return smallMarker;
}
;
private void initListeners() {
getMap().setOnMarkerClickListener(this);
getMap().setOnMapLongClickListener(this);
getMap().setOnInfoWindowClickListener(this);
getMap().setOnMapClickListener(this);
}
@Override
public void onConnected(Bundle bundle) {
Log.d("Location", "onConnected");
mCurrentLocation = LocationServices
.FusedLocationApi
.getLastLocation(mGoogleApiClient);
initCamera(mCurrentLocation);
}
private void initCamera(Location location) {
CameraPosition position = CameraPosition.builder()
.target(new LatLng(location.getLatitude(),
location.getLongitude()))
.zoom(16f)
.bearing(0.0f)
.tilt(0.0f)
.build();
getMap().animateCamera(CameraUpdateFactory
.newCameraPosition(position), null);
getMap().setMapType(MAP_TYPES[CURRENT_MAP_TYPE]);
getMap().setTrafficEnabled(false);
getMap().getUiSettings().setZoomControlsEnabled(true);
}
@Override
public void onConnectionSuspended(int i) {
Log.d("Location", "Suspended");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("Location", "FAILED");
}
@Override
public void onInfoWindowClick(Marker marker) {
}
@Override
public void onMapClick(LatLng latLng) {
// MarkerOptions options = new MarkerOptions().position(latLng);
// options.title(getAddressFromLatLng(latLng));
//
// options.icon(BitmapDescriptorFactory.defaultMarker());
// getMap().addMarker(options);
}
@Override
public void onMapLongClick(LatLng latLng) {
// MarkerOptions options = new MarkerOptions().position(latLng);
// options.title(getAddressFromLatLng(latLng));
//
// options.icon(BitmapDescriptorFactory.fromBitmap(
// BitmapFactory.decodeResource(getResources(),
// R.mipmap.ic_launcher)));
//
// getMap().addMarker(options);
}
private String getAddressFromLatLng(LatLng latLng) {
Geocoder geocoder = new Geocoder(getActivity());
String address = "";
try {
address = geocoder
.getFromLocation(latLng.latitude, latLng.longitude, 1)
.get(0).getAddressLine(0);
} catch (IOException e) {
}
return address;
}
@Override
public boolean onMarkerClick(Marker marker) {
marker.showInfoWindow();
return true;
}
}
|
package com.tencent.mm.plugin.account.ui;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
class LoginUI$9 implements OnKeyListener {
final /* synthetic */ LoginUI eSk;
LoginUI$9(LoginUI loginUI) {
this.eSk = loginUI;
}
public final boolean onKey(View view, int i, KeyEvent keyEvent) {
if (66 != i || keyEvent.getAction() != 0) {
return false;
}
LoginUI.f(this.eSk);
return true;
}
}
|
package com.pgs.javadev.mainManu;
import com.pgs.javadev.interfaces.TreeDraw;
import com.pgs.javadev.treeDirectionDraw.*;
class DecisionMaker {
static TreeDraw TreeToDraw(String treeDirection, int treeSize) {
TreeDraw decisionTree;
switch (treeDirection) {
case "up":
decisionTree = new TreeUp(treeSize);
return decisionTree;
case "down":
decisionTree = new TreeDown(treeSize);
return decisionTree;
case "left":
decisionTree = new TreeLeft(treeSize);
return decisionTree;
case "right":
decisionTree = new TreeRight(treeSize);
return decisionTree;
default:
decisionTree = new TreeUp(treeSize);
return decisionTree;
}
}
} |
package model;
import java.util.ArrayList;
/**
* <b>Description of the Cell class</b> <br>
* Used as a cell of an evidence table. Offers functionality to add and retrieve
* values of a cell of an evidence table.
*
* @author Watnuss
*
*/
public class Cell {
private double probability;
private ArrayList<String> intersection;
/**
* <b>Description of Cell()</b><br>
* Constructor of Cell class.
*/
public Cell() {
intersection = new ArrayList<String>();
}
/**
* <b>Description of getProbability()</b><br>
* Gets the probability of this Cell.
*
* @return Probability
*/
public double getProbability() {
return probability;
}
/**
* <b>Description of setProbability(double probability)</b><br>
* Sets the probability of this Cell.
*
* @param probability
* Probability
*/
public void setProbability(double probability) {
this.probability = probability;
}
/**
* <b>Description of getIntersectionAsString()</b><br>
* Gets the intersection of this Cell. <br>
* <br>
* <b>!!! Care: For our use-case we only have single elemented sets. For
* more generic usage this class has to be adapted !!!</b><br>
*
* @return Intersection of this Cell as String
*/
public String getIntersectionAsString() {
if (intersection.isEmpty())
return " ";
else
// temporarily, as there is always just one element
return intersection.get(0);
}
/**
* <b>Description of addIntersection(String element)</b><br>
* Adds an element to the set of elements.
*
* @param element
* Element to be added
*/
public void addIntersection(String element) {
intersection.add(element);
}
public String toString() {
return (intersection.isEmpty()) ? "{ }" : "{ " + intersection.get(0)
+ " } / " + probability;
}
}
|
package com.tencent.mm.ui.conversation.a;
import com.tencent.mm.g.a.im;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.x;
class o$1 extends c<im> {
final /* synthetic */ o usZ;
o$1(o oVar) {
this.usZ = oVar;
this.sFo = im.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
if (((im) bVar).bRX.bQA) {
this.usZ.usX = false;
this.usZ.anR();
} else {
x.i("MicroMsg.TryNewInitBanner", "summerinit onSceneEnd -1 show tryNewInitBanner[%s]", new Object[]{this.usZ});
this.usZ.usX = true;
this.usZ.anR();
}
return false;
}
}
|
package com.zhouyi.business.core.service;
import com.zhouyi.business.core.model.SysRoleMenu;
import com.zhouyi.business.core.vo.SysRoleMenuVo;
import java.util.List;
public interface SysRoleMenuService {
SysRoleMenu findSysRoleMenuById(String id);
List<SysRoleMenu> findSysRoleMenuListBySysRoleMenu(SysRoleMenuVo sysRoleMenuVo);
void saveSysRoleMenu(SysRoleMenu sysRoleMenu);
void updateSysRoleMenu(SysRoleMenu sysRoleMenu);
void deleteSysRoleMenu(String id);
void deleteRoleMenuByRoleId(String roleId);
void deleteRoleMenuByMenuId(String menuId);
List<SysRoleMenu> getSysRoleMenuByRoleId(String roleId);
List<SysRoleMenu> getSysRoleMenuByMenuId(String menuId);
int findTotal(SysRoleMenuVo sysRoleMenuVo);
}
|
package org.sero.cash.superzk.protocol;
import org.sero.cash.superzk.crypto.ecc.Field;
import org.sero.cash.superzk.crypto.ecc.Point;
import org.sero.cash.superzk.json.HexType;
import org.sero.cash.superzk.protocol.superzk.Account;
import org.sero.cash.superzk.util.Base58;
import org.sero.cash.superzk.util.HexUtils;
public class AccountType {
public static abstract class SK implements HexType {
public Field.FR zsk;
public Field.FR vsk;
public SK() {
}
public SK(Field.FR zsk, Field.FR vsk) {
this.zsk = zsk;
this.vsk = vsk;
}
public abstract TK toTK();
public boolean isValid() {
if (this.zsk.isZero()) {
return false;
}
if (this.vsk.isZero()) {
return false;
}
return true;
}
public SK fromBytes(byte[] data) {
if (Param.isFlagSet(data)) {
return new Account.SK(data);
} else {
return new org.sero.cash.superzk.protocol.czero.Account.SK(data);
}
}
public byte[] toBytes() {
byte[] ret = new byte[64];
System.arraycopy(this.zsk.toBytes(), 0, ret, 0, 32);
System.arraycopy(this.vsk.toBytes(), 0, ret, 32, 32);
return ret;
}
public String toString() {
return HexUtils.toHex(this.toBytes());
}
}
public static abstract class TK implements HexType {
public Point zpk;
public Field.FR vsk;
public abstract PK toPK();
public abstract boolean isMyPKr(PKr pkr);
public static TK fromBytes(byte[] data) {
if (Param.isFlagSet(data)) {
return new Account.TK(data);
} else {
return new org.sero.cash.superzk.protocol.czero.Account.TK(data);
}
}
public byte[] toBytes() {
byte[] ret = new byte[64];
System.arraycopy(this.zpk.toBytes(), 0, ret, 0, 32);
System.arraycopy(this.vsk.toBytes(), 0, ret, 32, 32);
return ret;
}
public boolean isValid() {
return this.zpk.isValid() && !this.vsk.isZero();
}
public String toString() {
return Base58.encode(this.toBytes());
}
public String toHex() {
return HexUtils.toHex(this.toBytes());
}
}
public static abstract class PK implements HexType {
public Point zpk;
public Point vpk;
public static PK fromBytes(byte[] data) {
if (Param.isFlagSet(data)) {
return new Account.PK(data);
} else {
return new org.sero.cash.superzk.protocol.czero.Account.PK(data);
}
}
public byte[] toBytes() {
byte[] ret = new byte[64];
System.arraycopy(this.zpk.toBytes(), 0, ret, 0, 32);
System.arraycopy(this.vpk.toBytes(), 0, ret, 32, 32);
return ret;
}
public abstract PKr createPKr(Field.FR a);
public boolean isValid(byte[] data) {
return zpk != null && zpk != null;
}
public String toString() {
return Base58.encode(this.toBytes());
}
}
public static abstract class PKr implements HexType {
protected int i;
public Point ZPKr;
public Point VPKr;
public Point BASEr;
public boolean isValid() {
return this.ZPKr != null && this.ZPKr.isValid() &&
this.VPKr != null && this.VPKr.isValid() &&
this.BASEr != null && this.BASEr.isValid();
}
public static PKr fromBytes(byte[] data) {
if (Param.isFlagSet(data)) {
return new Account.PKr(data);
} else {
return new org.sero.cash.superzk.protocol.czero.Account.PKr(data);
}
}
public String toHex() {
return HexUtils.toHex(this.toBytes());
}
public String toString() {
return HexUtils.toHex(this.toBytes());
}
}
}
|
package com.intelli.reception;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.get.graph.LigneTemperature;
import com.google.appengine.api.datastore.*;
public class GetTemperatures extends HttpServlet {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
String valeur=req.getParameter("temp");//Integer.parseInt(req.getParameter("temp"));
String lieu = req.getParameter("lieu");
String date = req.getParameter("date");
LigneTemperature l = new LigneTemperature(lieu, date, valeur);
l.store();
/*Entity temp = new Entity("Temperature");
temp.setProperty("Date", date);
temp.setProperty("lieu", lieu);
temp.setProperty("valeur", valeur);
datastore.put(temp);*/
resp.getWriter().println("");
}
}
|
package dao;
import com.carrotsearch.hppc.*;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import org.mapdb.*;
import sbe.msg.marketData.TradingSessionEnum;
import vo.ClientVO;
import vo.OrderVO;
import vo.StockVO;
import vo.TradeVO;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
public class OffHeapStorage {
private static final Integer HAWKES_STATUS = 1;
private static final Integer WARMUP_STATUS = 2;
private static final Integer LOB_STATUS = 3;
private ObjectArrayList<StockVO> stockVOList;
private ObjectArrayList<ClientVO> clientVOList;
private ObjectObjectMap<String,BTreeMap<Long,OrderVO>> ordersMap;
private IntObjectMap<BTreeMap<Integer,TradeVO>> tradesMap;
private HTreeMap<Long,String> symbolStatusMap;
private HTreeMap<Integer,Boolean> hawkesSimulationMap;
private HTreeMap<Integer,Boolean> warmupSimulationMap;
private HTreeMap<Integer,Boolean> statusMap;
private ObjectObjectMap<String,HTreeMap.KeySet<Long> > pricesMap;
private DB db;
private boolean isReadOnly;
private static final String ORDERS_BID = "orders_bid_";
private static final String ORDERS_OFFER = "orders_offer_";
private static final String ORDERS_SUBMITTED = "orders_sub_";
private static final String PRICES = "prices_";
public void init(String dataPath,boolean isReadOnly){
ordersMap = new ObjectObjectHashMap<>();
tradesMap = new IntObjectHashMap<>();
pricesMap = new ObjectObjectHashMap<>();
this.isReadOnly = isReadOnly;
stockVOList = loadStocks(dataPath);
clientVOList = loadClients(dataPath);
removeClient(getClient(999)); //remove admin from list of clients
initDB(dataPath,isReadOnly);
initStockHashMaps(stockVOList);
initSymbolHashMap(stockVOList);
initSimulation(clientVOList);
db.commit();
}
private void initDB(String dataPath,boolean isReadOnly){
DBMaker.Maker maker = DBMaker.fileDB(dataPath + File.separator + "webStorage.db")
.fileMmapEnable()
.transactionEnable()
.closeOnJvmShutdown()
.allocateStartSize(10 * 1024*1024*1024) //5GB
.allocateIncrement(1024 * 1024 * 1024); //1GB
if(isReadOnly){
maker = maker.readOnly();
}
db = maker.make();
}
private void initStockHashMaps(ObjectArrayList<StockVO> stockVOList){
for (int i=0, max=stockVOList.size(); i < max; i++) {
StockVO stockVO = stockVOList.get(i);
if(stockVO != null){
int securityId = stockVO.getSecurityId();
//orders bid
String bidKey = ORDERS_BID + securityId;
BTreeMap<Long,OrderVO> orderBidMap = db.treeMap(bidKey, Serializer.LONG, Serializer.JAVA).createOrOpen();
ordersMap.put(bidKey,orderBidMap);
//orders offer
String offerKey = ORDERS_OFFER + securityId;
BTreeMap<Long,OrderVO> orderOfferMap = db.treeMap(offerKey, Serializer.LONG, Serializer.JAVA).createOrOpen();
ordersMap.put(offerKey,orderOfferMap);
//orders submitted
String subKey = ORDERS_SUBMITTED + securityId;
BTreeMap<Long,OrderVO> orderSubMap = db.treeMap(subKey, Serializer.LONG, Serializer.JAVA).createOrOpen();
ordersMap.put(subKey,orderSubMap);
//trades
BTreeMap<Integer,TradeVO> tradeMap = db.treeMap("trades_" + securityId, Serializer.INTEGER, Serializer.JAVA).createOrOpen();
tradesMap.put(securityId,tradeMap);
//prices
String priceKey = PRICES + securityId;
HTreeMap.KeySet<Long> priceMap = db.hashSet(priceKey, Serializer.LONG).createOrOpen();
pricesMap.put(priceKey,priceMap);
}
}
}
private void initSymbolHashMap(ObjectArrayList<StockVO> stockVOList){
symbolStatusMap = db.hashMap("symbolStatus", Serializer.LONG, Serializer.STRING).createOrOpen();
if(!isReadOnly) {
for (int i = 0, max = stockVOList.size(); i < max; i++) {
StockVO stockVO = stockVOList.get(i);
if (stockVO != null) {
long securityId = stockVO.getSecurityId();
symbolStatusMap.put(securityId, TradingSessionEnum.ContinuousTrading.toString());
}
}
}
}
public void setSymbolStatus(long securityId,TradingSessionEnum tradingSessionEnum){
symbolStatusMap.put(securityId, tradingSessionEnum.toString());
}
public TradingSessionEnum getSymbolStatus(long securityId){
return TradingSessionEnum.valueOf(symbolStatusMap.get(securityId));
}
public void initSimulation(ObjectArrayList<ClientVO> clientVOList){
hawkesSimulationMap = db.hashMap("hawkesSimulation", Serializer.INTEGER, Serializer.BOOLEAN).createOrOpen();
warmupSimulationMap = db.hashMap("warmupSimulation", Serializer.INTEGER, Serializer.BOOLEAN).createOrOpen();
statusMap = db.hashMap("status", Serializer.INTEGER, Serializer.BOOLEAN).createOrOpen();
if(!isReadOnly) {
for (int i = 0, max = clientVOList.size(); i < max; i++) {
ClientVO clientVO = clientVOList.get(i);
if (clientVO != null) {
int compId = clientVO.getCompId();
hawkesSimulationMap.put(compId, false);
warmupSimulationMap.put(compId, false);
}
}
statusMap.put(HAWKES_STATUS, false);
statusMap.put(WARMUP_STATUS, false);
statusMap.put(LOB_STATUS, false);
}
}
public void updateHawkesSimulation(int compId,boolean status){
hawkesSimulationMap.put(compId,status);
// db.commit();
}
public boolean getHawkesSimulation(int compId){
return hawkesSimulationMap.get(compId);
}
public void updateHawkesSimulationStatus(boolean status){
statusMap.put(HAWKES_STATUS,status);
// db.commit();
}
public boolean getHawkesSimulationSttaus(){
return statusMap.get(HAWKES_STATUS);
}
public boolean hasHawkesSimulationStarted(){
return statusMap.get(HAWKES_STATUS);
}
public void updateWarmupSimulation(int compId,boolean status){
warmupSimulationMap.put(compId,status);
// db.commit();
}
public boolean getWarmupSimulation(int compId){
return warmupSimulationMap.get(compId);
}
public void updateWarmupSimulationStatus(boolean status){
statusMap.put(WARMUP_STATUS,status);
// db.commit();
}
public boolean getWarmupSimulationSttaus(){
return statusMap.get(WARMUP_STATUS);
}
public boolean getLOBStatus(){
return statusMap.get(LOB_STATUS);
}
public boolean hasLOBSnapshotComplete(){
return statusMap.get(LOB_STATUS);
}
public void setLOBStatus(boolean status){
statusMap.put(LOB_STATUS,status);
// db.commit();
}
private ObjectArrayList<StockVO> loadStocks(String dataPath){
String stockFile = dataPath + File.separator + "Stock.csv";
ObjectArrayList<StockVO> stockVOList = new ObjectArrayList<>();
try {
StockDAO.loadStocks(stockFile, stockVOList);
} catch (Exception e) {
throw new RuntimeException("Unable to load stocks",e);
}
return stockVOList;
}
private ObjectArrayList<ClientVO> loadClients(String dataPath){
String clientFile = dataPath + File.separator + "clientData.csv";
ObjectArrayList<ClientVO> clientVOList = new ObjectArrayList<>();
try {
ClientDAO.loadClients(clientFile, clientVOList);
} catch (Exception e) {
throw new RuntimeException("Unable to load stocks",e);
}
return clientVOList;
}
public void removeClient(ClientVO clienVO){
clientVOList.removeFirst(clienVO);
}
public ClientVO getClient(int id){
for (int i=0, max=clientVOList.size(); i < max; i++) {
ClientVO clientVO = clientVOList.get(i);
if(clientVO.getCompId() == id){
return clientVO;
}
}
return null;
}
public void addPrice(int securityId,long price){
HTreeMap.KeySet<Long>priceMap = pricesMap.get(PRICES + securityId);
priceMap.add(price);
// db.commit();
}
public Iterator<Long> getPrices(int securityId){
HTreeMap.KeySet<Long> priceMap = pricesMap.get(PRICES + securityId);
return priceMap.iterator();
}
public void clearPrices(int securityId){
HTreeMap.KeySet<Long> priceMap = pricesMap.get(PRICES + securityId);
if(priceMap.size() > 0) {
priceMap.clear();
}
db.commit();
}
public void clearPrices(){
for(ObjectCursor<HTreeMap.KeySet<Long>> pricesCursor : pricesMap.values()){
if(pricesCursor.value.size() > 0) {
pricesCursor.value.clear();
}
}
db.commit();
}
public void addBidOrder(int securityId,OrderVO orderVO){
BTreeMap<Long,OrderVO> orderMap = ordersMap.get(ORDERS_BID + securityId);
orderMap.put(orderVO.getOrderId(),orderVO);
// db.commit();
}
public void addOfferOrder(int securityId,OrderVO orderVO){
BTreeMap<Long,OrderVO> orderMap = ordersMap.get(ORDERS_OFFER + securityId);
orderMap.put(orderVO.getOrderId(),orderVO);
// db.commit();
}
public void addSubmittedOrder(int securityId, OrderVO orderVO){
BTreeMap<Long,OrderVO> orderMap = ordersMap.get(ORDERS_SUBMITTED + securityId);
orderMap.put(orderVO.getOrderId(),orderVO);
// db.commit();
}
public void addTrades(int securityId, TradeVO tradeVO){
BTreeMap<Integer,TradeVO> tradeMap = tradesMap.get(securityId);
tradeMap.put(tradeVO.getTradeId(),tradeVO);
// db.commit();
}
public Collection<OrderVO> getBidOrders(int securityId){
BTreeMap<Long,OrderVO> orderMap = ordersMap.get(ORDERS_BID + securityId);
return orderMap.getValues();
}
public Collection<OrderVO> getOfferOrders(int securityId){
BTreeMap<Long,OrderVO> orderMap = ordersMap.get(ORDERS_OFFER + securityId);
return orderMap.getValues();
}
public Collection<OrderVO> getSubmittedOrders(int securityId){
BTreeMap<Long,OrderVO> orderMap = ordersMap.get(ORDERS_SUBMITTED + securityId);
return orderMap.getValues();
}
public Collection<TradeVO> getTrades(int securityId){
BTreeMap<Integer,TradeVO> tradeMap = tradesMap.get(securityId);
return tradeMap.getValues();
}
public void clearBidOrders(int securityId){
BTreeMap<Long,OrderVO> orderMap = ordersMap.get(ORDERS_BID + securityId);
if(orderMap.size() > 0) {
orderMap.clear();
}
db.commit();
}
public void clearOfferOrders(int securityId){
BTreeMap<Long,OrderVO> orderMap = ordersMap.get(ORDERS_OFFER + securityId);
if(orderMap.size() > 0) {
orderMap.clear();
}
db.commit();
}
public void clearSubmittedOrders(int securityId){
BTreeMap<Long,OrderVO> orderMap = ordersMap.get(ORDERS_SUBMITTED + securityId);
if(orderMap.size() > 0) {
orderMap.clear();
}
db.commit();
}
public void clearTrades(int securityId){
BTreeMap<Integer,TradeVO> tradeMap = tradesMap.get(securityId);
if(tradeMap.size() > 0) {
tradeMap.clear();
}
db.commit();
}
public void clearTrades(){
for(ObjectCursor<BTreeMap<Integer,TradeVO>> tradeCursor : tradesMap.values()){
if(tradeCursor.value.size() > 0) {
tradeCursor.value.clear();
}
}
db.commit();
}
public void clearOrders(){
for(ObjectCursor<BTreeMap<Long,OrderVO>> ordersCursor : ordersMap.values()){
if(ordersCursor.value.size() > 0) {
ordersCursor.value.clear();
}
}
db.commit();
}
public boolean isSimultationComplete(){
if(hawkesSimulationMap.getValues().contains(true)){
return false;
}
return true;
}
public boolean isWarmupComplete(){
if(warmupSimulationMap.getValues().contains(false)){
return false;
}
return true;
}
public void close(){
db.commit();
db.close();
}
public void commit(){
db.commit();
}
}
|
package com.example.lkplaces.jpa.repository;
import com.example.lkplaces.jpa.entity.PlaceType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PlaceTypeRepository extends JpaRepository<PlaceType, Integer> {
}
|
package com.goldgov.dygl.module.partymember.dao;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.goldgov.dygl.dynamicfield.DynamicField;
import com.goldgov.gtiles.core.dao.mybatis.annotation.MybatisRepository;
@MybatisRepository("partyMemberDao_BE")
public interface IPartyMemberDao_BE {
void addInfo(@Param("fields") DynamicField field,@Param("partyMemberID") String partyMemberID);
void updateInfo(@Param("entityID") String entityID,@Param("fields") DynamicField field);
Map<String, Object> findInfoById(@Param("id") String partyMemberID,@Param("fields") DynamicField field);
}
|
public class Travel extends Square {
private final static int AMOUNT_GAIN = 200;
public Travel(String name, int position) {
super(name, position);
}
@Override
public boolean isOwned() {
return false;
}
public void execute(Player player)
{
System.out.println(StdIO.printSquareLandedOn(player, this.getName()) + " and has gained ⚒200");
System.out.println(StdIO.showMaterialsIncreased(player, AMOUNT_GAIN));
player.increasePlayerMaterials(AMOUNT_GAIN);
StdIO.printTravelSquare(player, AMOUNT_GAIN);
}
//If player has passed travel square and not landed on it this method is called
public static void passedTravelSquare(Player player) {
System.out.println(StdIO.printTravelSquare(player, AMOUNT_GAIN));
System.out.println(StdIO.showMaterialsIncreased(player, AMOUNT_GAIN));
player.increasePlayerMaterials(AMOUNT_GAIN);
player.getPiece().setPassedTravelSquare(false);
}
}
|
import java.util.Random;
public class MultiCatch {
public static void main(String[] args) {
try {
// will throw exception of type A, or B, or C
throwRandomException();
}
catch (A | B | C ex) {
// At compile-time ex type is "closest common ancestor
// of A, B and C".
// In this example compile type of ex is Throwable.
System.out.println(ex);
}
}
static void throwRandomException() throws A, B, C {
Random random = new Random();
switch (random.nextInt(3)) {
case 0:
throw new A();
case 1:
throw new B();
case 2:
throw new C();
}
}
}
class A extends Error {
}
class B extends Throwable {
}
class C extends RuntimeException {
}
|
package online_2017;
/**
* @author kangkang lou
*/
import java.util.Scanner;
/**
* 松鼠过河
*/
public class Main_7 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
jump(arr);
}
}
public static void jump(int[] arr) {
int n = arr.length;
int[] dp = new int[n + 1];
for (int i = 0; i < n; i++) {
int endPosition = Math.min(i + arr[i], n);
for (int j = i + 1; j <= endPosition; j++) {
if (dp[j] == 0) {
dp[j] = dp[i] + 1;
}
}
if (dp[n] != 0 || (arr[i] == 0 && dp[i] == 0)) {
break;
}
}
if (dp[n] != 0) {
System.out.println(dp[n]);
} else {
System.out.println(-1);
}
}
}
|
/*
* 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 pe.egcc.pagoapp.view;
import javax.swing.JOptionPane;
import pe.egcc.pagoapp.dto.PagoDto;
import pe.egcc.pagoapp.service.PagoService;
/**
*
* @author Alumno-CT
*/
public class PagoView extends javax.swing.JFrame {
/**
* Creates new form PagoView
*/
public PagoView() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtHoras = new javax.swing.JTextField();
txtDias = new javax.swing.JTextField();
txtPagoHora = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
jLabel4 = new javax.swing.JLabel();
txtIngresos = new javax.swing.JTextField();
txtRenta = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtNeto = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("PAGO APP");
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setText("Horas Trabajadas");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel2.setText("Dias Trabajados");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel3.setText("Pago por Hora");
txtHoras.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txtHoras.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtHorasActionPerformed(evt);
}
});
txtDias.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txtDias.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtDiasActionPerformed(evt);
}
});
txtPagoHora.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton1.setText("Calcular");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel4.setText("Ingresos");
txtIngresos.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txtIngresos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtIngresosActionPerformed(evt);
}
});
txtRenta.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txtRenta.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtRentaActionPerformed(evt);
}
});
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel5.setText("Renta");
txtNeto.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel6.setText("Neto");
jButton2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jButton2.setText("Salir");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(61, 61, 61)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtNeto)
.addComponent(txtIngresos, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtRenta, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(15, 15, 15))
.addGroup(layout.createSequentialGroup()
.addContainerGap(51, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtPagoHora)
.addComponent(txtHoras, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtDias, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addComponent(jSeparator1))))
.addGap(32, 32, 32))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtHoras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtDias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtPagoHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtIngresos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtRenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtNeto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)
.addComponent(jButton2))
.addContainerGap(21, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtHorasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtHorasActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtHorasActionPerformed
private void txtDiasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDiasActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtDiasActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
//datos ingreso
int horas = Integer.parseInt(txtHoras.getText());
int dias = Integer.parseInt(txtDias.getText());
double pagohora = Double.parseDouble(txtPagoHora.getText());
//proceso
PagoDto dto = new PagoDto(horas, dias, pagohora);
PagoService pagoService = new PagoService();
dto = pagoService.calcularPago(dto);
txtIngresos.setText(Double.toString(dto.getIngresos()));
txtRenta.setText(Double.toString(dto.getRenta()));
txtNeto.setText(Double.toString(dto.getNeto()));
// reporte
/*
String repo = "";
repo += "Ingresos: " + dto.getIngresos() + "\n";
repo += "Renta: " + dto.getRenta() + "\n";
repo += "Neto: " + dto.getNeto() + "\n";
JOptionPane.showMessageDialog(rootPane, repo, "REPORTE", JOptionPane.INFORMATION_MESSAGE);
*/
}//GEN-LAST:event_jButton1ActionPerformed
private void txtIngresosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIngresosActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtIngresosActionPerformed
private void txtRentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtRentaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtRentaActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
dispose();
}//GEN-LAST:event_jButton2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PagoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PagoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PagoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PagoView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PagoView().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextField txtDias;
private javax.swing.JTextField txtHoras;
private javax.swing.JTextField txtIngresos;
private javax.swing.JTextField txtNeto;
private javax.swing.JTextField txtPagoHora;
private javax.swing.JTextField txtRenta;
// End of variables declaration//GEN-END:variables
}
|
package common.ztb.test;
import java.io.IOException;
import org.apache.commons.dbcp.BasicDataSource;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
public abstract class BaseDBUnitTest extends BaseDaoTest {
protected DatabaseConnection connection;
private BasicDataSource dataSource;
public boolean testmodel=false;
public void setDataSource(BasicDataSource dataSource) {
this.dataSource = dataSource;
}
protected void onSetUpBeforeTransaction() throws Exception {
super.onSetUpBeforeTransaction();
this.connection = new DatabaseConnection(dataSource.getConnection());
IDataSet dataSet = this.getDataSet();
if (dataSet != null) {
if(testmodel){
org.dbunit.ext.mssql.InsertIdentityOperation.CLEAN_INSERT.execute(
this.connection, dataSet);
}else{
org.dbunit.ext.mssql.InsertIdentityOperation.CLEAN_INSERT.execute(
this.connection, dataSet);
}
}
}
protected void onTearDownAfterTransaction() throws Exception {
super.onTearDownAfterTransaction();
IDataSet dataSet = this.getDataSet();
if (dataSet != null) {
if(testmodel){
org.dbunit.ext.mssql.InsertIdentityOperation.DELETE_ALL.execute(
connection, dataSet);
}else{
org.dbunit.ext.mssql.InsertIdentityOperation.NONE.execute(
connection, dataSet);
}
}
this.connection.close();
}
protected abstract IDataSet getDataSet() throws DataSetException,
IOException;
}
|
package com.cngl.bilet.repository;
import com.cngl.bilet.entity.Havalimani;
import org.springframework.data.jpa.repository.JpaRepository;
public interface HavalimaniRepository extends JpaRepository<Havalimani,Long> {
} |
package clueGame;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class NewGameDialog extends JPanel {
public NewGameDialog(String player)
{
JFrame frame = new JFrame("DialogDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(frame, "You are " + player + ", press Next Player to begin play");
}
}
|
package com.zmyaro.ltd;
import android.content.Context;
public class MissileTurret extends Turret {
public MissileTurret(Context context) {
super(context);
mDamages = new int[]{5, 10, 20, 20, 30};
mDelays = new int[]{40, 40, 30, 20, 10};
mRanges = new int[]{300, 320, 360, 400, 500};
mCosts = new int[]{40, 40, 100, 160, 600};
mWidth = 12;
mHeight = 24;
mCenterOffsetX = 6;
mCenterOffsetY = 18;
}
}
|
package ro.fasttrackit.curs20.homework;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import ro.fasttrackit.curs20.homework.entity.Transaction;
import ro.fasttrackit.curs20.homework.entity.Type;
import ro.fasttrackit.curs20.homework.repository.TransactionRepository;
import java.util.List;
/*Create a webapp backend that manages the transactions in a budget:
Transaction
- id
- product
- type: SELL/BUY
- amount: double
GET /transactions - get all transactions. Make it filterable by type, minAmount, maxAmount (you will have 6 filtering methods in repository: byType, byMinAmoun, byMaxAmout, byTypeAndMin, byTypeAndMax, byMinAndMax, byTypeAndMinAndMax)
GET /transactions/{id} - get transaction with id
POST /transactions - adds a new transaction
PUT /transactions/{id} - replaces the transaction with id
PATCH /transactions/{id} - supports changing the product and the amount
DELETE /transactions/{id} - deletes the transaction with id
GET /transactions/reports/type -> returns a map from type to sum of amount - the processing is done in memory, not in the database. you can try making another implementation with calculations in db
GET /transactions/reports/product -> returns a map from product to sum of amount
example:
If you have transactions
[
{type:SELL, amount:3.2},
{type:BUY, amount:4.0},
{type:SELL, amount:1.3}
]
the type report will be
{
SELL: [
{type:SELL, amount:3.2},
{type:SELL, amount:1.3}
],
BUY: [{type:BUY, amount:4.0}]
}*/
@SpringBootApplication
public class BudgetAppApplication {
public static void main(String[] args) {
SpringApplication.run(BudgetAppApplication.class, args);
}
@Bean
CommandLineRunner atStartup(TransactionRepository repository) {
return args -> {
repository.saveAll(List.of(
new Transaction("laptop", Type.BUY, 1000),
new Transaction("headphones", Type.BUY, 100),
new Transaction("player", Type.BUY, 250),
new Transaction("tv", Type.SELL, 750),
new Transaction("car", Type.SELL, 10000),
new Transaction("fridge", Type.SELL, 500)
));
};
}
}
|
package com.rile.methotels.pages.services;
import com.rile.methotels.entities.Rezervacija;
import com.rile.methotels.services.dao.RezervacijaDao;
import java.util.ArrayList;
import java.util.List;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.RequestParameter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.util.TextStreamResponse;
/**
*
* @author Stefan
*/
public class FindRezervacija {
@Inject
private Request request;
@Property
private List<Rezervacija> rezervacije;
@Property
private Rezervacija rezervacija;
@Inject
private RezervacijaDao rezervacijaDao;
Object onActivate(@RequestParameter("ime") String ime) {
if (rezervacije == null) {
rezervacije = new ArrayList<Rezervacija>();
}
String response = "<table class=\"navigation\" > <th>\n" +
" Ime rezervacije\n" +
" </th>\n" + " ";
rezervacije = rezervacijaDao.getListByIme(ime);
for (Rezervacija r : rezervacije) {
response += (" <tr>\n" +
" <td> " + r.getIme() + "</td>\n" +
" </tr>"
);
}
response += "</table>";
return new TextStreamResponse("text/plain", response);
}
}
|
package tom.graphic.ThreeD;
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.MediaTracker;
import java.io.PrintStream;
import java.net.URL;
import java.util.StringTokenizer;
// Referenced classes of package tom.graphic.ThreeD:
// View3DCanvas, View3DCommon
public class View3DApplet extends Applet {
String paramName;
public View3DCanvas view;
public Integer getParameterInt(String s) {
Integer integer = null;
String s1;
if ((s1 = getParameter(s)) != null)
try {
integer = new Integer(s1);
}
catch (Exception _ex) {
System.out.println("Error, for paremeter " + s + " incorrect int value:" + s1);
}
return integer;
}
public void init() {
setLayout(new BorderLayout());
add("Center", view = new View3DCanvas());
Integer integer;
if ((integer = getParameterInt("angleX")) != null)
view.setAngleX(integer.intValue());
Integer integer1;
if ((integer1 = getParameterInt("angleY")) != null)
view.setAngleY(integer1.intValue());
Integer integer2;
if ((integer2 = getParameterInt("angleZ")) != null)
view.setAngleZ(integer2.intValue());
Integer integer3;
if ((integer3 = getParameterInt("posX")) != null)
view.setPosX(integer3.intValue());
if ((integer3 = getParameterInt("posX")) != null)
view.setPosX(integer3.intValue());
Integer integer4;
if ((integer4 = getParameterInt("posY")) != null)
view.setPosY(integer4.intValue());
Integer integer5;
if ((integer5 = getParameterInt("posZ")) != null)
view.setPosZ(integer5.intValue());
if ((paramName = getParameter("backgIma")) != null)
setBackgIma(paramName);
Integer integer6;
if ((integer6 = getParameterInt("backgMode")) != null)
setBackgMode(integer6.intValue());
if ((paramName = getParameter("model")) != null)
setModel(paramName);
String s = null;
if ((s = getParameter("allowedMove")) != null)
try {
boolean aflag[] = new boolean[6];
StringTokenizer stringtokenizer = new StringTokenizer(s, ",");
for (int i = 0; i < 6; i++)
aflag[i] = Boolean.valueOf(stringtokenizer.nextToken()).booleanValue();
view.setAllowedMove(aflag[0], aflag[1], aflag[2], aflag[3], aflag[4], aflag[5]);
}
catch (Exception _ex) {
System.out.println("erreur with parameter allowedMove");
}
}
public void setBackgIma(String s) {
MediaTracker mediatracker = new MediaTracker(this);
java.awt.Image image;
mediatracker.addImage(image = getImage(getDocumentBase(), s), 0);
try {
mediatracker.waitForID(0);
}
catch (Exception _ex) {
System.out.println("Not all images loaded.");
}
view.setBackgIma(image);
}
public void setBackgMode(int i) {
view.setBackgMode(i);
}
public void setModel(String s) {
Object obj = null;
try {
java.io.InputStream inputstream = (new URL(getDocumentBase(), s)).openStream();
view.setObj(inputstream, s);
}
catch (Exception exception) {
System.out.println(exception);
}
}
}
|
package pattern_test.composite;
/**
* Description:
*
* @author Baltan
* @date 2019-04-02 10:38
*/
public class Mouse implements Component {
@Override
public int getPrice() {
return 200;
}
}
|
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import proto.BlockchainGrpc;
import proto.BlockchainService;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class BankClient {
static private int idGenerator = 0;
private int id;
private final ManagedChannel channel;
private final BlockchainGrpc.BlockchainBlockingStub blockingStub;
BankClient(int port) {
this(ManagedChannelBuilder.forAddress("localhost", port)
.usePlaintext()
.build());
}
public int getId() {
return this.id;
}
BankClient(ManagedChannel channel) {
this.id = idGenerator++;
this.channel = channel;
blockingStub = BlockchainGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public void sendTransaction(int destClient, BlockchainService.Transaction.Action ac, double amount, String time) {
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss.SS").format(new Date());
BlockchainService.Transaction t = BlockchainService.Transaction.newBuilder()
.setSourceClient(this.id)
.setDestClient(destClient)
.setAction(ac)
.setAmount(amount)
.setTime(time)
.build();
blockingStub.onTransactionReceive(t);
// System.out.println("Sending Transaction from: " + this.id + " amount: " + amount);
}
public void statusRequest() {
BlockchainService.StatusRequest statusRequest = BlockchainService.StatusRequest.newBuilder()
.setClientId(this.id)
.build();
BlockchainService.StatusReply reply;
reply = this.blockingStub.onStatusCheck(statusRequest);
System.out.println("**CLIENT STATUS** " + reply.getMsg());
}
}
|
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
public class DiscountServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ProductBean db = new ProductBean();
db.setDiscount(Integer.parseInt(req.getParameter("off")));
PrintWriter out = resp.getWriter();
JSONArray result;
result = db.discountInfo(db.getDiscount());
//System.out.println(result);
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("UTF-8");
out.println(result);
out.close();
}
}
|
package model;
import java.util.ArrayList;
/**Advertising Entity
* @author Andressa de Andrade Freitas
* @version 0.0.1
* @since Release 0
*/
public class Advertising {
private CustomerEnum customerEnum;;
private ArrayList<Deal> deal;
private ArrayList<Discount> discount;
public Advertising(){
}
public ArrayList<Discount> getDiscount() {
return discount;
}
public void setDiscount(ArrayList<Discount> discount) {
this.discount = discount;
}
public ArrayList<Deal> getDeal() {
return deal;
}
public void setDeal(ArrayList<Deal> deal) {
this.deal = deal;
}
}
|
package data;
public class Value {
private BusPosition busPosition;
private RouteCode routeCode;
private BusLine busLine;
public Value(BusPosition busPosition, RouteCode routeCode, BusLine busLine) {
this.busPosition = busPosition;
this.routeCode = routeCode;
this.busLine = busLine;
}
@Override
public String toString() {
return "Value{" +
"busPosition=" + busPosition +
", routeCode=" + routeCode +
", busLine=" + busLine +
'}';
}
}
|
import java.util.LinkedList;
import tracker.*;
public class Test{
static int score = 0;
public static void main(String[] args) {
testLabel();
testIssue();
testTracker();
System.out.println("Pontszam: " + score);
if(score < 6) System.out.println("Jegy: elegtelen (1)");
else if(score < 9) System.out.println("Jegy: elegseges (2)");
else if(score < 12) System.out.println("Jegy: kozepes (3)");
else if(score < 15) System.out.println("Jegy: jo (4)");
else System.out.println("Jegy: jeles (5)");
}
private static void testLabel() {
Label l1 = new Label("alma");
String s = new String("alma");
Label l2 = new Label(s);
Label l3 = new Label("korte");
assertEquals("A Label osztaly konstruktora vagy lekerdezo-muvelete helytelenul mukodik.", l1.getName(), s);
assertEquals("A Label osztaly konstruktora vagy lekerdezo-muvelete helytelenul mukodik.", l2.getName(), "alma");
score = score + 1;
assertTrue("A Label osztaly isSame muvelete egyforma cimkeknel hamisat adott vissza.", l1.isSame(l2));
assertTrue("A Label osztaly isSame muvelete egyforma cimkeknel hamisat adott vissza.", l2.isSame(l1));
assertTrue("A Label osztaly isSame muvelete kulonbozo cimkeknel igazat adott vissza.", !l2.isSame(l3));
score = score + 1;
System.out.println("Label: OK (eddig " + score + " pont)");
}
private static void testIssue() {
testIssueConstructorAndGetters();
testIssueCreate();
testIssueHasLabel();
System.out.println("Issue: OK (eddig " + score + " pont)");
}
private static void testIssueConstructorAndGetters() {
Label l1 = new Label("alma");
Label l2 = new Label("korte");
Label l3 = new Label("szilva");
Label[] labels = new Label[] { l1, l2, l3 };
Issue i1 = new Issue("gyumolcsok", labels, 42);
assertEquals("Az Issue osztaly konstruktora vagy lekerdezo-muvelete helytelenul mukodik.", i1.getDescription(), "gyumolcsok");
assertEquals("Az Issue osztaly konstruktora vagy lekerdezo-muvelete helytelenul mukodik.", i1.getMilestone(), 42);
assertEquals("Az Issue osztaly konstruktora vagy lekerdezo-muvelete helytelenul mukodik.", i1.getLabels().size(), 3);
assertTrue("Az Issue osztaly konstruktora vagy lekerdezo-muvelete helytelenul mukodik.", i1.getLabels().get(1).isSame(l2));
score = score + 2;
}
private static void testIssueCreate() {
Issue i1 = Issue.createIssue("");
Issue i2 = Issue.createIssue("alma");
Issue i3 = Issue.createIssue("alma:korte");
Issue i4 = Issue.createIssue("alma:42:2");
Issue i5 = Issue.createIssue("alma@korte@barack:42");
Issue i6 = Issue.createIssue("alma@joska:42:2");
Issue i7 = Issue.createIssue("alma@joska:korte");
assertTrue("A createIssue metodus helytelen inputra is letrehoz objektumot (\"\").", (i1 == null));
assertTrue("A createIssue metodus helytelen inputra is letrehoz objektumot (\"alma\").", (i2 == null));
assertTrue("A createIssue metodus helytelen inputra is letrehoz objektumot (\"alma:korte\").", (i3 == null));
assertTrue("A createIssue metodus helytelen inputra is letrehoz objektumot (\"alma:42:2\").", (i4 == null));
assertTrue("A createIssue metodus helytelen inputra is letrehoz objektumot (\"alma@korte@barack:42\").", (i5 == null));
assertTrue("A createIssue metodus helytelen inputra is letrehoz objektumot (\"alma@joska:42:2\").", (i6 == null));
assertTrue("A createIssue metodus helytelen inputra is letrehoz objektumot (\"alma@joska:korte\").", (i7 == null));
Issue i8 = Issue.createIssue("alma:42");
Issue i9 = Issue.createIssue("alma@joska:42");
Issue i10 = Issue.createIssue("alma@joska,pista:42");
assertTrue("A createIssue metodus helyes inputra nem letrehoz objektumot (\"alma:42\").", (i8 != null));
assertTrue("A createIssue metodus helyes inputra nem letrehoz objektumot (\"alma@joska:42\").", (i9 != null));
assertTrue("A createIssue metodus helyes inputra nem letrehoz objektumot (\"alma@joska,pista:42\").", (i10 != null));
assertEquals("A createIssue metodus helytelen objektumot hoz letre (\"alma:42\").", i8.getDescription(), "alma");
assertEquals("A createIssue metodus helytelen objektumot hoz letre (\"alma:42\").", i8.getMilestone(), 42);
assertEquals("A createIssue metodus helytelen objektumot hoz letre (\"alma@joska,pista:42\").", i10.getMilestone(), 42);
assertEquals("A createIssue metodus helytelen objektumot hoz letre (\"alma:42\").", i8.getLabels().size(), 0);
assertEquals("A createIssue metodus helytelen objektumot hoz letre (\"alma@joska,pista:42\").", i10.getLabels().size(), 2);
assertEquals("A createIssue metodus helytelen objektumot hoz letre (\"alma@joska,pista:42\").", i10.getLabels().get(1).getName(), "pista");
score = score + 2;
}
private static void testIssueHasLabel() {
Issue i1 = Issue.createIssue("alma:42");
Issue i2 = Issue.createIssue("alma@joska,pista:42");
assertFalse("A Issue osztaly hasLabel metodusa helytelenul mukodik (i1.hasLabel(\"proba\")).", i1.hasLabel("proba"));
assertTrue("A Issue osztaly hasLabel metodusa helytelenul mukodik (i2.hasLabel(\"joska\")).", i2.hasLabel("joska"));
assertTrue("A Issue osztaly hasLabel metodusa helytelenul mukodik (i2.hasLabel(\"pista\")).", i2.hasLabel("pista"));
assertFalse("A Issue osztaly hasLabel metodusa helytelenul mukodik(i2.hasLabel(\"proba\")).", i2.hasLabel("proba"));
score = score + 1;
}
private static boolean labelListEquals(LinkedList<Label> l1, LinkedList<Label> l2) {
if( (l1 == null) && (l2 == null) ) return true;
if( ((l1 != null) && (l2 == null)) || ((l1 == null) && (l2 != null)) ) return false;
if( l1.size() != l2.size() ) return false;
for(int i = 0; i < l1.size(); i++) {
if( !l1.get(i).isSame(l2.get(i)) )
return false;
}
return true;
}
private static boolean issueEquals(Issue i1, Issue i2) {
return ((i1.getDescription().equals(i2.getDescription())) &&
(labelListEquals(i1.getLabels(), i2.getLabels())) &&
(i1.getMilestone() == i2.getMilestone()));
}
private static boolean issueListEquals(LinkedList<Issue> l1, LinkedList<Issue> l2) {
if( (l1 == null) && (l2 == null) ) return true;
if( ((l1 != null) && (l2 == null)) || ((l1 == null) && (l2 != null)) ) return false;
if( l1.size() != l2.size() ) return false;
for(int i = 0; i < l1.size(); i++) {
if( !issueEquals(l1.get(i), l2.get(i)) )
return false;
}
return true;
}
private static void testTracker() {
Tracker t = new Tracker("input.txt");
assertEquals("A Tracker osztaly konstruktora helytelenul mukodik.", t.getNumberOfLabels(), 4);
assertEquals("A Tracker osztaly konstruktora helytelenul mukodik.", t.getNumberOfIssues(), 4);
score = score + 4;
assertTrue("A Tracker osztaly find metodusa helytelenul mukodik (d1-re-re a masodik sort kene visszaadnia).", issueEquals(t.find("d1"), Issue.createIssue("d1@lab1,lab2,lab3:2")));
assertTrue("A Tracker osztaly find metodusa helytelenul mukodik (d5-re nem kene talalatot adnia, mert az utolo sor ervenytelen, mert nincs lab4-es label).", (t.find("d5") == null));
score = score + 2;
LinkedList<Issue> l = new LinkedList<Issue>();
l.add(Issue.createIssue("d1@lab1,lab2,lab3:2"));
l.add(Issue.createIssue("d2@lab2,lab3:3"));
assertTrue("A Tracker osztaly listByLabel metodusa helytelenul mukodik (lab2-re az elso ket feladatot kene visszaadnia).", issueListEquals(t.listByLabel(new Label("lab2")), l));
assertEquals("A Tracker osztaly listByLabel metodusa helytelenul mukodik (lab5-re ures listat kene visszaadnia).", t.listByLabel(new Label("lab5")).size(), 0);
assertTrue("A Tracker osztaly listByLabel metodusa helytelenul mukodik (lab4-re null- kene visszaadnia).", (t.listByLabel(new Label("lab4")) == null));
score = score + 2;
assertTrue("A Tracker osztaly isMilestoneComplete metodusa helytelenul mukodik (1-re igazat kene visszaadnia).", t.isMilestoneComplete(1));
assertFalse("A Tracker osztaly isMilestoneComplete metodusa helytelenul mukodik (2-re hamisat kene visszaadnia).", t.isMilestoneComplete(2));
score = score + 2;
System.out.println("Tracker: OK (eddig " + score + " pont)");
}
private static void assertFalse(String msg, boolean p) {
if (p) {
throw new RuntimeException(msg);
}
}
private static void assertTrue(String msg, boolean p) {
if (!p) {
throw new RuntimeException(msg);
}
}
private static void assertEquals(String msg, Object expected, Object actual) {
if (!expected.equals(actual)) {
throw new RuntimeException(msg + "\nexpected:\n" + expected
+ "\nactual:\n" + actual);
}
}
} |
package javax.vecmath;
import java.io.Serializable;
public class AxisAngle4d implements Serializable, Cloneable {
static final long serialVersionUID = 3644296204459140589L;
public double x;
public double y;
public double z;
public double angle;
static final double EPS = 1.0E-12D;
public AxisAngle4d(double x, double y, double z, double angle) {
this.x = x;
this.y = y;
this.z = z;
this.angle = angle;
}
public AxisAngle4d(double[] a) {
this.x = a[0];
this.y = a[1];
this.z = a[2];
this.angle = a[3];
}
public AxisAngle4d(AxisAngle4d a1) {
this.x = a1.x;
this.y = a1.y;
this.z = a1.z;
this.angle = a1.angle;
}
public AxisAngle4d(AxisAngle4f a1) {
this.x = a1.x;
this.y = a1.y;
this.z = a1.z;
this.angle = a1.angle;
}
public AxisAngle4d(Vector3d axis, double angle) {
this.x = axis.x;
this.y = axis.y;
this.z = axis.z;
this.angle = angle;
}
public AxisAngle4d() {
this.x = 0.0D;
this.y = 0.0D;
this.z = 1.0D;
this.angle = 0.0D;
}
public final void set(double x, double y, double z, double angle) {
this.x = x;
this.y = y;
this.z = z;
this.angle = angle;
}
public final void set(double[] a) {
this.x = a[0];
this.y = a[1];
this.z = a[2];
this.angle = a[3];
}
public final void set(AxisAngle4d a1) {
this.x = a1.x;
this.y = a1.y;
this.z = a1.z;
this.angle = a1.angle;
}
public final void set(AxisAngle4f a1) {
this.x = a1.x;
this.y = a1.y;
this.z = a1.z;
this.angle = a1.angle;
}
public final void set(Vector3d axis, double angle) {
this.x = axis.x;
this.y = axis.y;
this.z = axis.z;
this.angle = angle;
}
public final void get(double[] a) {
a[0] = this.x;
a[1] = this.y;
a[2] = this.z;
a[3] = this.angle;
}
public final void set(Matrix4f m1) {
Matrix3d m3d = new Matrix3d();
m1.get(m3d);
this.x = (float)(m3d.m21 - m3d.m12);
this.y = (float)(m3d.m02 - m3d.m20);
this.z = (float)(m3d.m10 - m3d.m01);
double mag = this.x * this.x + this.y * this.y + this.z * this.z;
if (mag > 1.0E-12D) {
mag = Math.sqrt(mag);
double sin = 0.5D * mag;
double cos = 0.5D * (m3d.m00 + m3d.m11 + m3d.m22 - 1.0D);
this.angle = (float)Math.atan2(sin, cos);
double invMag = 1.0D / mag;
this.x *= invMag;
this.y *= invMag;
this.z *= invMag;
} else {
this.x = 0.0D;
this.y = 1.0D;
this.z = 0.0D;
this.angle = 0.0D;
}
}
public final void set(Matrix4d m1) {
Matrix3d m3d = new Matrix3d();
m1.get(m3d);
this.x = (float)(m3d.m21 - m3d.m12);
this.y = (float)(m3d.m02 - m3d.m20);
this.z = (float)(m3d.m10 - m3d.m01);
double mag = this.x * this.x + this.y * this.y + this.z * this.z;
if (mag > 1.0E-12D) {
mag = Math.sqrt(mag);
double sin = 0.5D * mag;
double cos = 0.5D * (m3d.m00 + m3d.m11 + m3d.m22 - 1.0D);
this.angle = (float)Math.atan2(sin, cos);
double invMag = 1.0D / mag;
this.x *= invMag;
this.y *= invMag;
this.z *= invMag;
} else {
this.x = 0.0D;
this.y = 1.0D;
this.z = 0.0D;
this.angle = 0.0D;
}
}
public final void set(Matrix3f m1) {
this.x = (m1.m21 - m1.m12);
this.y = (m1.m02 - m1.m20);
this.z = (m1.m10 - m1.m01);
double mag = this.x * this.x + this.y * this.y + this.z * this.z;
if (mag > 1.0E-12D) {
mag = Math.sqrt(mag);
double sin = 0.5D * mag;
double cos = 0.5D * ((m1.m00 + m1.m11 + m1.m22) - 1.0D);
this.angle = (float)Math.atan2(sin, cos);
double invMag = 1.0D / mag;
this.x *= invMag;
this.y *= invMag;
this.z *= invMag;
} else {
this.x = 0.0D;
this.y = 1.0D;
this.z = 0.0D;
this.angle = 0.0D;
}
}
public final void set(Matrix3d m1) {
this.x = (float)(m1.m21 - m1.m12);
this.y = (float)(m1.m02 - m1.m20);
this.z = (float)(m1.m10 - m1.m01);
double mag = this.x * this.x + this.y * this.y + this.z * this.z;
if (mag > 1.0E-12D) {
mag = Math.sqrt(mag);
double sin = 0.5D * mag;
double cos = 0.5D * (m1.m00 + m1.m11 + m1.m22 - 1.0D);
this.angle = (float)Math.atan2(sin, cos);
double invMag = 1.0D / mag;
this.x *= invMag;
this.y *= invMag;
this.z *= invMag;
} else {
this.x = 0.0D;
this.y = 1.0D;
this.z = 0.0D;
this.angle = 0.0D;
}
}
public final void set(Quat4f q1) {
double mag = (q1.x * q1.x + q1.y * q1.y + q1.z * q1.z);
if (mag > 1.0E-12D) {
mag = Math.sqrt(mag);
double invMag = 1.0D / mag;
this.x = q1.x * invMag;
this.y = q1.y * invMag;
this.z = q1.z * invMag;
this.angle = 2.0D * Math.atan2(mag, q1.w);
} else {
this.x = 0.0D;
this.y = 1.0D;
this.z = 0.0D;
this.angle = 0.0D;
}
}
public final void set(Quat4d q1) {
double mag = q1.x * q1.x + q1.y * q1.y + q1.z * q1.z;
if (mag > 1.0E-12D) {
mag = Math.sqrt(mag);
double invMag = 1.0D / mag;
this.x = q1.x * invMag;
this.y = q1.y * invMag;
this.z = q1.z * invMag;
this.angle = 2.0D * Math.atan2(mag, q1.w);
} else {
this.x = 0.0D;
this.y = 1.0D;
this.z = 0.0D;
this.angle = 0.0D;
}
}
public String toString() {
return "(" + this.x + ", " + this.y + ", " + this.z + ", " + this.angle + ")";
}
public boolean equals(AxisAngle4d a1) {
try {
return (this.x == a1.x && this.y == a1.y && this.z == a1.z &&
this.angle == a1.angle);
} catch (NullPointerException e2) {
return false;
}
}
public boolean equals(Object o1) {
try {
AxisAngle4d a2 = (AxisAngle4d)o1;
return (this.x == a2.x && this.y == a2.y && this.z == a2.z &&
this.angle == a2.angle);
} catch (NullPointerException e2) {
return false;
} catch (ClassCastException e1) {
return false;
}
}
public boolean epsilonEquals(AxisAngle4d a1, double epsilon) {
double diff = this.x - a1.x;
if (((diff < 0.0D) ? -diff : diff) > epsilon)
return false;
diff = this.y - a1.y;
if (((diff < 0.0D) ? -diff : diff) > epsilon)
return false;
diff = this.z - a1.z;
if (((diff < 0.0D) ? -diff : diff) > epsilon)
return false;
diff = this.angle - a1.angle;
if (((diff < 0.0D) ? -diff : diff) > epsilon)
return false;
return true;
}
public int hashCode() {
long bits = 1L;
bits = VecMathUtil.hashDoubleBits(bits, this.x);
bits = VecMathUtil.hashDoubleBits(bits, this.y);
bits = VecMathUtil.hashDoubleBits(bits, this.z);
bits = VecMathUtil.hashDoubleBits(bits, this.angle);
return VecMathUtil.hashFinish(bits);
}
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
public final double getAngle() {
return this.angle;
}
public final void setAngle(double angle) {
this.angle = angle;
}
public double getX() {
return this.x;
}
public final void setX(double x) {
this.x = x;
}
public final double getY() {
return this.y;
}
public final void setY(double y) {
this.y = y;
}
public double getZ() {
return this.z;
}
public final void setZ(double z) {
this.z = z;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\javax\vecmath\AxisAngle4d.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package Learn;
import Learn.h;
class staticBlockk2{
static {
System.out.println("kem cho majama");
}
}
public class staticblock extends staticBlock2 {
static String s;
static int count = 10;
int a =493;
static {
System.out.println(count);
count = 100;
System.out.println(s);
staticblock sb = new staticblock();
}
static h H = new h();
void pprint(){
System.out.println("pp got called");
}
static void print(){
System.out.println("kem chho majama");
}
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
staticBlockk2 sb2 ;
staticblock sb = new
staticblock();
System.out.println(count);
System.out.println(staticblock.count);
System.out.println(sb);
System.out.println(Class.forName("Learn.staticBlockk2"));
System.out.println(staticblock.class.isInstance(sb));
}
}
|
package com.cos.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;
import com.cos.constants.ParamConstants;
import com.cos.constants.URLConstant;
import com.cos.entities.Image;
import com.cos.services.interfaces.ImageServiceInterface;
@RestController
@RequestMapping(value = URLConstant.IMAGE_URL)
public class ImageController {
@Autowired
private ImageServiceInterface imageServiceInterface;
@RequestMapping(value = URLConstant.ADD_IMAGE_URL, method = RequestMethod.POST)
public ResponseEntity<?> addImage(@RequestParam(ParamConstants.LINK) String link,
@RequestParam(ParamConstants.PRODUCT_ID) int productId,
@RequestParam(ParamConstants.MAIN) boolean main) {
Image image = imageServiceInterface.addImage(link, productId, main);
return new ResponseEntity<Image> (image, HttpStatus.OK);
}
@RequestMapping(value = URLConstant.GET_ALL_IMAGE, method = RequestMethod.GET)
public ResponseEntity<?> getAllImage() {
List<Image> listOfImage = imageServiceInterface.getAllImage();
return new ResponseEntity<List<Image>> (listOfImage, HttpStatus.OK);
}
@RequestMapping(value = URLConstant.CHANGE_MAIN_IMAGE, method = RequestMethod.POST)
public ResponseEntity<?> changeMainImage(@RequestParam(ParamConstants.IMAGE_ID) Integer imageId,
@RequestParam(ParamConstants.NEW_IMAGE) String newImage) {
Image image = imageServiceInterface.getImageById(imageId);
imageServiceInterface.changeMainImage(image, newImage);
return new ResponseEntity<Image> (image, HttpStatus.OK);
}
// public ResponseEntity<?> changeMainImage(@RequestParam(ParamConstants.IMAGE_ID) Integer imageId) {
// Image image = imageServiceInterface.getImageById(imageId);
// imageServiceInterface.changeMainImage(image);
// return new ResponseEntity<Image> (image, HttpStatus.OK);
// }
@RequestMapping(value = URLConstant.DELETE_IMAGE, method = RequestMethod.POST)
public ResponseEntity<?> deleteImageByProduct(@RequestParam(ParamConstants.PRODUCT_ID) int productId) {
String delSuccess = "delete successful";
imageServiceInterface.deleteImageByProduct(productId);
return new ResponseEntity<String> (delSuccess, HttpStatus.OK);
}
}
|
/**
* 1849. Splitting a String Into Descending Consecutive Values
* Medium
* 不应该一开始就考虑剪枝的,应该先考虑最容易通过的方法
*/
public class Solution {
private boolean dfs(String s, int i, long pre, int len) {
if (pre == 0 || len == 0) {
return false;
}
int start = i;
for (int j = i; j < s.length(); j++) {
if (s.charAt(j) != '0') {
break;
}
start++;
}
if (pre == 1) {
start--;
}
long next = pre - 1;
int l = 0;
boolean flag = true;
String ns = String.valueOf(next);
for (int j = start, k = 0; k < ns.length(); j++, k++) {
if (j == s.length() || s.charAt(j) != ns.charAt(k)) {
flag = false;
break;
}
l++;
}
if (flag) {
if (start + l == s.length()) {
return true;
}
return dfs(s, start + l, next, l);
}
return false;
}
public boolean splitString(String s) {
int start = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != '0') {
break;
}
start++;
}
long cur = 0;
int l = 0;
for (int i = start; i < s.length(); i++) {
cur = cur * 10 + (s.charAt(i) - '0');
l++;
if (l > (s.length() / 2 + 1)) {
return false;
}
if (dfs(s, i + 1, cur, l)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
String[] strs = {"200100", "99999999999999999998", "10", "64424509442147483647", "1234", "050043", "9080701", "10009998" };
Solution sol = new Solution();
for (String s : strs) {
System.out.println(sol.splitString(s));
}
}
}
|
package acceptanceTest;
import basetest.BaseTest;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import pages.LandingPageFacebook;
import pages.LaunchPageFacebook;
import pages.LoginPageFacebook;
import pages.ProfilePageFacebook;
import util.ExtentManager;
/**
* Created by acedric on 24/06/2017.
*/
public class ProfileTestFacebook extends BaseTest {
@Test
public void testProfile(){
reports = ExtentManager.getInstance();
reports.startTest("Starting Test");
openBrowser("chrome");
LaunchPageFacebook launchPageFacebook = PageFactory.initElements(driver, LaunchPageFacebook.class);
LoginPageFacebook loginPageFacebook = launchPageFacebook.goToFBHomePage();
loginPageFacebook.verifyTitle("facebook");
Object page = loginPageFacebook.doLogin("asouptalla@yahoo.com", "Pepe0987654321");
if (page instanceof LoginPageFacebook)
Assert.fail("Login failed");
else if (page instanceof LandingPageFacebook)
System.out.println("Login Passed");
LandingPageFacebook landingPageFacebook = (LandingPageFacebook)page;
ProfilePageFacebook profilePageFacebook = landingPageFacebook.goToProfilePage();
profilePageFacebook.getTopMenu().goToSetting();
// LaunchPageFacebook launchPageFacebook = new LaunchPageFacebook();
// LoginPageFacebook loginPageFacebook = launchPageFacebook.goToFBHomePage();
// LandingPageFacebook page = loginPageFacebook.doLogin("", "");
// page.goToProfilePage();
/*
System.setProperty("webdriver.chrome.driver","C:\\Users\\acedric\\IdeaProjects\\Ashish\\src\\test\\java\\ashish\\chromedriver.exe");
driver = new ChromeDriver();
*/
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.b2c.services.order.strategy;
import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull;
import de.hybris.platform.commerceservices.order.impl.DefaultCommerceCartCalculationStrategy;
import de.hybris.platform.commerceservices.service.data.CommerceCartParameter;
import de.hybris.platform.core.model.order.CartModel;
import de.hybris.platform.order.CalculationService;
import de.hybris.platform.order.exceptions.CalculationException;
import de.hybris.platform.promotions.jalo.PromotionsManager.AutoApplyMode;
/**
*
*/
public class EzgCommerceCartCalculationStrategy extends DefaultCommerceCartCalculationStrategy
{
@Override
public boolean calculateCart(CommerceCartParameter parameter)
{
final CartModel cartModel = parameter.getCart();
validateParameterNotNull(cartModel, "Cart model cannot be null");
final CalculationService calcService = getCalculationService();
boolean recalculated = false;
if (calcService.requiresCalculation(cartModel))
{
try
{
parameter.setRecalculate(false);
beforeCalculate(parameter);
calcService.calculate(cartModel);
getPromotionsService().updatePromotions(getPromotionGroups(), cartModel, true, AutoApplyMode.APPLY_ALL,
AutoApplyMode.APPLY_ALL, getTimeService().getCurrentTime());
}
catch (final CalculationException calculationException)
{
throw new IllegalStateException("Cart model " + cartModel.getCode() + " was not calculated due to: "
+ calculationException.getMessage());
}
finally
{
afterCalculate(parameter);
}
recalculated = true;
}
// if (calculateExternalTaxes)
// {
// getExternalTaxesService().calculateExternalTaxes(cartModel);
// }
return recalculated;
}
}
|
package app0510.gugudan;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
public class ActionControl implements ActionListener{
JTextField t_input;
public ActionControl(JTextField t_input) {
this.t_input=t_input;
}
@Override
public void actionPerformed(ActionEvent e) {
int dan=Integer.parseInt(t_input.getText());
printDan(dan);
}
public void printDan(int dan) {
for(int i=1; i<=9; i++) {
System.out.println(dan+"*"+i+"="+(dan*i));
}
}
}
|
package shawn.designpattern.adapter;
public class Iphone extends Phone implements LightningChargable {
public Iphone(boolean cableConnected, int batteryPercentage) {
super(cableConnected, batteryPercentage);
}
@Override
public void connect() {
System.out.println("라이트닝 케이블을 연결한다.");
this.connectCable();
}
@Override
public boolean isFullyCharged() {
return this.getBatteryPercentage() == 100;
}
@Override
public void charge() {
this.setBatteryPercentage(100);
}
}
|
/**
*
*/
package com.cnk.travelogix.operation.interceptor;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.InterceptorException;
import de.hybris.platform.servicelayer.interceptor.PrepareInterceptor;
import de.hybris.platform.servicelayer.keygenerator.KeyGenerator;
import org.springframework.beans.factory.annotation.Required;
import com.cnk.travelogix.datamodel.operation.reconfirmationconfig.model.ReconfirmationConfigModel;
/**
* This PrepareInterceptor generate the unique code for reconfirmaion config model based on configured number generator
* series
*
* @author C5244543
*
*/
public class ReconfirmationConfigPrepareInterceptor implements PrepareInterceptor<ReconfirmationConfigModel>
{
private KeyGenerator keyGenerator;
@Override
public void onPrepare(final ReconfirmationConfigModel model, final InterceptorContext ctx) throws InterceptorException
{
if (ctx.isNew(model))
{
model.setCode((String) this.keyGenerator.generate());
}
}
@Required
public void setKeyGenerator(final KeyGenerator keyGenerator)
{
this.keyGenerator = keyGenerator;
}
}
|
package fotoshop.GUI.SequencePanel;
import fotoshop.Events.PropertyMessage;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
/**
* Panel displayed in a dialog by the {@link FilterSequencePanel} for constructing
* a new sequence of filters that should be applied to the current image
* @see #SequenceConstructorPanel(java.util.List)
* @see #addFiltersList(java.lang.String)
* @see #getName()
* @see #getReturnList()
* @see TextField_Change
* @author Benjamin Nicholls, bn65@kent.ac.uk
*/
public class SequenceConstructorPanel extends JPanel{
/**
* The working sequence, list of messages (indicating the filter to apply)
*/
private List<PropertyMessage> messageList = new ArrayList<PropertyMessage>();
/**
* name of the current working sequence
*/
private String sequenceName = null;
/**
* filters that have currently been selected to be in this sequence
*/
private JPanel sequencesPanel = new JPanel();
/**
* Layout constraints of the panel
*/
private GridBagConstraints thisC = new GridBagConstraints();
/**
* Initialise the constructor panel with a list of filters. Set up the layout of the
* panels components, create a list of buttons to allow the addition of filters
* to the sequence, and a textbox to allow the naming of the sequence
* @param filters List of available filters (names) that can be added to
* the sequence
* @see TextField_Change
*/
public SequenceConstructorPanel(List<String> filters){
JPanel buttonPanel = new JPanel();
this.setLayout(new GridBagLayout());
GridBagConstraints buttonC = new GridBagConstraints();
thisC.gridx = 0;
thisC.gridy = 0;
thisC.fill = GridBagConstraints.HORIZONTAL;
this.add(new JLabel("Choose filters to apply"), thisC);
thisC.gridy = 1;
thisC.fill = GridBagConstraints.NONE;
this.add(new JLabel("Sequence Name: "), thisC);
thisC.fill = GridBagConstraints.HORIZONTAL;
thisC.gridx = 1;
//Text field for naming the sequence
JTextField nameField = new JTextField();
nameField.addKeyListener(new KeyAdapter(){
@Override
public void keyPressed(KeyEvent event){
JTextField field = (JTextField) event.getSource();
sequenceName = field.getText();
}
});
this.add(nameField, thisC);
thisC.fill = GridBagConstraints.VERTICAL;
thisC.gridy = 2;
thisC.gridx = 0;
this.add(buttonPanel, thisC);
thisC.gridx = 1;
this.add(sequencesPanel, thisC);
sequencesPanel.setLayout(new BorderLayout());
JLabel label = new JLabel("Filter sequence:");
buttonPanel.setLayout(new GridBagLayout());
buttonC.fill = GridBagConstraints.HORIZONTAL;
buttonC.gridx = 0;
buttonC.gridy = 0;
buttonC.anchor = GridBagConstraints.PAGE_START;
//Create buttons for adding to the sequence
buttonPanel.add(new JLabel("Available Filters:"), buttonC);
addFiltersList(null);
JButton optionButton;
for(String s : filters){
buttonC.gridy = buttonC.gridy+1;
optionButton = new JButton(s);
optionButton.addActionListener(new FilterButtonListener(s));
buttonPanel.add(optionButton, buttonC);
}
}
/**
* Reconstruct the {@link #sequencesPanel}, adding a new filter.
* Removing all components and adding labels
* for each filter in the current sequence to a JScrollPane. Also added is a
* JFormattedTextField to allow values to be given to the sequence entry (i.e
* the number of 90 degree rotations to perform, or the percentage to increase the
* brightness by - to a max of %100).
* @param s
* @see TextField_Change
*/
public void addFiltersList(String s){
List<String> entry = new ArrayList<String>();
//Add value s to the messageList
if(s != null){
entry.add(s);
messageList.add(new PropertyMessage(s, 0, true));
}
sequencesPanel.removeAll();
//Set the layout of the panel
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel label = new JLabel("Filter sequence:");
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
panel.setLayout(layout);
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(label, c);
c.gridy = 1;
c.fill = GridBagConstraints.NONE;
c.weightx = 0.5;
label = new JLabel("Filter");
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
panel.add(label, c);
c.gridx = 1;
c.weightx = 1;
label = new JLabel("Value");
label.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
panel.add(label, c);
c.fill = GridBagConstraints.NONE;
JFormattedTextField valueField;
int n = 0;
JPanel scrollPanel = new JPanel();
scrollPanel.setLayout(new GridBagLayout());
//Add a label JFormattedTextField pair for each PropertyMessage in messageList
for(PropertyMessage msg : messageList){
c.gridy = n;
c.gridx = 0;
c.weightx = 0.5;
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.NONE;
label = new JLabel(n+1 + ": " + msg.getName());
//label.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
scrollPanel.add(label, c);
c.gridx = 1;
c.anchor = GridBagConstraints.EAST;
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumIntegerDigits(100);
valueField = new JFormattedTextField(format);
//valueField.setValue(new Integer(filter.get(1)));
valueField.setValue(new Float(msg.getValue()));
valueField.setBorder(BorderFactory.createLineBorder(Color.BLACK));
valueField.addPropertyChangeListener(new TextField_Change(msg, n));
scrollPanel.add(valueField, c);
n++;
}
JScrollPane scroller = new JScrollPane(scrollPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroller.setPreferredSize(new Dimension(200, sequencesPanel.getPreferredSize().height));
c.gridx = 0;
c.gridy = c.gridy+1;
c.fill = GridBagConstraints.CENTER;
panel.add(scroller, c);
sequencesPanel.add(scroller);
validate();
}
/**
* Get the sequence name
* @return {@link #sequenceName}
*/
public String getName(){
return sequenceName;
}
/**
* Get the sequence of filters to apply
* @return {@link #messageList}
*/
public List<PropertyMessage> getReturnList(){
return messageList;
}
/**
* Listener for the Text fields used by the constructor panel. Any change in
* text attempts to update the textfields {@link #entry} and messageList
* {@link #index}
*/
public class TextField_Change implements PropertyChangeListener {
/**
* PropertyMessage the text field will edit
*/
private PropertyMessage entry;
/**
* index the entry should be put into the {@link #messageList}
*/
private int index;
/**
* Initialise the Listener with the PropertyMessage entry and int index value
* @param entry PropertyMessage applied to entry
* @param n int applied to index
*/
public TextField_Change(PropertyMessage entry, int n){
this.entry = entry;
this.index = n;
}
public void propertyChange(PropertyChangeEvent event){
JFormattedTextField source = (JFormattedTextField) event.getSource();
Integer str = ((Number)source.getValue()).intValue();
entry.setValue(str);
messageList.set(index, entry);
}
}
/**
* Listener for buttons that add filters to the working {@link #messageList sequence}
* Initialised with a string value, which is {@link #addFiltersList(java.lang.String)} added
* to the filtersList on activation.
*/
public class FilterButtonListener implements ActionListener{
/**
* Value to add to the messageList
*/
String filterName;
/**
* Initialise the listener with value s
* @param s String value to apply to filterName
*/
public FilterButtonListener(String s){
this.filterName = s;
}
@Override
public void actionPerformed(ActionEvent ae) {
addFiltersList(this.filterName);
}
}
}
|
package com.tencent.mm.plugin.account.friend.a;
import android.database.Cursor;
import com.tencent.mm.bt.h;
import com.tencent.mm.sdk.e.j;
import com.tencent.mm.sdk.platformtools.bi;
public final class q extends j {
public static final String[] diD = new String[]{"CREATE TABLE IF NOT EXISTS invitefriendopen ( username text PRIMARY KEY , friendtype int , updatetime int , reserved1 int , reserved2 int , reserved3 text , reserved4 text ) "};
private h dCZ;
public q(h hVar) {
this.dCZ = hVar;
}
public final boolean a(p pVar) {
if (pz(pVar.getUsername())) {
pVar.bWA = -1;
if (this.dCZ.update("invitefriendopen", pVar.wH(), "username=?", new String[]{pVar.getUsername()}) > 0) {
return true;
}
return false;
}
pVar.bWA = -1;
if (((int) this.dCZ.insert("invitefriendopen", "username", pVar.wH())) == -1) {
return false;
}
return true;
}
public final boolean pz(String str) {
Cursor b = this.dCZ.b("select invitefriendopen.username,invitefriendopen.friendtype,invitefriendopen.updatetime,invitefriendopen.reserved1,invitefriendopen.reserved2,invitefriendopen.reserved3,invitefriendopen.reserved4 from invitefriendopen where invitefriendopen.username = \"" + bi.oU(str) + "\"", null, 2);
boolean moveToFirst = b.moveToFirst();
b.close();
return moveToFirst;
}
}
|
package ua.project.protester.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ValidationDataSetResponse {
private String dataSetName;
private ValidationDataSetStatus status;
private List<String> missingParameters;
}
|
/*
* Copyright 2013-4 Red Hat Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.ui.provider;
import java.io.OutputStream;
import org.overlord.rtgov.ui.client.model.ResolutionState;
import org.overlord.rtgov.ui.client.model.BatchRetryResult;
import org.overlord.rtgov.ui.client.model.MessageBean;
import org.overlord.rtgov.ui.client.model.SituationBean;
import org.overlord.rtgov.ui.client.model.SituationSummaryBean;
import org.overlord.rtgov.ui.client.model.SituationsFilterBean;
import org.overlord.rtgov.ui.client.model.UiException;
/**
* This interface represents a provider that can supply information about
* 'Situations'.
*
*/
public interface SituationsProvider {
/**
* This method returns the name of the provider.
*
* @return The provider name
*/
public String getName();
/**
* This method adds a new situation event listener.
*
* @param l The situation event listener
*/
public void addSituationEventListener(SituationEventListener l);
/**
* This method removes a situation event listener.
*
* @param l The situation event listener
*/
public void removeSituationEventListener(SituationEventListener l);
/**
* Search for services using the given filters and search text.
*
* @param filters The filters
* @return The list of situation summaries
* @throws UiException Failed to search situations
*/
public java.util.List<SituationSummaryBean> search(SituationsFilterBean filters) throws UiException;
/**
* Fetches a full situation by its id.
*
* @param id The situation id
* @throws UiException Failed to retrieve the situation
*/
public SituationBean getSituation(String id) throws UiException;
/**
* This method resubmits the supplied message to the service associated
* with the identified situation.
*
* @param situationId The situation id
* @param message The message
* @param username The user performing the resubmit
* @throws UiException
*/
public void resubmit(String situationId, MessageBean message, String username) throws UiException;
/**
* Retrieve the resubmission failures for the specified situation.
*
* @param situationId The situation id
* @return The list of situation summaries
* @throws UiException Failed to retrieve resubmission failures
*/
public java.util.List<SituationSummaryBean> getResubmitFailures(String situationId) throws UiException;
/**
* This method export all situation's matching the given filter criteria
*
* @param filters
* @param outputStream
* Failed to search situations
*/
public void export(SituationsFilterBean filters, OutputStream outputStream);
/**
* This method resubmits all situation's matching the given filter criteria
*
* @param filters The filters
* @param username The user doing the resubmit
* @return The {@link BatchRetryResult}
* @throws UiException
* Failed to search situations
*/
public BatchRetryResult resubmit(SituationsFilterBean filters, String username) throws UiException;
/**
* This method deletes all situation's matching the given filter criteria
*
* @param filters The filters
* @return The {@link BatchRetryResult}
* @throws UiException
* Failed to delete situations
*/
public int delete(SituationsFilterBean filters) throws UiException;
public void assign(final String situationId, final String userName) throws UiException;
public void unassign(final String situationId) throws UiException;
public void updateResolutionState(final String situationId, final ResolutionState resolutionState)
throws UiException;
}
|
package com.tyss.cg.polymorphism;
public class MethodOverridingClass2 implements MethodsInterface {
@Override
public String displayMessage() {
return "overriden displayMessage() of MethodsInterface from MethodOverridingClass2";
}
@Override
public String printMessage() {
return "overring printMessage() of MethodInterface from MethodOverridingClass2";
}
}
|
/*
* 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 pbo2.pkg10118071.latihan20.targetsaldotabungan;
// package scanner
import java.util.Scanner;
/**
*
* @author
* NAMA : David Aditya Winarto
* KELAS : PBO2
* NIM : 10118071
* Deskripsi Program : Program ini berisi program untuk menampilkan
* perhitungan target saldo tabungan
*
*/
public class PBO210118071Latihan20TargetSaldoTabungan {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// membuat objek dari class scanner
Scanner input = new Scanner(System.in);
// variabel untuk menyimpan input dari user
int saldoAwal, saldoTarget, saldo, bunga;
System.out.print("Saldo Awal \t : Rp. ");
saldoAwal = input.nextInt();
System.out.print("Bunga/Bulan(%) \t : ");
bunga = input.nextInt();
System.out.print("Saldo Target \t : Rp. ");
saldoTarget = input.nextInt();
saldo = saldoAwal;
int i = 1;
System.out.println();
while (saldo < saldoTarget) {
saldo = (saldo * bunga / 100) + saldo;
System.out.println("Saldo di bulan ke-" + i + " Rp." + saldo);
i++;
}
}
}
|
package ua.project.protester.request;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Getter
public class BaseFilter {
protected final Integer pageSize;
protected final Integer pageNumber;
protected final String filterName;
public Integer getOffset() {
return (pageNumber - 1) * pageSize;
}
}
|
package server;
import com.google.cloud.firestore.DocumentSnapshot;
import controllers.Constants;
import models.Schedule;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import utils.DatabaseUtil;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@CrossOrigin(origins = "https://tsuresh.github.io", maxAge = 3600)
@RestController
@RequestMapping("/api/v1/bookings")
public class BookingController {
private static final String TAG = "BookingController";
public static ResponseEntity<Response> getAvailability(String plateNumber, String fromDate, String toDate) {
Date dateFrom = null, dateTo = null;
try {
dateFrom = new Date(fromDate);
dateTo = new Date(toDate);
} catch (Exception e) {
return new ResponseEntity(new Response(Constants.ERROR, "Unable to cast the given date"), HttpStatus.BAD_REQUEST);
}
long fromDateTimestamp = dateFrom.getTime();
long toDateTimestamp = dateTo.getTime();
for (DocumentSnapshot document : DatabaseUtil.getCollection(Constants.VEHICLES + "/" + plateNumber + "/scheduleList")) {
Schedule schedule = document.toObject(Schedule.class);
if (fromDateTimestamp <= schedule.getDateFrom() && schedule.getDateFrom() <= toDateTimestamp) {
return new ResponseEntity(new Response(Constants.ERROR, "An existing booking clases with your date range"), HttpStatus.CONFLICT);
}
if (fromDateTimestamp <= schedule.getDateTo() && schedule.getDateTo() <= toDateTimestamp) {
return new ResponseEntity(new Response(Constants.ERROR, "An existing booking clases with your date range"), HttpStatus.CONFLICT);
}
}
return new ResponseEntity(new Response(Constants.SUCCESS, "The vehicle is available for booking"), HttpStatus.OK);
}
@GetMapping("/{vehicleID}")
public List<Schedule> getBookings(@PathVariable String vehicleID) {
List<Schedule> schedules = new ArrayList<>();
for (DocumentSnapshot document : DatabaseUtil.getCollection(Constants.VEHICLES + "/" + vehicleID + "/scheduleList")) {
Schedule schedule = document.toObject(Schedule.class);
schedule.setBookingId(document.getId());
schedules.add(schedule);
}
return schedules;
}
@PostMapping("/isBooked")
public ResponseEntity<Response> isBooked(@Valid @RequestBody AvailabilityBody availabilityBody) {
if (availabilityBody.getPlateNumber() == null || availabilityBody.getPlateNumber().isEmpty()) {
return new ResponseEntity(new Response(Constants.ERROR, "Plate number must be there"), HttpStatus.BAD_REQUEST);
}
return getAvailability(availabilityBody.getPlateNumber(), availabilityBody.getDateFrom(), availabilityBody.getDateTo());
}
@PostMapping("")
public ResponseEntity<Response> makeBooking(@Valid @RequestBody BookingBody bookingBody) {
ResponseEntity<Response> availabilityResponse = getAvailability(bookingBody.getPlateNumber(), bookingBody.getDateFrom(), bookingBody.getDateTo());
if (availabilityResponse.getBody().getMessage().equals(Constants.SUCCESS)) {
return manageBooking(bookingBody, "");
} else {
return availabilityResponse;
}
}
@PutMapping("")
public ResponseEntity<Response> updateBooking(@Valid @RequestBody BookingBody bookingBody) {
if (bookingBody.getBookingId() == null || bookingBody.getBookingId().isEmpty()) {
return new ResponseEntity(new Response(Constants.ERROR, "THe booking ID must not be empty!"), HttpStatus.BAD_REQUEST);
}
ResponseEntity<Response> availabilityResponse = getAvailability(bookingBody.getPlateNumber(), bookingBody.getDateFrom(), bookingBody.getDateTo());
if (availabilityResponse.getBody().getMessage().equals(Constants.SUCCESS)) {
return manageBooking(bookingBody, bookingBody.getBookingId());
} else {
return availabilityResponse;
}
}
@DeleteMapping("/{plateNumber}/{bookingId}")
public ResponseEntity<Response> deleteBooking(@PathVariable String plateNumber, @PathVariable String bookingId) {
if (DatabaseUtil.deleteData(Constants.VEHICLES + "/" + plateNumber + "/scheduleList", bookingId)) {
return new ResponseEntity(new Response("SUCCESS", "Successfully deleted"), HttpStatus.ACCEPTED);
} else {
return new ResponseEntity(new Response("FAILED", "Unable to delete booking"), HttpStatus.BAD_REQUEST);
}
}
private ResponseEntity<Response> manageBooking(BookingBody bookingBody, String bookingID) {
if (bookingBody.getAddress() == null || bookingBody.getAddress().isEmpty()) {
return new ResponseEntity(new Response(Constants.ERROR, "Your address must be there"), HttpStatus.BAD_REQUEST);
}
if (bookingBody.getFullName() == null || bookingBody.getFullName().isEmpty()) {
return new ResponseEntity(new Response(Constants.ERROR, "Your full name must be there"), HttpStatus.BAD_REQUEST);
}
if (bookingBody.getContactNumber() == null || bookingBody.getContactNumber().isEmpty()) {
return new ResponseEntity(new Response(Constants.ERROR, "Your contact number must be there"), HttpStatus.BAD_REQUEST);
}
Schedule schedule = new Schedule(
bookingBody.getAddress(),
bookingBody.getIsVerified(),
bookingBody.getContactNumber(),
new Date(bookingBody.getDateTo()).getTime(),
bookingBody.getFullName(),
new Date(bookingBody.getDateFrom()).getTime()
);
if (bookingID.isEmpty()) {
if (DatabaseUtil.addData(schedule, Constants.VEHICLES + "/" + bookingBody.getPlateNumber() + "/scheduleList")) {
return new ResponseEntity(new Response(Constants.SUCCESS, "Successfully made the booking"), HttpStatus.CREATED);
} else {
return new ResponseEntity(new Response(Constants.ERROR, "Failed to add new booking"), HttpStatus.BAD_REQUEST);
}
} else {
if (DatabaseUtil.addData(schedule, Constants.VEHICLES + "/" + bookingBody.getPlateNumber() + "/scheduleList", bookingID)) {
return new ResponseEntity(new Response(Constants.SUCCESS, "Successfully updated the booking"), HttpStatus.ACCEPTED);
} else {
return new ResponseEntity(new Response(Constants.ERROR, "Failed to update the booking"), HttpStatus.BAD_REQUEST);
}
}
}
}
|
package ru.progwards.java1.lessons.basics;
public class ReverseDigits {
public static int reverseDigits(int number){
int number1 = number % 10;
int number2 = (number / 10)%10;
int number3 = number / 100;
return number = (number1 * 100) + (number2 * 10) + (number3);
}
public static void main(String[] args) {
System.out.println(reverseDigits(257));
}
}
|
package com.landa.adapter;
import java.io.File;
import android.content.Context;
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 com.landa.fileexplorermanager.R;
import com.landa.features.BrowseHandler;
public class ClipboardFileListAdapter extends BaseAdapter {
private final Context context;
private final File[] data;
public ClipboardFileListAdapter(Context context, File[] values) {
this.context = context;
this.data = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//View rowView = convertView;
//if(rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_row, parent, false);
//}
File f = data[position];
TextView textView = (TextView) rowView.findViewById(R.id.file_name);
TextView fullPath = (TextView) rowView.findViewById(R.id.full_path);
ImageView imageView = (ImageView) rowView.findViewById(R.id.file_image);
textView.setText(f.getName());
fullPath.setText(f.getAbsolutePath());
imageView.setImageResource(
BrowseHandler.getFileIconResourceId(f.getAbsolutePath()));
return rowView;
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
} |
package com.sapient.springboot.model;
public class Description {
private int deptId;
private String name;
private String deptDescription;
public Description() {
super();
}
public Description(int deptId, String deptDescription) {
this.deptId = deptId;
this.deptDescription = deptDescription;
}
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDeptDescription() {
return deptDescription;
}
public void setDeptDescription(String deptDescription) {
this.deptDescription = deptDescription;
}
}
|
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Random;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.statistics.HistogramDataset;
/**
* @author Kayhan Dehghani Mohammadi
* Spring 2017
* CMPT 365 Assignment 1
* Image Editor
*/
public class ImageUtility {
//Returns the grayscale of the original image
public static BufferedImage makeGrayScale(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage resultImage = new BufferedImage(width, height, image.getType());
for(int y=0; y<height; y++){
for(int x=0; x<width; x++){
Color c = new Color(image.getRGB(x, y));
int red = (int)(c.getRed() * 0.299);
int green = (int)(c.getGreen() * 0.587);
int blue = (int)(c.getBlue() *0.114);
Color newColor = new Color(red+green+blue,
red+green+blue,red+green+blue);
resultImage.setRGB(x,y,newColor.getRGB());
}
}
return resultImage;
}
// makes a histogram of the grayscale of the image
// Returns an image of the histogram
// Warning: for color images the histogram will only show the blue
public static BufferedImage makeGrayscaleHistogram(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
ArrayList<Integer> histFreq = new ArrayList<>();
double[] histFreqdouble = new double[width+height];
Color c;
for(int y=0; y<height; y++){
for(int x=0; x<width; x++){
c = new Color(image.getRGB(x, y));
histFreq.add(c.getBlue());
}
}
for(int i=0; i<width+height; i++) {
histFreqdouble[i] = (double) histFreq.get(i);
}
HistogramDataset histogramdataset = new HistogramDataset();
histogramdataset.addSeries("Grayscale Histogram", histFreqdouble, 256);
JFreeChart histogram = ChartFactory.createHistogram("Histogram", "gray value", "frequency [# of pixels]", histogramdataset, PlotOrientation.VERTICAL, true, true, false);
return histogram.createBufferedImage(700,400);
}
// Returns the gamma corrected version of the image
public static BufferedImage applyGammaCorrection(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage resultImage = new BufferedImage(width, height, image.getType());
double gamma_inversed = 1/2.2;
for(int y=0; y<height; y++){
for(int x=0; x<width; x++){
Color c = new Color(image.getRGB(x, y));
int red = (int) (255 * (Math.pow((double) c.getRed() / (double) 255, gamma_inversed)));
int green = (int) (255 * (Math.pow((double) c.getGreen() / (double) 255, gamma_inversed)));
int blue = (int) (255 * (Math.pow((double) c.getBlue() / (double) 255, gamma_inversed)));
Color newColor = new Color(red,green,blue);
resultImage.setRGB(x,y,newColor.getRGB());
}
}
return resultImage;
}
// invert the image
public static BufferedImage invertImage(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage resultImage = new BufferedImage(width, height, image.getType());
for(int y=0; y<height; y++){
for(int x=0; x<width; x++){
Color c = new Color(image.getRGB(x, y));
int red = (int) (255-c.getRed());
int green = (int) (255-c.getGreen());
int blue = (int) (255-c.getBlue());
Color newColor = new Color(red,green,blue);
resultImage.setRGB(x,y,newColor.getRGB());
}
}
return resultImage;
}
// apply ordered dithering to the image
// Warning: input should be grayscale otherwise only the blue will be affected
public static BufferedImage grayscalOrderedDither(BufferedImage image) {
Random random = new Random();
int n = 5;
int[][] ditherMatrix = new int[n][n];
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
ditherMatrix[i][j] = random.nextInt(255);
}
}
int width = image.getWidth();
int height = image.getHeight();
BufferedImage resultImage = new BufferedImage(width, height, image.getType());
int i,j,grayValue;
Color c;
for(int x=0; x<width; x++){
for(int y=0; y<height; y++){
i = x % ditherMatrix.length;
j = y % ditherMatrix.length;
c = new Color(image.getRGB(x, y));
grayValue = (int) (c.getBlue());
if(grayValue > ditherMatrix[i][j]) {
resultImage.setRGB(x,y,Color.WHITE.getRGB());
}
else{
resultImage.setRGB(x,y,Color.BLACK.getRGB());
}
}
}
return resultImage;
}
}
|
package com.microsilver.mrcard.basicservice.dao;
import com.microsilver.mrcard.basicservice.model.FxSdUserPreReg;
import com.microsilver.mrcard.basicservice.model.FxSdUserPreRegExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface FxSdUserPreRegMapper {
int countByExample(FxSdUserPreRegExample example);
int deleteByExample(FxSdUserPreRegExample example);
int deleteByPrimaryKey(Long mobile);
int insert(FxSdUserPreReg record);
int insertSelective(FxSdUserPreReg record);
List<FxSdUserPreReg> selectByExample(FxSdUserPreRegExample example);
FxSdUserPreReg selectByPrimaryKey(Long mobile);
int updateByExampleSelective(@Param("record") FxSdUserPreReg record, @Param("example") FxSdUserPreRegExample example);
int updateByExample(@Param("record") FxSdUserPreReg record, @Param("example") FxSdUserPreRegExample example);
int updateByPrimaryKeySelective(FxSdUserPreReg record);
int updateByPrimaryKey(FxSdUserPreReg record);
} |
package com.ibeiliao.pay.impl.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.ibeiliao.pay.datasource.MyBatisDao;
import com.ibeiliao.pay.impl.entity.PayLogPO;
/**
* t_pay_log 表的操作接口
*
* @author linyi 2016-07-10
*/
@MyBatisDao
public interface PayLogDao {
/**
* 保存数据
*
* @param po 要保存的对象
*/
void insert(PayLogPO po);
/**
* 修改数据,以主键更新
*
* @param po - 要更新的数据
* @return 更新的行数
*/
int update(PayLogPO po);
/**
* 根据主键读取记录
*/
public PayLogPO get(@Param("logId") long logId);
}
|
package com.habit.secrect.service.user;
import java.util.List;
import com.habit.secrect.bean.user.Comment;
import com.habit.secrect.bean.user.Msg;
public interface MsgService {
/**
* 查询所有的消息列表
*
* @param userId
* @param integer
* @param pageSize
* @return
*/
public List<Msg> getMsgList(int page, int pageSize);
/**
* 添加消息
*
* @param msg
* @return
*/
public boolean addMsg(Msg msg);
}
|
package pr01_m8;
import java.io.*;
import java.io.*;
public class pr01_m8{
public static void main(String[] args) throws IOException{
File f=new File("fitxer.html");
try (BufferedWriter bw=new BufferedWriter(new FileWriter(f))){
bw.write("<html>");
bw.newLine();
bw.write(" <head>");
bw.newLine();
bw.write(" <title>");
bw.newLine();
bw.write(" Nova pàgina web");
bw.newLine();
bw.write(" </title>");
bw.newLine();
bw.write(" </head>");
bw.newLine();
bw.write(" <body>");
bw.newLine();
bw.write(" Nova pàgina web");
bw.newLine();
bw.write(" </body>");
bw.newLine();
bw.write("</html>");
bw.newLine();
bw.write("-------------------------------");
bw.newLine();
bw.close();
}
}
}
|
package com.aldeir.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.aldeir.model.Materias;
public interface MateriasRepository extends JpaRepository<Materias, Integer> {
}
|
package net.plazmix.core.api.common.orm;
import com.google.common.base.Preconditions;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
public abstract class AbstractDataContainer<T, ID> implements DataContainer<T, ID> {
private final String name, primaryColumnName;
private final Map<String, Column> columnMap;
private final Function<Data, T> objectMapper;
private final Function<T, Data> dataMapper;
protected AbstractDataContainer(String name, Map<String, Column> columnMap, Function<Data, T> objectMapper, Function<T, Data> dataMapper) {
this.name = name;
this.columnMap = Collections.unmodifiableMap(columnMap);
this.primaryColumnName = getPrimaryColumnName(columnMap);
this.objectMapper = objectMapper;
this.dataMapper = dataMapper;
}
private String getPrimaryColumnName(Map<String, Column> columnMap) {
String primaryColumnName = null;
for (Column column : columnMap.values()) {
if (primaryColumnName != null)
throw new IllegalArgumentException("Container cannot contain more than one primary column!");
if (column.isPrimary()) {
primaryColumnName = column.getName();
break;
}
}
if (primaryColumnName == null)
throw new IllegalArgumentException("Primary column not found!");
return primaryColumnName;
}
@Override
public String getName() {
return name;
}
@Override
public Iterable<Column> getColumns() {
return columnMap.values();
}
@Override
public Collection<String> getColumnNames() {
return columnMap.keySet();
}
@Override
public Column getPrimaryColumn() {
return getColumnByName(primaryColumnName);
}
@Override
public Column getColumnByName(String columnName) {
Preconditions.checkArgument(columnMap.containsKey(columnName), "Column %s is not found!", columnName);
return columnMap.get(columnName);
}
@Override
public Function<Data, T> getObjectMapper() {
return objectMapper;
}
@Override
public Function<T, Data> getDataMapper() {
return dataMapper;
}
}
|
package com.gamemaker.entity;
import java.util.ArrayList;
import java.util.List;
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.OneToMany;
@Entity
public class GameDetails {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private String path;
@OneToMany(mappedBy= "gameId", cascade = CascadeType.ALL)
private List<PlayerDetails> playerDetails;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<PlayerDetails> getPlayerDetails() {
return playerDetails;
}
public void setPlayerDetails(List<PlayerDetails> playerDetails) {
this.playerDetails = playerDetails;
}
public void addPlayerDetails(PlayerDetails details) {
if(playerDetails == null)
playerDetails = new ArrayList<>();
playerDetails.add(details);
}
}
|
/*
* 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 algoritmos;
import amc_practica2a.Punto;
import java.util.ArrayList;
import java.util.Random;
/**
*
* @author usuario
*/
public class Algoritmos {
ArrayList<Punto> puntos;
public ArrayList<Punto> GenerarPuntosAleatorios(int talla){
Random rnd = new Random(System.currentTimeMillis());
ArrayList<Punto> ArrayDePuntos = new ArrayList();
Punto[] puntosAleatorios;
puntosAleatorios = new Punto[talla];
System.out.println("Generando Puntos Aleatorios");
for (int i = 0; i < talla; i++) {
int puntox = rnd.nextInt(10000);
int puntoy = rnd.nextInt(10000);;
puntosAleatorios[i] = new Punto(puntox,puntoy);
ArrayDePuntos.add(puntosAleatorios[i]);
}
return ArrayDePuntos;
}
public ArrayList<Punto> GenerarPuntosAleatoriosPeor(int talla){
Random rnd = new Random(System.currentTimeMillis());
ArrayList<Punto> ArrayDePuntos = new ArrayList();
Punto puntoAux;
System.out.println("Generando Puntos Aleatorios");
// Para generar los puntos todos en la bisectriz, pongo un mismo x
int coordX = rnd.nextInt(10000);
for (int i = 0; i < talla; i++) {
int coordY = rnd.nextInt(10000);
puntoAux = new Punto(coordX,coordY);
ArrayDePuntos.add(puntoAux);
}
return ArrayDePuntos;
}
public void OrdenarArrayPunto(ArrayList<Punto> elementos){
int p,j;
Punto aux;
for(p=1; p<elementos.size();p++){
aux = elementos.get(p);
j = p-1;
while((j>=0)&&(aux.getX() < elementos.get(j).getX())){
elementos.set(j+1, elementos.get(j));
j--;
}
elementos.set(j+1,aux);
}
}
public void mostrarArrayList(ArrayList<Punto> puntos){
for(int i=0; i<puntos.size();i++){
System.out.println("x: "+puntos.get(i).getX()+" - y: "+puntos.get(i).getY());
}
}
public double DistanciaMinimaDyV(ArrayList<Punto> puntos){
double solucion1, solucion2, solucionfinal;
int medio;
if(puntos.size()>3)
{
medio = (int) Math.round((puntos.get(0).getX()+puntos.get(puntos.size()-1).getX())/2);
solucion1 = DistanciaMinimaDyV(Particion(puntos,0, medio));
solucion2 = DistanciaMinimaDyV(Particion(puntos,medio,(int)puntos.get(puntos.size()-1).getX()));
solucionfinal = Math.min(DistanciaMinimaExhaustivo(Particion(puntos, medio-(int)Math.min(solucion1,solucion2), medio+(int)Math.min(solucion1,solucion2))),Math.min(solucion1, solucion2));
}
else if(puntos.size() == 3){
return CalcularDistancia3Puntos(puntos.get(0), puntos.get(1), puntos.get(2));
}
else{
return 100000;
}
return solucionfinal;
}
public ArrayList<Punto> Particion(ArrayList<Punto> elementos, int inicio, int fin){
//Particionamos el arrayList de inicio a fin
ArrayList<Punto> aux = new ArrayList<>();
for (int i = 0; i < elementos.size(); i++){
if(elementos.get(i).getX() < fin && elementos.get(i).getX() >= inicio)
aux.add(elementos.get(i));
}
return aux;
}
public double CalcularDistancia3Puntos(Punto A, Punto B, Punto C){
double distanciaMinima = 0, distancia1 = 0, distancia2 = 0, distancia3 = 0;
distancia1 = Math.sqrt(Math.pow(A.getX()-B.getX(),2) + Math.pow(A.getY()-B.getY(),2))
+ Math.sqrt(Math.pow(B.getX()-C.getX(),2) + Math.pow(B.getY()-C.getY(),2));
distancia2 = Math.sqrt(Math.pow(A.getX()-C.getX(),2) + Math.pow(A.getY()-C.getY(),2))
+ Math.sqrt(Math.pow(C.getX()-B.getX(),2) + Math.pow(C.getY()-B.getY(),2));
distancia3 = Math.sqrt(Math.pow(B.getX()-C.getX(),2)+Math.pow(B.getY()-C.getY(),2))
+ Math.sqrt(Math.pow(C.getX()-A.getX(),2)+Math.pow(C.getY()-A.getY(),2));
distanciaMinima = Math.min(Math.min(distancia1, distancia2), distancia3);
return distanciaMinima;
}
public double DistanciaMinimaExhaustivo(ArrayList<Punto> x){
double distanciaminima = 100000;
double aux;
if(x.size() >= 3){
for(int i = 0 ; i < x.size(); i++ ){
for(int j = i+1; j < x.size(); j++){
for(int t = j+1; t < x.size(); t++){
aux = CalcularDistancia3Puntos(x.get(i),x.get(j),x.get(t));
if(aux < distanciaminima){
distanciaminima = aux;
}
}
}
}
}
return distanciaminima;
}
}
|
package com.example.abhijith.dicegame;
import java.util.Random;
/**
* Created by abhijith on 30/7/16.
*/
public class DiceActivity {
public int humanScore,computerScore,humanCurrentScore,computerCurrentScore;
public boolean human;
public Random random;
DiceActivity() {
random = new Random();
reset();
}
void reset()
{
human = true;
humanScore = computerScore = computerCurrentScore = humanCurrentScore = 0;
}
public int rollDice(){
return random.nextInt(6) + 1;
}
}
|
package com.cw.controller;
import com.cw.controller.groups.GroupA;
import com.cw.domain.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
import java.util.List;
@Controller
public class EmployeeController {
@RequestMapping(value = "/addemployee")
/**
* 开启校验
* 名称:@Valid 、 @Validated
* 类型:形参注解
* 位置:处理器类中的实体类类型的方法形参前方
* 作用:设定对当前实体类类型参数进行校验
*/
//使用@Valid开启校验,使用@Validated也可以开启校验
//Errors对象用于封装校验结果,如果不满足校验规则,对应的校验结果封装到该对象中,包含校验的属性名和校验不通过返回的消息
public String addEmployee(@Valid Employee employee, Errors errors, Model m) {
// 通过形参Errors获取校验结果数据,通过Model接口将数据封装后传递到页面显示
//判定Errors对象中是否存在未通过校验的字段
if (errors.hasErrors()) {
//获取所有未通过校验规则的信息
List<FieldError> fieldErrors = errors.getFieldErrors();
System.out.println(fieldErrors.size());
for (FieldError error : fieldErrors) {
System.out.println(error.getField() + "--》" + error.getDefaultMessage());
//将校验结果信息添加到Model对象中,用于页面显示,后期实际开发中无需这样设定,返回json数据即可
m.addAttribute(error.getField(), error.getDefaultMessage());
}
//当出现未通过校验的字段时,跳转页面到原始页面,进行数据回显
return "addemployee.jsp";
}
return "success.jsp";
}
// @Validated支持分组校验,@Valid不支持分组校验
// 引用类型使用@Valid开启校验,控制器使用@Validated开启校验
@RequestMapping(value = "/addemployee2")
public String addEmployee2(@Validated({GroupA.class}) Employee employee, Errors errors, Model m) {
// 通过形参Errors获取校验结果数据,通过Model接口将数据封装后传递到页面显示
if (errors.hasErrors()) {
List<FieldError> fieldErrors = errors.getFieldErrors();
System.out.println(fieldErrors.size());
for (FieldError error : fieldErrors) {
System.out.println(error.getField() + "--》" + error.getDefaultMessage());
m.addAttribute(error.getField(), error.getDefaultMessage());
}
return "addemployee.jsp";
}
return "success.jsp";
}
}
|
package com.tencent.mm.plugin.webview.model;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class z$c$5 implements OnClickListener {
final /* synthetic */ z$d pRy;
public z$c$5(z$d z_d) {
this.pRy = z_d;
}
public final void onClick(DialogInterface dialogInterface, int i) {
this.pRy.goBack();
}
}
|
package leecode.DP;
public class 最长有效括号_32 {
public static int longestValidParentheses(String s) {
int [] dp=new int[s.length()];
char[]chars=s.toCharArray();
int max=0;
for (int i = 1; i <chars.length ; i++) {//dp[0]是0 一个字符不会构成括号
if(chars[i]==')'){
if(chars[i-1]=='('){
dp[i]=2; //不要忘记这个
if(i-2>=0) {
dp[i] = dp[i - 2] + 2;//是 dp[i-2]
}
}
if(chars[i-1]==')'){
if(i-dp[i-1]-1>=0&&chars[i-dp[i-1]-1]=='('){
dp[i]=dp[i-1]+2;
if(i-dp[i-1]-2>0){
dp[i]=dp[i-1]+2+dp[i-dp[i-1]-2];
}
}
}
}
max=Math.max(max,dp[i]);
}
return max;
}
public static int method(String str){
char[]chars=str.toCharArray();
int[]dp=new int[chars.length];
int max=0;
for (int i = 1; i <chars.length ; i++) {
if(chars[i]=='('){
dp[i]=0;
}
// int pre=i-dp[i-1]-1;
if(chars[i]==')'){
int pre=i-dp[i-1]-1;
if(pre>=0&&chars[pre]=='(') {
dp[i] = dp[i - 1] + 2 + (pre-1>=0?dp[pre-1]:0);
}
}
max=Math.max(max,dp[i]);
}
return max;
}
public static void main(String[] args) {
String s="(()";
// int len=longestValidParentheses(s);
// System.out.println(len);
System.out.println(method(s));
}
}
|
public class AudiA8 {
private static int wheelSize; //class variable
private String color; //instance variable
public static void rotateWheel() { //static method
//do something
}
public void turnOnEngine() { //non-static method
//do something
}
//getter and setter methods not shown
} |
package ClassConcept;
public class WrapperClassConcept {
public static void main(String[] args) {
String x="100";
System.out.println(x+20);
//Data conversion Sting to integer
int i =Integer.parseInt(x);
System.out.println(i+20);
// Different type of wrapper class--String,Double,Boolean
// string to double conversion
String y= "12.33";
double d= Double.parseDouble(y);
System.out.println(10+d);
//String to Boolean
String k="ture";
boolean b = Boolean.parseBoolean(k);
System.out.println(b);
// int to string conversion
int j=200;
System.out.println(j+20);
String s=String.valueOf(j);
System.out.println(s+20);
//
String u="10A";
int w =Integer.parseInt(u);
System.out.println(w+20);
}
}
|
package com.algaworks.ecommerce.conhecendoentitymanager;
import com.algaworks.ecommerce.EntityManagerTest;
import com.algaworks.ecommerce.model.Produto;
import org.junit.Test;
import java.math.BigDecimal;
public class ContextoDePersistencia extends EntityManagerTest {
@Test
public void usarContextoPersistencia() {
entityManager.getTransaction().begin();
Produto produto = entityManager.find(Produto.class, 1);
produto.setPreco(new BigDecimal(100));
Produto produtoNovo = new Produto();
produtoNovo.setNome("Caneca para café");
produtoNovo.setDescricao("Boa caneca para café");
produtoNovo.setPreco(new BigDecimal(10));
entityManager.persist(produtoNovo);
Produto produtoNovo2 = new Produto();
produtoNovo2.setNome("Caneca para chá");
produtoNovo2.setDescricao("Boa caneca para chá");
produtoNovo2.setPreco(new BigDecimal(10));
produtoNovo2 = entityManager.merge(produtoNovo2);
entityManager.flush();
produtoNovo2.setDescricao("Alterar descrição");
entityManager.getTransaction().commit();
}
}
|
package be.cegeka.eventualizr.api;
import org.joda.time.LocalDateTime;
public class MeetingTO {
private String venue;
private String title;
private LocalDateTime start;
private LocalDateTime end;
private Long id;
public String getVenue() {
return venue;
}
public void setVenue(String venue) {
this.venue = venue;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public LocalDateTime getStart() {
return start;
}
public void setStart(LocalDateTime start) {
this.start = start;
}
public LocalDateTime getEnd() {
return end;
}
public void setEnd(LocalDateTime end) {
this.end = end;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
|
package service;
import java.util.*;
//Create a class called PersonalityCalculator
public class PersonalityCalculator {
// integer findAnswers(String options)
// findAnswer() accepts String as an argument and returns integer array as an output
public int findAnswers(String options) {
String c[]=options.split(",");//split the options and store in an separate string array
int n=c.length;
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(c[i]);
// Convert the string array into an integer array.
//Change the type as integers - and store it in an integer array
return a[i];//Return integer array
}
int x=a[0]+a[1]+a[2]+a[4]+a[7]+a[9]+a[10]+a[11]+a[13]+a[17]+a[19];
System.out.println(x);
int y=a[3]+a[5]+a[6]+a[12]+a[14]+a[15]+a[16]+a[18];
System.out.println(y);
int Z=66-x+y;
return Z;//return an integer which helps to find which type of brain your having
}
// PersonalityCalculator has two methods findAnswers and findYourBrainType
// String findYourBrainType(String options) is the method prototype
// findYourBrainType accepts String as an argument and returns String as an output
public String findYourBrainType(String options) {
int Z=findAnswers(options);// option is a string which contains all the options selected as a string
if((Z>=2)&&(Z<=55)) {
return "Left-Brained";
}
else if((Z>=56)&&(Z<=64)) {
return "No clear preference ";
}
else if((Z>=65)&&(Z<=100)) {
return "Right-brained";
}
else
return "something went wrong";
}
}
|
package com.alium.ic.web;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.ListDataModel;
import javax.inject.Inject;
import javax.inject.Named;
import com.alium.ic.domains.SlowWojewodztwo;
import com.alium.ic.service.WojewodztwoManager;
@SessionScoped
@Named("wojewodztwoBean") // nazwa Beana , nie musi byc taka sama jak nazwa klasy
public class WojewodztwoBean implements Serializable{
private static final long serialVersionUID = 1L;
private SlowWojewodztwo wojewodztwo= new SlowWojewodztwo();
//model danych
private ListDataModel<SlowWojewodztwo> wojewodztwa= new ListDataModel<SlowWojewodztwo>();
@Inject
WojewodztwoManager wm;
public SlowWojewodztwo getWojewodztwo() {
return wojewodztwo;
}
public void setWojewodztwo(SlowWojewodztwo wojewodztwo) {
this.wojewodztwo = wojewodztwo;
}
public ListDataModel<SlowWojewodztwo> getWojewodztwa() {
wojewodztwa.setWrappedData(wm.getWojewodztwa());
return wojewodztwa;
}
public String addWojewodztwo(){
wm.addWojewodztwo(wojewodztwo); // w panstwo manager wywoluje metode addPanstwo z parametrem wejsciowym panstwp (->bean)
return null; // przekierowuje na strone showSlownik
}
/* public String deleteCountry(){
SlowWojewodztwo countryToDelete= panstwa.getRowData();
pm.deleteCountry(countryToDelete);
return null;
}
// akcja
public String editPanstwo(){
panstwo = new SlowWojewodztwo(); // Panstwo - klasa , a nie lista
panstwo = panstwa.getRowData();
return "editPanstwo";
}
public String updatePanstwo(){
pm.updateWojewodztwo(panstwo);
panstwo = new SlowWojewodztwo();
return "showSlownik";
}*/
}
|
import org.apache.commons.lang3.StringUtils;
import org.broad.tribble.readers.TabixReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by gcc on 31/03/17.
*/
public class Tabix {
private final String inputFile;
/**
* basic constructor
* @param file
* @throws IOException
*/
public Tabix(String file) throws IOException {
inputFile = file;
}
/**
* this method performs tabix command on CADD annotation file
* @param chr, chromosome number
* @param start, variant start
* @param end, variant stop
* @param ref, reference allele
* @param alt, alternative allele
* @return resultLine, tabix query result
* @throws IOException
*/
public String queryExecute(String chr, String start, String end, String ref, String alt) throws IOException {
TabixReader tr = new TabixReader(this.inputFile);
// builds tabix query
String s = String.format("%s:%s-%s", chr,start, start);
TabixReader.Iterator query = tr.query(s);
String line = null;
String resultLine = null;
while((line=query.next())!=null) {
List<String> split = Arrays.asList(line.split("\t"));
ArrayList<String> arraylistSplit = new ArrayList<String>(split);
// selects correct tabix query result
if(arraylistSplit.get(0).equals(chr) & arraylistSplit.get(1).equals(start) & arraylistSplit.get(2).equals(ref) & arraylistSplit.get(4).equals(alt)) {
resultLine = StringUtils.join(arraylistSplit, "\t");
}
}
tr.close();
return resultLine;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.