text stringlengths 10 2.72M |
|---|
package PackagesInterfaces.p2;
public class OtherPackage {
OtherPackage()
{
PackagesInterfaces.AccessModifier.Protection pm = new PackagesInterfaces.AccessModifier.Protection();
System.out.println("This is a other Packge ");
System.out.println("The value of n_pub is " +pm.n_pub);
//Private,DEfault and Protected wont work
//System.out.println("The value of n is " +Protection2.n);
//System.out.println("The value of n_pri is "+Protection2.n_pri);
//System.out.println("The value of n_pro is "+p4.n_pro);
}
}
|
/*
* 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 org.rdcit.oc_scto;
import java.io.File;
import org.rdcit.tools.SpreadsheetReader;
import org.rdcit.tools.SpreadsheetWriter;
import static org.rdcit.tools.Statics.workingRepository;
import org.rdcit.tools.TemplateFactory;
/**
*
* @author sa841
*/
public class FromOcToScto {
File inputFile;
File outputFile;
SpreadsheetReader inputFileReader;
SpreadsheetWriter outputFileWriter;
public FromOcToScto(File inputFile) {
this.inputFile = inputFile;
}
void init() {
String outputFileName = inputFile.getName().replace(".xls", ".xlsx");
outputFile = new File(workingRepository + outputFileName);
TemplateFactory.createSctoTemplate(outputFile);
inputFileReader = new SpreadsheetReader(inputFile);
outputFileWriter = new SpreadsheetWriter(outputFile);
}
void close() {
outputFileWriter.close(outputFile);
inputFileReader.close();
}
public File convert() {
init();
Settings settings = new Settings(inputFile, outputFile, inputFileReader, outputFileWriter);
settings.setSettingsSheet();
Survey survey = new Survey(inputFile, outputFile, inputFileReader, outputFileWriter);
survey.setSurveySheet();
close();
return outputFile;
}
public static void main(String[] args) {
FromOcToScto fromOcToScto = new FromOcToScto(new File(workingRepository + "42F_PHENOTYPINGG_V150.xls"));
fromOcToScto.convert();
}
}
|
package ma.adria.banque.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* cette classe représente un compte d'un abonné
* @author ouakrim
* @since 02/2016
* @version 1.0.0
*/
@Entity
@Table(name="Compte")
public class Compte implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/*=====================================================================================*/
/* ATTRIBUES DE LA CLASSE */
/*=====================================================================================*/
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private long id;
private String numeroCompte;
private String intitule;
private double soldeComptable;
@ManyToOne
private Abonne abonne;
/*=====================================================================================*/
/* CONSTRUCTEURS */
/*=====================================================================================*/
public Compte() {
super();
}
public Compte(String numeroCompte, String intitule, double soldeComptable,
Abonne abonne) {
super();
this.numeroCompte = numeroCompte;
this.intitule = intitule;
this.soldeComptable = soldeComptable;
this.abonne = abonne;
}
/*=====================================================================================*/
/* GETTERS & SETTERS */
/*=====================================================================================*/
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNumeroCompte() {
return numeroCompte;
}
public void setNumeroCompte(String numeroCompte) {
this.numeroCompte = numeroCompte;
}
public String getIntitule() {
return intitule;
}
public void setIntitule(String intitule) {
this.intitule = intitule;
}
public double getSoldeComptable() {
return soldeComptable;
}
public void setSoldeComptable(double soldeComptable) {
this.soldeComptable = soldeComptable;
}
public Abonne getAbonne() {
return abonne;
}
public void setAbonne(Abonne abonne) {
this.abonne = abonne;
}
}
|
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*<applet code="Project.java" width=700 height =800></applet>*/
public class Project extends Applet implements Runnable{
Thread t;
String str="";int count=0;
Font f=new Font("SansSerif",Font.PLAIN+Font.BOLD,30);
public void init(){
setBackground(Color.orange);
setForeground(Color.blue);
setFont(f);
}
public void paint(Graphics g){
Graphics2D g2= (Graphics2D)g;
if(count>21&&count<70){
//nodes postioning..
g.setColor(Color.red);
g.fillOval(300,100,50,50); //1
g.fillOval(250,200,50,50); //2
g.fillOval(350,200,50,50); //3
g.fillOval(200,300,50,50); //4
g.fillOval(300,300,50,50); //5
g.fillOval(150,400,50,50); //6
g.fillOval(250,400,50,50); //7
g.fillOval(350,400,50,50); //8
g.fillOval(400,500,50,50); //9
/*
borders around nodes..
*/
g.setColor(Color.blue);
g.drawOval(300,100,49,49);
g.drawOval(250,200,49,49);
g.drawOval(350,200,49,49);
g.drawOval(200,300,49,49);
g.drawOval(300,300,49,49);
g.drawOval(150,400,49,49);
g.drawOval(250,400,49,49);
g.drawOval(350,400,49,49);
g.drawOval(400,500,49,49);
//nodes linking..
g.drawLine(325,150,275,200); //1-2
g.drawLine(325,150,375,200); //1-3
g.drawLine(275,250,225,300); //2-4
g.drawLine(275,250,325,300); //2-5
g.drawLine(225,350,175,400); //4-6
g.drawLine(225,350,275,400); //4-7
g.drawLine(335,345,375,400); //5-8
g.drawLine(385,445,425,500); //8-9
g.setColor(Color.blue);
g.drawString("A",315,135);
g.drawString("B",265,235); //300,125 ,250,125 1
g.drawString("C",365,235);
g.drawString("D",215,335); //250,225,200,225 2
g.drawString("E",315,335); //4//200,325,150,325 4
g.drawString("F",165,435);
g.drawString("G",265,435);
g.drawString("H",365,435);
g.drawString("I",420,535);
if(count>38){
try{
g.drawString(str,300,600);
t.sleep(1000); } catch(InterruptedException e){}
} }
// arrows left side..
if(count>30&&count<=33)
g.drawString("-->",240,125);// al
if(count>33&&count<=36)
g.drawString("-->",190,225);//bl
if(count>36&&count<=39)
g.drawString("-->",140,325);//dl
if(count>39&&count<=40){
g.drawString("-->",90,425);//fl
str+="F-"; try{ t.sleep(500); } catch(InterruptedException e){}
}
if(count>40&&count<=41){
g.drawString("<--",300,425);//gr
str+="G-";try{ t.sleep(500); } catch(InterruptedException e){}
}
if(count>41&&count<=42){
g.drawString("<--",250,325);//dr
str+="D-"; try{ t.sleep(500); } catch(InterruptedException e){}
}
if(count>42&&count<=43){
g.drawString("<--",350,325);//er
str+="E-"; try{ t.sleep(500); } catch(InterruptedException e){}
}
if(count>43&&count<=44){
g.drawString("<--",400,425);//hr
str+="H-";try{ t.sleep(500); } catch(InterruptedException e){}
}
if(count>44&&count<=45){
g.drawString("<--",450,525);//ir
str+="I-"; try{ t.sleep(500); } catch(InterruptedException e){}
}
if(count>45&&count<=46){
g.drawString("<--",310,225);//br
str+="B-"; try{ t.sleep(500); } catch(InterruptedException e){}
}
if(count>46&&count<=47){
g.drawString("<--",430,225);//cr
str+="C-"; try{ t.sleep(500); } catch(InterruptedException e){}
}
if(count>47&&count<=48){
g.drawString("<--",350,125);//ar
str+="A"; try{ t.sleep(500); } catch(InterruptedException e){}
}
if(count>=0&&count<=10) {
g.setColor(Color.black);
g.drawString("BINARY SEARCH TREE",200,150);
g.drawString("POSTORDER TRAVERSAL",180,180);
g.setColor(Color.blue);
new Font("sansSerif",Font.PLAIN,3);
g.drawString("Case Study By 200,201,203",150,400);
g.setColor(Color.blue);
try{ t.sleep(200); } catch(InterruptedException e){}
}
if(count>10&&count<=20){
g.setColor(Color.blue);
g.drawString("POSTORDER TRAVERSAL",200,100);
g.setColor(Color.black);
g.drawString("POSTORDER TRAVEL MEANS ..",10,150);
g.drawString("LEFTNODE->RIGHTNODE->ROOT",10,180);
g.drawString("TRAVERSING START FROM LEAF NODES",10,240);
try{t.sleep(250);}catch(InterruptedException e){}
}
if(count>=70) {
g.drawString("Thank you",250,200);
}
count++;
}
public void start(){
t=new Thread(this);
t.start();
}
public void run(){
while(true){
try{
repaint();
t.sleep(500);
}
catch(InterruptedException e){}
}
}
} |
package com.evan.demo.yizhu.yushi_fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import com.evan.demo.yizhu.R;
public class yushi_paifengshan extends Fragment {
private View rootView;
private ImageButton paifengshan;
private int flag = 0;
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public View onCreateView(@Nullable LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_yushi_paifengshan, container, false);
initUi();
return rootView;
}
private void initUi() {
//这里写加载布局的代码
paifengshan = (ImageButton)rootView.findViewById(R.id.paifengshan);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//这里写逻辑代码
if(flag == 0 ){
paifengshan.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
paifengshan.setImageDrawable(getResources().getDrawable(R.drawable.paifengshan_off));
}
else {
paifengshan.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
paifengshan.setImageDrawable(getResources().getDrawable(R.drawable.paifengshan_on));
}
paifengshan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag == 0 ){
paifengshan.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_isselect));
paifengshan.setImageDrawable(getResources().getDrawable(R.drawable.paifengshan_on));
flag = 1;
}
else {
paifengshan.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_circle_notselect));
paifengshan.setImageDrawable(getResources().getDrawable(R.drawable.paifengshan_off));
flag = 0;
}
}
});
}
}
|
package com.google.gwt.ParkIt.client;
import com.google.gwt.ParkIt.shared.UserEntry;
import com.google.gwt.ParkIt.shared.UserMapEntry;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("UserMapDataService")
public interface UserMapDataService extends RemoteService {
public void storeUserMapEntry(UserMapEntry userMapEntry, UserEntry user);
}
|
package com.learning.arrays;
public class Task12270 {
/**
* Method get 4 chars from corners of the 2 dimensional array
* and return them
*
* @param array 2 dimensional char array that you want work with
* @return StringBuilder representation of result
*/
public StringBuilder getCorners(char[][] array) {
if (array == null) {
throw new IllegalArgumentException("reference to null is not acceptable");
} else if (array.length < 2 || array[0].length < 2 || array[array.length - 1].length < 2) {
throw new IllegalArgumentException("length of arrays must be more than 1");
}
StringBuilder result = new StringBuilder("Symbols from corners: ");
char[] answer = {array[0][0],
array[0][array[0].length - 1],
array[array.length - 1][0],
array[array.length - 1][array[array.length - 1].length - 1]};
return result.append(answer);
}
}
|
package com.redhat.insurance.claims.reports;
import java.io.File;
import java.util.Arrays;
import net.masterthought.cucumber.Configuration;
import net.masterthought.cucumber.ReportBuilder;
import net.masterthought.cucumber.Reportable;
public class CucumberReportGenerator {
private String[] jsonFiles;
public CucumberReportGenerator( String... files ) {
this.jsonFiles = files;
}
public void generateReports() {
System.out.println( System.getProperty( "user.dir" ) );
File reportOutputDirectory = new File( "target" );
String buildNumber = "1";
String projectName = "commonwealth-resolve";
boolean runWithJenkins = false;
boolean parallelTesting = false;
Configuration configuration = new Configuration( reportOutputDirectory, projectName );
// optional configuration
configuration.setParallelTesting( parallelTesting );
configuration.setRunWithJenkins( runWithJenkins );
configuration.setBuildNumber( buildNumber );
// addidtional metadata presented on main page
configuration.addClassifications( "Platform", "N/A" );
configuration.addClassifications( "Browser", "Chrome" );
ReportBuilder reportBuilder = new ReportBuilder( Arrays.asList( jsonFiles ), configuration );
Reportable result = reportBuilder.generateReports();
}
}
|
package com.ufcg.virtualmusicbox;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TwoFragment extends Fragment {
private RecyclerView rv;
// private Bundle bundle;
// private String data;
private ArrayList<Music> play;
public TwoFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// bundle = getArguments();
// data = bundle.getString("LIST");
}
public void update(){
play = MainActivity.getRank();
// Log.d("dois update",play.get(0).titulo);
RankingAdapter adapter = new RankingAdapter(play);
rv.setAdapter(adapter);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
update();
} else {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
// Log.d("Tag", data);
// Gson gson = new Gson();
// Music[] arr = gson.fromJson(data, Music[].class);
// for (Music m : arr) {
// Log.d("cantor: ", m.cantor);
// Log.d("titulo: ", m.titulo);
// Log.d("votos: ", m.votos + "");
// }
rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
play = MainActivity.getRank();
RankingAdapter adapter = new RankingAdapter(play);
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
} |
package com.jeffdisher.thinktank.chat;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import com.eclipsesource.json.JsonObject;
import com.jeffdisher.laminar.utils.Assert;
/**
* Data structure which represents what the server knows about the state of the chatroom and all the connected users.
*/
public class ChatStore {
private static final int CACHE_SIZE = 10;
private final Set<RemoteEndpoint> _connections = new HashSet<>();
private final Queue<MessageTuple> _cache = new LinkedList<>();
/**
* Tells the store that a new message has arrived which should be relayed to the connected users.
*
* @param sender The sender of the message.
* @param content The message content.
* @param index The 1-indexed representation of the order this message arrived (after any message with a lower
* index).
*/
public synchronized void newMessageArrived(UUID sender, String content, long index) {
MessageTuple tuple = new MessageTuple(sender, content, index);
_cache.add(tuple);
if (_cache.size() > CACHE_SIZE) {
_cache.remove();
}
String message = tuple.toJson();
for (RemoteEndpoint endpoint : _connections) {
try {
endpoint.sendString(message);
} catch (IOException e) {
// This is fatal since we don't have handling for it.
throw Assert.unimplemented(e.getLocalizedMessage());
}
}
}
public synchronized void addConnectionAndSendBacklog(RemoteEndpoint session, long previousIndex) {
Assert.assertTrue(null != session);
boolean didAdd = _connections.add(session);
Assert.assertTrue(didAdd);
// Send off anything in the cache which is after this index.
try {
for (MessageTuple tuple : _cache) {
if (tuple.index > previousIndex) {
session.sendString(tuple.toJson());
}
}
} catch (IOException e) {
// This is fatal since we don't have handling for it.
throw Assert.unimplemented(e.getLocalizedMessage());
}
}
public synchronized void removeConnection(RemoteEndpoint session) {
Assert.assertTrue(null != session);
boolean didRemove = _connections.remove(session);
Assert.assertTrue(didRemove);
}
private static class MessageTuple {
public final UUID sender;
public final String content;
public final long index;
public MessageTuple(UUID sender, String content, long index) {
this.sender = sender;
this.content = content;
this.index = index;
}
public String toJson() {
JsonObject object = new JsonObject();
object.add("sender", this.sender.toString());
object.add("content", this.content);
object.add("index", this.index);
return object.toString();
}
}
}
|
package com.bean;
import com.db.connection;
public class signup {
String Fname;
String Lname;
String Email;
String pass;
/**
* @return the fname
*/
public String getFname() {
return Fname;
}
/**
* @param fname the fname to set
*/
public void setFname(String fname) {
Fname = fname;
System.out.println( " name is " + Fname);
}
/**
* @return the lname
*/
public String getLname() {
return Lname;
}
/**
* @param lname the lname to set
*/
public void setLname(String lname) {
Lname = lname;
}
/**
* @return the email
*/
public String getEmail() {
return Email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
Email = email;
}
/**
* @return the pass
*/
public String getPass() {
return pass;
}
/**
* @param pass the pass to set
*/
public void setPass(String pass) {
this.pass = pass;
}
public boolean insert()
{
System.out.println(Fname + Lname + pass + Email );
connection con=new connection();
boolean flag=con.put(Fname,Lname,pass,Email);
System.out.println("inside insert");
return flag;
}
}
|
package com.zxt.framework.dictionary.service;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import net.sf.jsqlparser.JSQLParserException;
/**
* 数据字段缓存操作
*
* @author chinazxt
*
*/
public interface DictionaryCacheService {
/**
* 数据库表添加缓存功能
* 1、添加trigger
* 2、添加数据库表记录
*
* 表名,数据源(类型),列名(主键),trigger名称,缓存表主键值
* @param params 包含数据源的id和动态数据字典的表达式
* @exception JSQLParserException sql解析异常
*/
public void insertCache(Map params)throws JSQLParserException,SQLException;
/**
* 获取某个表的触发器
* @param dataSourceId 数据源的id
* @param sqlExpression 动态数据字典的表达式
* @return
*/
public List getTriggers(String dataSourceId,String sqlExpression)throws JSQLParserException;
/**
* 根据表名查询相应的缓存记录
* @param sqlExpression 动态数据字典的表达式
* @return
*/
public List getDictionaryCacheRecord(String sqlExpression) throws JSQLParserException;
/**
* 清除缓存相关的trigger和cache记录
*
* @param params 包含sql表达式和datasoureid
* @throws JSQLParserException
*/
public void deleteCache(Map params)throws JSQLParserException;
/**
* 获取相应的trigger脚本
* @param dataSourceId
* @param sqlExpression
* @return
*/
public String getTriggerScript(String dataSourceId,String sqlExpression) throws JSQLParserException ;
}
|
package controller;
import entity.DepotDraw_insert;
import entity.DepotDraw_select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.DepotDrawService;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/depotDraw")
public class depotDrawController {
@Autowired
DepotDrawService depotDrawService;
//引入的xml文件
String xmlPath = "DepotDrawSQL.xml";
//主页面查询
@RequestMapping("/select")
public String depot_draw_select(DepotDraw_select depotDraw_select, Model model){
if (depotDraw_select.getDept().isEmpty()!=true){ depotDraw_select.setDept(depotDraw_select.getDept().substring(0,4)); }
if (depotDraw_select.getStore().isEmpty()!=true){ depotDraw_select.setStore(depotDraw_select.getStore().substring(0,4)); }
List result = depotDrawService.select(xmlPath,depotDraw_select);
String[][] form = new String[result.size()][8];
for (int i=0;i<result.size();i++){
Map map = (Map) result.get(i);
form[i][0]= String.valueOf(map.get("draw_no"));
form[i][1]= String.valueOf(map.get("dept_name"));
form[i][2]= String.valueOf(map.get("store_name"));
form[i][3]= String.valueOf(map.get("create_emp"));
form[i][4]= String.valueOf(map.get("create_date").toString().substring(0,10));
form[i][5]= String.valueOf(map.get("state"));
form[i][6]= String.valueOf(map.get("audit_emp"));
form[i][7]= String.valueOf(map.get("maker"));
}
model.addAttribute("result",form);
return "depot/draw/main";
}
//添加领用单
@RequestMapping("/insert")
public String depot_draw_insert(DepotDraw_insert depotDraw_insert,Model model){
if (depotDraw_insert.getStore().isEmpty()!=true){ depotDraw_insert.setStore(depotDraw_insert.getStore().substring(0,4)); }
if (depotDraw_insert.getDept().isEmpty()!=true){ depotDraw_insert.setDept(depotDraw_insert.getDept().substring(0,4)); }
String state = "添加失败!";
int success= depotDrawService.insert(xmlPath,depotDraw_insert);
if (success == 1){
state = "添加成功!";
}
// System.out.println(depotInInsert.toString());
model.addAttribute("state",state);
return "depot/draw/insert";
}
//删除
@RequestMapping("/delete")
public @ResponseBody
int depot_draw_delete(String id, String src){
return depotDrawService.delete(xmlPath,id,src);
}
//审核
@RequestMapping("/audit")
public @ResponseBody int depot_draw_audit(String id,String src,String user){
return depotDrawService.audit(xmlPath,id,src,user);
}
//消审
@RequestMapping("/remove")
public @ResponseBody int depot_draw_remove(String id,String src){
return depotDrawService.remove(xmlPath,id,src);
}
//详情页查询
@RequestMapping("detail_select")
public @ResponseBody String[][] depot_draw_detail_select(String draw_no, String src){
List result = depotDrawService.detail_select(xmlPath,draw_no,src);
//System.out.println(result.toString());
String[][] form = new String[result.size()][5];
//将查询到的数据赋给二维数组
for (int i=0;i<result.size();i++){
Map map = (Map) result.get(i);
form[i][0]= String.valueOf(map.get("card_no"));
form[i][1]= String.valueOf(map.get("equi_name"));
form[i][2]= String.valueOf(map.get("unit"));
form[i][3]= String.valueOf(map.get("store_name"));
form[i][4]= String.valueOf(map.get("dept_name"));
}
//System.out.println(form[0][0]);
return form;
}
//详情页添加
@RequestMapping("/detail_insert")
public @ResponseBody int depot_out_detail_insert(String draw_no,String card_no,String src){
return depotDrawService.detail_insert(xmlPath,draw_no,card_no,src);
}
//详情页删除
@RequestMapping("/detail_delete")
public @ResponseBody int depot_draw_detail_delete(String id,String src){
return depotDrawService.detail_delete(xmlPath,id,src);
}
//详情页添加页面查询
@RequestMapping("/detail_insert_select")
public @ResponseBody
String[][] depot_draw_detail_insert_select(String draw_no,String card_no, String src){
//System.out.println(card_no+src);
List result = depotDrawService.detail_insert_select(xmlPath,draw_no,card_no,src);
String[][] form = new String[result.size()][4];
for (int i=0;i<result.size();i++){
Map map = (Map) result.get(i);
form[i][0]= String.valueOf(map.get("card_no"));
form[i][1]= String.valueOf(map.get("equi_name"));
form[i][2]= String.valueOf(map.get("vendor"));
form[i][3]= String.valueOf(map.get("store"));
}
return form;
}
}
|
package com.leanthoughts.sjics.view;
import com.vaadin.annotations.Theme;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.VaadinRequest;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.spring.navigator.SpringViewProvider;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.ValoTheme;
import org.springframework.beans.factory.annotation.Autowired;
@Theme("valo")
@SpringUI
public class SjicsUI extends UI {
// we can use either constructor autowiring or field autowiring
@Autowired
private SpringViewProvider viewProvider;
@Override
protected void init(VaadinRequest request) {
//Main layout
final VerticalLayout root = new VerticalLayout();
root.setSizeFull();
root.setMargin(true);
root.setSpacing(true);
setContent(root);
//Layouts for each section
HorizontalLayout header=new HorizontalLayout();
HorizontalLayout menu=new HorizontalLayout();
//VerticalLayout content =new VerticalLayout();
HorizontalLayout footer=new HorizontalLayout();
//Add all sections to the root view
root.addComponent(header);
root.addComponent(menu);
//Label to hold the title
Label title=new Label("<h1>Camrent</h1>", ContentMode.HTML);
//Add the title to the header
header.addComponent(title);
//Label to hold the footer
Label footerlabel=new Label("Copyright 2015");
//Addthe footerlabel to the footer
footer.addComponent(footerlabel);
footer.setComponentAlignment(footerlabel, Alignment.MIDDLE_CENTER);
//Buttons for navigation
Button customerRegistration=new Button("Customer Registration");
Button product=new Button("Product Registration");
Button booking=new Button("Booking");
//Button Icons
product.setIcon(FontAwesome.FOLDER);
customerRegistration.setIcon(FontAwesome.USER);
booking.setIcon(FontAwesome.BOOK);
CssLayout menucontainer=new CssLayout(customerRegistration,product,booking);
menu.addComponent(menucontainer);
//Add listener for the button
customerRegistration.addClickListener(event -> getUI().getNavigator().navigateTo("customerView"));
product.addClickListener(event -> getUI().getNavigator().navigateTo("productView"));
booking.addClickListener(event -> getUI().getNavigator().navigateTo("bookingView"));
/*final CssLayout navigationBar = new CssLayout();
navigationBar.addStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
navigationBar.addComponent(createNavigationButton("View Scoped View",
ViewScopedView.VIEW_NAME));
root.addComponent(navigationBar);*/
final Panel viewContainer = new Panel();
viewContainer.setSizeFull();
root.addComponent(viewContainer);
root.setExpandRatio(viewContainer, 1.0f);
Navigator navigator = new Navigator(this, viewContainer);
navigator.addProvider(viewProvider);
//Add footer to the root view
root.addComponent(footer);
}
/*private Button createNavigationButton(String caption, final String viewName) {
Button button = new Button(caption);
button.addStyleName(ValoTheme.BUTTON_SMALL);
// If you didn't choose Java 8 when creating the project, convert this to an anonymous listener class
button.addClickListener(event -> getUI().getNavigator().navigateTo(viewName));
return button;
}*/
} |
package server;
import generator.util.ExerciseComparator;
import generator.util.ExerciseStatistics;
import generator.util.tags.ConceptTag;
import server.data.Exercise;
import server.services.GeneratorService;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String...args) {
String a = "test = asd123[1]";
int amount = 10;
GeneratorService s = new GeneratorService();
List<Exercise> exercises = s.generatePrograms(a, amount);
// System.out.println(exercises);
// ExerciseStatistics stats = new ExerciseStatistics(a, exercises);
// System.out.println("Finished generating 500 exercises.");
// System.out.println("We found " + stats.getDuplicateExercises() + " duplicates!");
//List<Exercise> duplicates = ExerciseComparator.getDuplicateExercises(exercises);
//exercises = exercises.stream().filter(e -> !duplicates.contains(e)).collect(Collectors.toList());
//duplicates.forEach(e -> System.out.println("Index: " + e.getIndex() + "\n" + e.getCode()));
//System.out.println("We found " + duplicates.size() + " duplicates!");
//System.out.println("After cleaning the duplicates, our list is of size " + exercises.size() + "!");
}
}
|
package back.service;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.springframework.stereotype.Service;
@Service
public class PasswordServiceProvider implements PasswordService {
private static final List<String> normals = new CopyOnWriteArrayList<>();
private static final List<String> preferentials = new CopyOnWriteArrayList<>();
private static int normalsCount = 0;
private static int preferentialsCount = 0;
@Override
public String normal() {
String password = "N" + String.format("%04d", ++normalsCount);
normals.add(password);
return password;
}
@Override
public String preferential() {
String password = "P" + String.format("%04d", ++preferentialsCount);
preferentials.add(password);
return password;
}
@Override
public String next() {
return !preferentials.isEmpty() ? preferentials.remove(0) : !normals.isEmpty() ? normals.remove(0) : "";
}
@Override
public void clear() {
normalsCount = 0;
preferentialsCount = 0;
normals.clear();
preferentials.clear();
}
} |
/*
* 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 pbo3.pkg10117089.latihan61.bangunruang;
/**
*
* @author a
*/
public class Bola implements BangunRuang{
private double jari;
public double getJari() {
return jari;
}
public void setJari(double jari) {
this.jari = jari;
}
@Override
public double hitungVolume() {
return (1.33*(Math.PI*Math.pow(getJari(), 3)));
}
}
|
public class Dog extends Animals{
private static String name = "Danger";
public String sounds(){
// System.out.println("Dog Barks!!!");
return "Barks";
}
}
|
package example.core;
/**
* Generates a hello message.
*/
public class HelloMessageGenerator {
/**
* Generate a hello message.
*
* @param name recipient name
* @return hello message
*/
public static String helloMessage(final String name) {
if (name == null) {
return "Hello, World!";
} else {
return String.format("Hello, %s!", name);
}
}
}
|
package com.example.ips.model;
import java.util.Date;
public class ServerplanNpmMaintain1 {
private Integer id;
private String storehouseUse;
private String develop;
private String construct;
private String releaseW;
private String releaseB;
private String mappinfAddress;
private String proxy;
private Date createTime;
private Date updateTime;
private Integer createUser;
private Integer updateUser;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStorehouseUse() {
return storehouseUse;
}
public void setStorehouseUse(String storehouseUse) {
this.storehouseUse = storehouseUse == null ? null : storehouseUse.trim();
}
public String getDevelop() {
return develop;
}
public void setDevelop(String develop) {
this.develop = develop == null ? null : develop.trim();
}
public String getConstruct() {
return construct;
}
public void setConstruct(String construct) {
this.construct = construct == null ? null : construct.trim();
}
public String getReleaseW() {
return releaseW;
}
public void setReleaseW(String releaseW) {
this.releaseW = releaseW == null ? null : releaseW.trim();
}
public String getReleaseB() {
return releaseB;
}
public void setReleaseB(String releaseB) {
this.releaseB = releaseB == null ? null : releaseB.trim();
}
public String getMappinfAddress() {
return mappinfAddress;
}
public void setMappinfAddress(String mappinfAddress) {
this.mappinfAddress = mappinfAddress == null ? null : mappinfAddress.trim();
}
public String getProxy() {
return proxy;
}
public void setProxy(String proxy) {
this.proxy = proxy == null ? null : proxy.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getCreateUser() {
return createUser;
}
public void setCreateUser(Integer createUser) {
this.createUser = createUser;
}
public Integer getUpdateUser() {
return updateUser;
}
public void setUpdateUser(Integer updateUser) {
this.updateUser = updateUser;
}
} |
package io.nekohasekai.tmicro;
public class Locale {
public String appName;
public String exit;
public static class English extends Locale {
{
appName = "TMicro";
exit = "Exit";
}
}
private static Locale instance;
public static Locale getCurrent() {
if (instance == null) {
instance = new English();
}
return instance;
}
}
|
package dto;
import java.util.HashMap;
public class PeopleHashMap {
private static final HashMap<Integer, Person> hashMap = new HashMap<>();
public static void addPersonToMap(Person p) {
hashMap.put(p.getId(), p);
}
public static void removePersonFromMap(Person p) {
hashMap.remove(p.getId(), p);
}
public static Person getPersonWithId(int id) {
return hashMap.get(id);
}
} |
/*
* © Copyright 2016 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file “COPYING“. In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.molr.inspector;
import cern.molr.commons.domain.Mission;
import cern.molr.inspector.domain.InstantiationRequest;
import cern.molr.inspector.domain.impl.InstantiationRequestImpl;
import cern.molr.inspector.json.MissionTypeAdapter;
import cern.molr.inspector.remote.SystemMain;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class SystemMainTest {
private static final Gson GSON = new GsonBuilder()
.registerTypeAdapter(Mission.class, new MissionTypeAdapter().nullSafe())
.create();
private Mission mockedMission;
@Before
public void setup() {
mockedMission = mock(Mission.class);
}
@Test
public void canStartAnInspector() throws Exception {
final String classPath = "/home/jepeders/workspace/cern/molr/inspector/build/main/";
final String inspectionClass = "cern.jarrace.inspector.remote.CliMain";
final String mainClass = "cern.jarrace.inspector.remote.CliMain";
final List<String> entryPoints = Collections.singletonList("main");
when(mockedMission.getMoleClassName()).thenReturn(mainClass);
when(mockedMission.getMissionContentClassName()).thenReturn(inspectionClass);
when(mockedMission.getTasksNames()).thenReturn(entryPoints);
final InstantiationRequest request = new InstantiationRequestImpl(classPath, mockedMission);
SystemMain.main(new String[]{GSON.toJson(request)});
}
}
|
package com.sise.bishe.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
/**
* 邮箱发送
*/
@Component
public class MailService {
@Autowired
JavaMailSender javaMailSender;
//发送简单邮件
public void sandSimpleMail(String from,String to,String subject,String content)
{
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(from);
mailMessage.setTo(to);
mailMessage.setSubject(subject);
mailMessage.setText(content);
javaMailSender.send(mailMessage);
}
}
|
package dev.nowalk.repositories;
import java.util.List;
import dev.nowalk.models.Department;
public interface DepartmentRepo {
public void addDepartment(Department d);
public List<Department> getAllDepartments();
public Department getDepartment(int id);
public Department getDepartmentByName(String name);
public Department updateDepartment(Department change);
public Department deleteDepartment(Department d);
}
|
import financialdata.*;
import java.util.ArrayList;
import java.util.Arrays;
public class DriverV2{
ArrayList<double[]> masterTraining = new ArrayList<double[]>(); // data is read and stored offline
ArrayList<Double> masterTarget = new ArrayList<Double>();
ArrayList<double[]> masterTestData = new ArrayList<double[]>();
ArrayList<Double> masterTestTarget = new ArrayList<Double>();
ArrayList<double[]> masterStockData = new ArrayList<double[]>();
NeuralNetwork nn;
int iterations = 0;
public DriverV2(int width, int depth, int iters){
nn = new NeuralNetwork();
nn.initializeNet(width,depth,1,206);
iterations = iters;
Datafeed.loadStocks();
}
public double[] createInputs(String ticker){
ArrayList<Double> out = new ArrayList<Double>();
out.addAll(Datafeed.getFundementals(ticker));
out.addAll(Convolutions.gaussianNormalization(Datafeed.getPriceSeries(ticker)));
out.addAll(Convolutions.gaussianNormalization(Datafeed.getVolumeSeries(ticker)));
return typeCastDouble(out.toArray(new Double[out.size()]));
}
public void writeMasterData(){
int tickerCount = 0;
while (tickerCount < 400){
masterTraining.add(createInputs(Datafeed.getTickerList().get(tickerCount)));
double newest = Datafeed.getNewestPrice(Datafeed.getTickerList().get(tickerCount));
double old = Datafeed.getLastClose(Datafeed.getTickerList().get(tickerCount));
masterTarget.add((newest-old)/newest);
tickerCount ++;
}
}
public void writeTestData(){
int tickerCount = 400;
while (tickerCount < Datafeed.getTickerList().size()){
masterTestData.add(createInputs(Datafeed.getTickerList().get(tickerCount)));
double newest = Datafeed.getNewestPrice(Datafeed.getTickerList().get(tickerCount));
double old = Datafeed.getLastClose(Datafeed.getTickerList().get(tickerCount));
masterTestTarget.add((newest-old)/newest);
tickerCount ++;
}
}
public void writeStockData(){
masterStockData.addAll(masterTraining);
masterStockData.addAll(masterTestData);
}
public void feedAll(){
int displayDivisor = 1;
double[] costHistory = new double[iterations];
double[] accuracyInHistory = new double[iterations];
double[] accuracyOutHistory = new double[iterations];
double cost = 0.0;
int numCorrectInSample=0;
int numCorrectOutSample=0;
int numTotal=0;
double accuracyInSample = 0.0;
double accuracyOutSample = 0.0;
for (int i = 0; i < iterations; i++){
int tickerCount = 0;
while (tickerCount < 400){ //goes through an trains on all stocks in the S&P500 inex
double[] target = new double[] {masterTarget.get(tickerCount) + .5};
nn.feedData(masterTraining.get(tickerCount),target);
double signHypothesis = Math.signum(Double.parseDouble(nn.toStringOutLast())-.51); //prints hypothesis Y
System.out.println("~~~~");
System.out.println(signHypothesis);
if (signHypothesis == Math.signum(target[0]-.5)){
numCorrectInSample += 1;
}
numTotal +=1;
System.out.println("~~~~");
cost += Math.abs(Double.parseDouble(nn.toStringOutLast()) - target[0]);
if (i % displayDivisor == 0){
System.out.println("Output is: " + nn.toStringOutLast());
System.out.println("Target is: " + (masterTarget.get(tickerCount)+0.5));
}
tickerCount ++;
}
tickerCount = 0;
while (tickerCount < masterTestData.size()){
double[] targetO = new double[] {masterTestTarget.get(tickerCount)+ .5}; // this tests model on out of sample masterTestTarget and MasterTestData
if (nn.feedDataTest(masterTestData.get(tickerCount),targetO)){
numCorrectOutSample += 1;
System.out.println("heppend");
}
System.out.println("accuracy out of sample being tested "+tickerCount);
tickerCount ++;
}
costHistory[i] = cost; // records epochs cost
accuracyInHistory[i] = numCorrectInSample * 1.0 / numTotal; // returns double %accuracy
accuracyOutHistory[i] = numCorrectOutSample * 1.0 / numTotal;// reut
System.out.println(i+"th iteration");
System.out.println("Cost: " + cost);
System.out.println("--");
cost = 0;
}
System.out.println("Cost History:"); // display cost and accuracy arrays
for (double dub : costHistory){
System.out.println(dub);
}
System.out.println("Accuracy-In-Sample History:");
for (double dub : accuracyInHistory){
System.out.println(dub);
}
System.out.println("Accuracy-Out-of-Sample History:");
for (double dub : accuracyOutHistory){
System.out.println(dub);
}
}
public static double[] typeCastDouble(Double[] in){
double[] out = new double[in.length];
int i = 0;
while(i<in.length){
out[i] = in[i];
i++;
}
return out;
}
public String giveRecommendation(String ticker){
writeStockData();
//check if valid ticker
double[] stockdata = masterStockData.get(Datafeed.getTickerList().indexOf(ticker));
double prediction = nn.feedDataAsk(stockdata);
String action = "";
System.out.println(prediction);
if (prediction > 0){
action = "BUY";
}
else{
action = "SELL";
}
return "Our recommendation for "+ ticker + " is to " + action;
}
public static void main(String[] args){
String ticker = args[0];
if(ticker.equals("train")){
DriverV2 network = new DriverV2(160,1,10);
network.writeMasterData();
//network.writeTestData(); // here write master test data pls
network.feedAll();
}
}
}
|
/*
* Copyright (c) 2015, Jirav All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.engine.mock;
import java.util.Map;
import java.util.concurrent.Future;
import org.mockito.Mockito;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.notifications.NotificationProducer;
import pl.edu.icm.unity.notifications.NotificationStatus;
import pl.edu.icm.unity.types.basic.EntityParam;
@Component
public class MockNotificationsProducer implements NotificationProducer
{
private NotificationProducer mock;
@Override
public Future<NotificationStatus> sendNotification(EntityParam recipient,
String channelName, String templateId, Map<String, String> params,
String locale, String preferredAddress) throws EngineException
{
return mock.sendNotification(recipient, channelName, templateId, params, locale, preferredAddress);
}
@Override
public Future<NotificationStatus> sendNotification(String recipientAddress,
String channelName, String templateId, Map<String, String> params,
String locale) throws EngineException
{
return mock.sendNotification(recipientAddress, channelName, templateId, params, locale);
}
@Override
public void sendNotificationToGroup(String group, String channelName, String templateId,
Map<String, String> params, String locale) throws EngineException
{
mock.sendNotificationToGroup(group, channelName, templateId, params, locale);
}
public NotificationProducer getAndResetMockFromMockito()
{
mock = Mockito.mock(NotificationProducer.class);
return mock;
}
}
|
package eecs.ai.p1.commands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import eecs.ai.p1.Board;
import eecs.ai.p1.BoardState;
import eecs.ai.p1.Directions;
public abstract class Command{
private List<ArrayList<Directions>> legalMoves;
private BoardState goalState;
/**
* Initializes a list of legal moves based on the position
*/
public final void initLegalMoves(){
List<ArrayList<Directions>> legalMoves = new ArrayList<>();
legalMoves.add(null);
legalMoves.add(new ArrayList<Directions>(Arrays.asList(Directions.DOWN, Directions.RIGHT)));
legalMoves.add(new ArrayList<Directions>(Arrays.asList(Directions.LEFT, Directions.DOWN, Directions.RIGHT)));
legalMoves.add(new ArrayList<Directions>(Arrays.asList(Directions.LEFT,Directions.DOWN)));
legalMoves.add(new ArrayList<Directions>(Arrays.asList(Directions.UP, Directions.DOWN, Directions.RIGHT)));
legalMoves.add(new ArrayList<Directions>(Arrays.asList(Directions.UP, Directions.LEFT, Directions.DOWN, Directions.RIGHT)));
legalMoves.add(new ArrayList<Directions>(Arrays.asList(Directions.UP, Directions.LEFT, Directions.DOWN)));
legalMoves.add(new ArrayList<Directions>(Arrays.asList(Directions.UP, Directions.RIGHT)));
legalMoves.add(new ArrayList<Directions>(Arrays.asList(Directions.UP, Directions.LEFT, Directions.RIGHT)));
legalMoves.add(new ArrayList<Directions>(Arrays.asList(Directions.UP, Directions.LEFT)));
this.legalMoves = legalMoves;
}
/**
* Initializes the reference goal state for use within commands
*/
public final void initGoalState(){
List<Integer> goalList = new ArrayList<>();
List<Integer> range = IntStream.rangeClosed(0, 8).boxed().collect(Collectors.toList());
goalList.addAll(range);
this.goalState = BoardState.of(goalList);
}
//TODO Move these to board?
/**
* Accessor for the goal state of the 8-puzzle
* @return the BoardState representing the goal state
*/
public final BoardState getGoalState(){
return this.goalState;
}
/**
* Get the possible legal moves given the board position
* @param position
* @return
*/
public final ArrayList<Directions> getLegalMoves(int position){
return legalMoves.get(position);
}
//Method requirement for execute method.
public abstract void execute(Board board);
} |
package J_51;
/**
* Created by IBM_ADMIN on 10/16/2016.
*/
public class Bird extends AbstractAnimal {
private void fly() {
System.out.println("Fly Fly!");
}
public void height() {
System.out.println("20cm");
}
public void weight() {
System.out.println("100g");
}
public void color() {
System.out.println("Brown");
}
public void breed() {
System.out.println("Dove Breed");
}
} |
package introsde.assignment3.soap;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Classe Java per person complex type.
*
* <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe.
*
* <pre>
* <complexType name="person">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="activities" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="activity" type="{http://soap.assignment3.introsde/}activity" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="birthdate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
* <element name="email" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="firstname" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="lastname" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="username" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}long" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "person", propOrder = {
"activities",
"birthdate",
"email",
"firstname",
"lastname",
"username"
})
public class Person {
protected Person.Activities activities;
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar birthdate;
protected String email;
protected String firstname;
protected String lastname;
protected String username;
@XmlAttribute(name = "id")
protected Long id;
/**
* Recupera il valore della proprietÓ activities.
*
* @return
* possible object is
* {@link Person.Activities }
*
*/
public Person.Activities getActivities() {
return activities;
}
/**
* Imposta il valore della proprietÓ activities.
*
* @param value
* allowed object is
* {@link Person.Activities }
*
*/
public void setActivities(Person.Activities value) {
this.activities = value;
}
/**
* Recupera il valore della proprietÓ birthdate.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getBirthdate() {
return birthdate;
}
/**
* Imposta il valore della proprietÓ birthdate.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setBirthdate(XMLGregorianCalendar value) {
this.birthdate = value;
}
/**
* Recupera il valore della proprietÓ email.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEmail() {
return email;
}
/**
* Imposta il valore della proprietÓ email.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEmail(String value) {
this.email = value;
}
/**
* Recupera il valore della proprietÓ firstname.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFirstname() {
return firstname;
}
/**
* Imposta il valore della proprietÓ firstname.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFirstname(String value) {
this.firstname = value;
}
/**
* Recupera il valore della proprietÓ lastname.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLastname() {
return lastname;
}
/**
* Imposta il valore della proprietÓ lastname.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLastname(String value) {
this.lastname = value;
}
/**
* Recupera il valore della proprietÓ username.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUsername() {
return username;
}
/**
* Imposta il valore della proprietÓ username.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUsername(String value) {
this.username = value;
}
/**
* Recupera il valore della proprietÓ id.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getId() {
return id;
}
/**
* Imposta il valore della proprietÓ id.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setId(Long value) {
this.id = value;
}
/**
* <p>Classe Java per anonymous complex type.
*
* <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="activity" type="{http://soap.assignment3.introsde/}activity" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"activity"
})
public static class Activities {
protected List<Activity> activity;
/**
* Gets the value of the activity property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the activity property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getActivity().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Activity }
*
*
*/
public List<Activity> getActivity() {
if (activity == null) {
activity = new ArrayList<Activity>();
}
return this.activity;
}
}
}
|
package com.taurus.openbravo.integracionPOS.XML.entidades;
public class GT_CLS_Inventario implements GT_CLS_EntidadBase {
private String id;
private String sucursal;
private String almacen;
private String articulo;
private String cantidad;
private String unidadMedida;
private String movementDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSucursal() {
return sucursal;
}
public void setSucursal(String sucursal) {
this.sucursal = sucursal;
}
public String getAlmacen() {
return almacen;
}
public void setAlmacen(String almacen) {
this.almacen = almacen;
}
public String getArticulo() {
return articulo;
}
public void setArticulo(String articulo) {
this.articulo = articulo;
}
public String getCantidad() {
return cantidad;
}
public void setCantidad(String cantidad) {
this.cantidad = cantidad;
}
public String getUnidadMedida() {
return unidadMedida;
}
public void setUnidadMedida(String unidadMedida) {
this.unidadMedida = unidadMedida;
}
public String getMovementDate() {
return movementDate;
}
public void setMovementDate(String movementDate) {
this.movementDate = movementDate;
}
}
|
package br.com.infoCenter.persistencia;
import java.sql.Connection;
import java.sql.DriverManager;
public class Conexao {
private static Connection con;
public static Connection getConexao() {
if (con == null) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/infocenter" , "root", "root");
System.out.println("Conectou");
} catch (Exception e) {
try{
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/infocenter" , "postgres", "postgres");
} catch (Exception ex) {
e.printStackTrace();
System.out.println("Nao conectou");
}
}
}
return con;
}
public static void main(String[] args) {
getConexao();
}
} |
package com.andy.myapplication.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.andy.myapplication.Collector.BaseActivity;
import com.andy.myapplication.ListView.ListView_main;
import com.andy.myapplication.R;
public class Activity_OtherWay extends BaseActivity {
private TextView Other, Login;
private EditText Name, Password;
private LinearLayout layout1,layout2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otherway);
findViewById();
setListeners();
OnFocusChange();
}
private void findViewById() {
Other = findViewById(R.id.tv_other);
Name = findViewById(R.id.et_country);
Password = findViewById(R.id.et_phone);
Login = findViewById(R.id.bt_next);
layout1 = findViewById(R.id.layout1);
layout2 = findViewById(R.id.layout2);
}
private void setListeners() {
MyTextWatcher myTextWatcher = new MyTextWatcher();
OnClick onClick = new OnClick();
Login.addTextChangedListener(myTextWatcher);
Password.addTextChangedListener(myTextWatcher);
Name.addTextChangedListener(myTextWatcher);
Other.setOnClickListener(onClick);
}
private class OnClick implements View.OnClickListener {
@Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.tv_other:
intent = new Intent(Activity_OtherWay.this, Activity_PhoneLogin.class);
break;
}
startActivity(intent);
}
}
private class MyTextWatcher implements android.text.TextWatcher {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Login.setEnabled(Boolean.FALSE);//在这里重复设置,以保证清除任意EditText中的内容,按钮重新变回不可点击状态
Login.setBackground(getResources().getDrawable(R.drawable.bg_button_noedit));
Login.setTextColor(getResources().getColor(R.color.green_next_noedit));
}
@Override
public void afterTextChanged(Editable s) {
if (!(Name.getText().toString().equals("") || Password.getText().toString().equals
(""))) {
Login.setEnabled(Boolean.TRUE);
Login.setBackground(getResources().getDrawable(R.drawable.bg_button));
Login.setTextColor(getResources().getColor(R.color.green_next2));
Login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Activity_OtherWay.this, ListView_main.class);
startActivity(intent);
}
});
}
}
}
private void OnFocusChange() {
Name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
layout1.setBackground(getDrawable(R.drawable.line_green));
} else {
layout1.setBackground(getDrawable(R.drawable.line_gray));
}
}
});
Password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
layout2.setBackground(getDrawable(R.drawable.line_green));
} else {
layout2.setBackground(getDrawable(R.drawable.line_gray));
}
}
});
}
}
|
package presentation;
import business.implementation.AchievementsManager;
import business.implementation.Interfaces.AchievementsManagerInterface;
import business.implementation.Interfaces.ReviewInterface;
import business.implementation.Interfaces.UserManagementInterface;
import business.implementation.ReviewManagement;
import business.implementation.UserManagement;
import business.model.Utente;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.ImageProducer;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
public class evalutateReview extends starView {
Utente utente;
int row;
private JFrame frmUntitledGaming;
public evalutateReview(Utente c, int r) {
this.utente = c;
this.row = r;
initialize();
}
private void initialize() {
ReviewInterface ri = new ReviewManagement();
UserManagementInterface um = new UserManagement();
frmUntitledGaming = new JFrame();
frmUntitledGaming.setIconImage(Toolkit.getDefaultToolkit().getImage("./src/presentation/imgs/UG_silver_logo.png"));
frmUntitledGaming.setTitle(" Untitled Gaming - Valuta Recensioni");
frmUntitledGaming.setResizable(false);
frmUntitledGaming.setBounds(100, 100, 950, 700);
frmUntitledGaming.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmUntitledGaming.getContentPane().setLayout(null);
frmUntitledGaming.setLocationRelativeTo(null);
JButton button = new JButton("");
button.setIcon(new ImageIcon(getClass().getResource("imgs/back_icon.png")));
button.setToolTipText("torna indietro");
button.setBounds(10, 11, 45, 45);
frmUntitledGaming.getContentPane().add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmUntitledGaming.setVisible(false);
business.implementation.Utils.Utilities.changePage("logged", utente);
}
});
JLabel lblListaGiochi = null;
try {
int fineLista = ri.getPendingReviews().getRowCount();
int inizioLista = row + 4;
if (fineLista == 0) {
JOptionPane.showMessageDialog(null, "Nessuna review da valutare");
}
if ((row + 4) >= fineLista)
inizioLista = fineLista;
lblListaGiochi = new JLabel("Lista Commenti" + "(" + (inizioLista) + " / " + (fineLista) + ")");
} catch (SQLException e) {
e.printStackTrace();
}
lblListaGiochi.setHorizontalAlignment(SwingConstants.CENTER);
lblListaGiochi.setFont(new Font("Vivaldi", Font.BOLD, 40));
lblListaGiochi.setBounds(0, 23, 944, 61);
frmUntitledGaming.getContentPane().add(lblListaGiochi);
JButton btnSuccessiva = new JButton("");
btnSuccessiva.setIcon(new ImageIcon(getClass().getResource("imgs/Rounded_next.png")));
btnSuccessiva.setFont(new Font("MV Boli", Font.ITALIC, 13));
btnSuccessiva.setToolTipText("Pagina Successiva");
btnSuccessiva.setBounds(830, 581, 45, 45);
try {
if (row + 4 >= ri.getPendingReviews().getRowCount()) {
btnSuccessiva.setEnabled(false);
}
} catch (SQLException e) {
e.printStackTrace();
}
frmUntitledGaming.getContentPane().add(btnSuccessiva);
btnSuccessiva.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmUntitledGaming.setVisible(false);
new evalutateReview(utente, row + 4);
}
});
JButton button_4 = new JButton("");
button_4.setEnabled(false);
button_4.setIcon(new ImageIcon(getClass().getResource("imgs/Rounded_back_1.png")));
button_4.setToolTipText("Pagina Precedente");
button_4.setFont(new Font("MV Boli", Font.ITALIC, 13));
button_4.setBounds(68, 581, 45, 45);
frmUntitledGaming.getContentPane().add(button_4);
if (row == 0) button_4.setEnabled(false);
frmUntitledGaming.getContentPane().add(button_4);
button_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmUntitledGaming.setVisible(false);
new evalutateReview(utente, row - 4);
}
});
/** First User */
int vote = 0;
int gameId1 = 0;
int userId1 = 0;
String gioco1 = "";
JLabel label = null;
try {
if (row >= ri.getPendingReviews().getRowCount()) {
label = new JLabel("vuoto");
} else {
userId1 = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row, 0)));
gameId1 = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row, 3)));
try {
vote = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row, 2)));
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
gioco1 = um.getGameFromId(gameId1);
String username1 = um.getUsername(userId1);
label = new JLabel(username1);
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setForeground(Color.DARK_GRAY);
label.setFont(new Font("Oregano", Font.PLAIN, 21));
label.setBounds(243, 148, 211, 30);
frmUntitledGaming.getContentPane().add(label);
JPanel panel_4 = new JPanel();
panel_4.setToolTipText("Valutazione");
panel_4.setBounds(464, 141, 259, 45);
ImageIcon defaultIcon = new ImageIcon(getClass().getResource("imgs/31g.png"));
ImageProducer ip = defaultIcon.getImage().getSource();
List<ImageIcon>
list = Arrays.asList(
makeStarImageIcon(ip, .6f, .6f, 0f),
makeStarImageIcon(ip, .7f, .7f, 0f),
makeStarImageIcon(ip, .8f, .8f, 0f),
makeStarImageIcon(ip, .9f, .9f, 0f),
makeStarImageIcon(ip, 1f, 1f, 0f));
LevelBar lb = new LevelBar(defaultIcon, list, 2);
panel_4.add(makeStarRatingPanel("", lb));
lb.setLevel(vote - 1);
frmUntitledGaming.getContentPane().add(panel_4);
// Read the comment
JButton btnRecensione = new JButton("Leggi Commento");
btnRecensione.setToolTipText("Leggi Commento");
btnRecensione.setFont(new Font("MV Boli", Font.ITALIC, 17));
btnRecensione.setBounds(738, 148, 180, 30);
frmUntitledGaming.getContentPane().add(btnRecensione);
int finalGameId = gameId1;
int finalUserId = userId1;
btnRecensione.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmUntitledGaming.setVisible(false);
try {
new approveComment(utente, ri.getReview(finalUserId, finalGameId));
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
}
} catch (SQLException e) {
e.printStackTrace();
}
/** User 2 */
String gioco2 = "";
int gameId2 = 0;
int userId2 = 0;
JLabel label_1 = null;
try {
if (row + 1 >= ri.getPendingReviews().getRowCount()) {
label_1 = new JLabel("vuoto");
} else {
userId2 = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row + 1, 0)));
gameId2 = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row + 1, 3)));
try {
vote = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row + 1, 2)));
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
gioco2 = um.getGameFromId(gameId2);
String username2 = um.getUsername(userId2);
label_1 = new JLabel(username2);
label_1.setHorizontalAlignment(SwingConstants.CENTER);
label_1.setForeground(Color.DARK_GRAY);
label_1.setFont(new Font("Oregano", Font.PLAIN, 21));
label_1.setBounds(243, 271, 211, 30);
frmUntitledGaming.getContentPane().add(label_1);
JPanel panel_5 = new JPanel();
panel_5.setToolTipText("Valutazione");
panel_5.setBounds(464, 265, 259, 45);
ImageIcon defaultIcon = new ImageIcon(getClass().getResource("imgs/31g.png"));
ImageProducer ip = defaultIcon.getImage().getSource();
List<ImageIcon>
list = Arrays.asList(
makeStarImageIcon(ip, .6f, .6f, 0f),
makeStarImageIcon(ip, .7f, .7f, 0f),
makeStarImageIcon(ip, .8f, .8f, 0f),
makeStarImageIcon(ip, .9f, .9f, 0f),
makeStarImageIcon(ip, 1f, 1f, 0f));
LevelBar lb = new LevelBar(defaultIcon, list, 2);
panel_5.add(makeStarRatingPanel("", lb));
lb.setLevel(vote - 1);
frmUntitledGaming.getContentPane().add(panel_5);
// Read the comment
JButton btnGioca = new JButton("Leggi Commento");
btnGioca.setToolTipText("Leggi Commento");
btnGioca.setFont(new Font("MV Boli", Font.ITALIC, 17));
btnGioca.setBounds(738, 271, 180, 30);
frmUntitledGaming.getContentPane().add(btnGioca);
int finalGameId2 = gameId2;
int finalUserId2 = userId2;
btnGioca.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmUntitledGaming.setVisible(false);
try {
new approveComment(utente, ri.getReview(finalUserId2, finalGameId2));
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
}
} catch (SQLException e) {
e.printStackTrace();
}
/** User 3 */
int gameId3 = 0;
int userId3 = 0;
String gioco3 = "";
JLabel label_2 = null;
try {
if (row + 2 >= ri.getPendingReviews().getRowCount()) {
label_2 = new JLabel("vuoto");
} else {
userId3 = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row + 2, 0)));
gameId3 = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row + 2, 3)));
try {
vote = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row + 2, 2)));
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
gioco3 = um.getGameFromId(gameId3);
String username3 = um.getUsername(userId3);
// Username label
label_2 = new JLabel(username3);
label_2.setHorizontalAlignment(SwingConstants.CENTER);
label_2.setForeground(Color.DARK_GRAY);
label_2.setFont(new Font("Oregano", Font.PLAIN, 21));
label_2.setBounds(243, 386, 211, 30);
frmUntitledGaming.getContentPane().add(label_2);
// Star rating panel
JPanel panel_6 = new JPanel();
panel_6.setToolTipText("Valutazione");
panel_6.setBounds(464, 380, 259, 45);
ImageIcon defaultIcon = new ImageIcon(getClass().getResource("imgs/31g.png"));
ImageProducer ip = defaultIcon.getImage().getSource();
List<ImageIcon>
list = Arrays.asList(
makeStarImageIcon(ip, .6f, .6f, 0f),
makeStarImageIcon(ip, .7f, .7f, 0f),
makeStarImageIcon(ip, .8f, .8f, 0f),
makeStarImageIcon(ip, .9f, .9f, 0f),
makeStarImageIcon(ip, 1f, 1f, 0f));
LevelBar lb = new LevelBar(defaultIcon, list, 2);
panel_6.add(makeStarRatingPanel("", lb));
lb.setLevel(vote - 1);
frmUntitledGaming.getContentPane().add(panel_6);
// Read the comment
JButton btnGioca_1 = new JButton("Leggi Commento");
btnGioca_1.setToolTipText("Leggi Commento");
btnGioca_1.setFont(new Font("MV Boli", Font.ITALIC, 17));
btnGioca_1.setBounds(738, 386, 180, 30);
frmUntitledGaming.getContentPane().add(btnGioca_1);
int finalGameId3 = gameId3;
int finalUserId3 = userId3;
btnGioca_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmUntitledGaming.setVisible(false);
try {
new approveComment(utente, ri.getReview(finalUserId3, finalGameId3));
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
}
} catch (SQLException e) {
e.printStackTrace();
}
/** User 4 */
int userId4 = 0;
int gameId4 = 0;
String gioco4 = "";
JLabel label_3 = null;
try {
if (row + 3 >= ri.getPendingReviews().getRowCount()) {
label_3 = new JLabel("vuoto");
} else {
userId4 = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row + 3, 0)));
gameId4 = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row + 3, 3)));
try {
vote = Integer.parseInt(String.valueOf(ri.getPendingReviews().getValueAt(row + 3, 2)));
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
gioco4 = um.getGameFromId(gameId4);
String username4 = um.getUsername(userId4);
label_3 = new JLabel(username4);
label_3.setHorizontalAlignment(SwingConstants.CENTER);
label_3.setForeground(Color.DARK_GRAY);
label_3.setFont(new Font("Oregano", Font.PLAIN, 21));
label_3.setBounds(243, 504, 211, 30);
frmUntitledGaming.getContentPane().add(label_3);
JPanel panel_7 = new JPanel();
panel_7.setToolTipText("Valutazione");
panel_7.setBounds(464, 497, 259, 45);
ImageIcon defaultIcon = new ImageIcon(getClass().getResource("imgs/31g.png"));
ImageProducer ip = defaultIcon.getImage().getSource();
List<ImageIcon>
list = Arrays.asList(
makeStarImageIcon(ip, .6f, .6f, 0f),
makeStarImageIcon(ip, .7f, .7f, 0f),
makeStarImageIcon(ip, .8f, .8f, 0f),
makeStarImageIcon(ip, .9f, .9f, 0f),
makeStarImageIcon(ip, 1f, 1f, 0f));
LevelBar lb = new LevelBar(defaultIcon, list, 2);
panel_7.add(makeStarRatingPanel("", lb));
lb.setLevel(vote - 1);
frmUntitledGaming.getContentPane().add(panel_7);
// Read the comment
JButton btnGioca_2 = new JButton("Leggi Commento");
btnGioca_2.setToolTipText("Leggi Commento");
btnGioca_2.setFont(new Font("MV Boli", Font.ITALIC, 17));
btnGioca_2.setBounds(738, 504, 180, 30);
frmUntitledGaming.getContentPane().add(btnGioca_2);
int finalGameId4 = gameId4;
int finalUserId4 = userId4;
btnGioca_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmUntitledGaming.setVisible(false);
try {
new approveComment(utente, ri.getReview(finalUserId4, finalGameId4));
} catch (SQLException e1) {
e1.printStackTrace();
}
}
});
}
} catch (SQLException e) {
e.printStackTrace();
}
// Static text
JLabel lblgamenameHere_2 = new JLabel(gioco1);
lblgamenameHere_2.setHorizontalAlignment(SwingConstants.CENTER);
lblgamenameHere_2.setForeground(Color.DARK_GRAY);
lblgamenameHere_2.setFont(new Font("Oregano", Font.PLAIN, 21));
lblgamenameHere_2.setBounds(22, 148, 211, 30);
frmUntitledGaming.getContentPane().add(lblgamenameHere_2);
JLabel lblgamenameHere_1 = new JLabel(gioco2);
lblgamenameHere_1.setHorizontalAlignment(SwingConstants.CENTER);
lblgamenameHere_1.setForeground(Color.DARK_GRAY);
lblgamenameHere_1.setFont(new Font("Oregano", Font.PLAIN, 21));
lblgamenameHere_1.setBounds(22, 271, 211, 30);
frmUntitledGaming.getContentPane().add(lblgamenameHere_1);
JLabel lblgamenameHere = new JLabel(gioco3);
lblgamenameHere.setHorizontalAlignment(SwingConstants.CENTER);
lblgamenameHere.setForeground(Color.DARK_GRAY);
lblgamenameHere.setFont(new Font("Oregano", Font.PLAIN, 21));
lblgamenameHere.setBounds(22, 386, 211, 30);
frmUntitledGaming.getContentPane().add(lblgamenameHere);
JLabel lblGamenameHere = new JLabel(gioco4);
lblGamenameHere.setHorizontalAlignment(SwingConstants.CENTER);
lblGamenameHere.setForeground(Color.DARK_GRAY);
lblGamenameHere.setFont(new Font("Oregano", Font.PLAIN, 21));
lblGamenameHere.setBounds(22, 504, 211, 30);
frmUntitledGaming.getContentPane().add(lblGamenameHere);
JLabel lblNomeDelGioco = new JLabel("Nome del gioco:");
lblNomeDelGioco.setForeground(Color.LIGHT_GRAY);
lblNomeDelGioco.setFont(new Font("Georgia", Font.ITALIC, 13));
lblNomeDelGioco.setBounds(67, 94, 140, 21);
frmUntitledGaming.getContentPane().add(lblNomeDelGioco);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setForeground(Color.LIGHT_GRAY);
lblUsername.setFont(new Font("Georgia", Font.ITALIC, 13));
lblUsername.setBounds(283, 98, 140, 21);
frmUntitledGaming.getContentPane().add(lblUsername);
JLabel lblRecensione = new JLabel("Valutazione:");
lblRecensione.setForeground(Color.LIGHT_GRAY);
lblRecensione.setFont(new Font("Georgia", Font.ITALIC, 13));
lblRecensione.setBounds(484, 98, 140, 21);
frmUntitledGaming.getContentPane().add(lblRecensione);
frmUntitledGaming.setVisible(true);
}
} |
package com.proyecto.utils;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class UtilsService {
public static Calendar dateToCalendar(final Date date) {
final Calendar cal = new GregorianCalendar();
cal.setTime(date);
return cal;
}
}
|
package com.onightperson.hearken.scroll;
import java.util.ArrayList;
import java.util.List;
/**
* Created by liubaozhu on 17/8/29.
*/
public class ScrollUtils {
public static List<String> getData() {
String[] names = new String[] {
"David",
"John",
"Lily",
"James",
"David",
"John"
};
List<String> data = new ArrayList<>();
for (String name : names) {
data.add(name);
}
return data;
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v1.0.1-05/30/2003 05:06 AM(java_re)-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2005.06.02 at 05:03:40 BRT
//
package com.citibank.latam.common.bind;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.citibank.latam.common.bind package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
public class ObjectFactory
extends com.citibank.latam.common.bind.impl.runtime.DefaultJAXBContextImpl
{
private static java.util.HashMap defaultImplementations = new java.util.HashMap();
public final static java.lang.Class version = (com.citibank.latam.common.bind.impl.JAXBVersion.class);
static {
defaultImplementations.put("com.citibank.latam.common.bind.XMLTYPE", "com.citibank.latam.common.bind.impl.XMLTYPEImpl");
defaultImplementations.put("com.citibank.latam.common.bind.RECORDTYPE", "com.citibank.latam.common.bind.impl.RECORDTYPEImpl");
defaultImplementations.put("com.citibank.latam.common.bind.XML", "com.citibank.latam.common.bind.impl.XMLImpl");
defaultImplementations.put("com.citibank.latam.common.bind.RECORDLISTTYPE", "com.citibank.latam.common.bind.impl.RECORDLISTTYPEImpl");
}
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.citibank.latam.common.bind
*
*/
public ObjectFactory() {
super(new com.citibank.latam.common.bind.ObjectFactory.GrammarInfoImpl());
}
/**
* Create an instance of the specified Java content interface.
*
* @param javaContentInterface the Class object of the javacontent interface to instantiate
* @return a new instance
* @throws JAXBException if an error occurs
*/
public java.lang.Object newInstance(java.lang.Class javaContentInterface)
throws javax.xml.bind.JAXBException
{
return super.newInstance(javaContentInterface);
}
/**
* Get the specified property. This method can only be
* used to get provider specific properties.
* Attempting to get an undefined property will result
* in a PropertyException being thrown.
*
* @param name the name of the property to retrieve
* @return the value of the requested property
* @throws PropertyException when there is an error retrieving the given property or value
*/
public java.lang.Object getProperty(java.lang.String name)
throws javax.xml.bind.PropertyException
{
return super.getProperty(name);
}
/**
* Set the specified property. This method can only be
* used to set provider specific properties.
* Attempting to set an undefined property will result
* in a PropertyException being thrown.
*
* @param name the name of the property to retrieve
* @param value the value of the property to be set
* @throws PropertyException when there is an error processing the given property or value
*/
public void setProperty(java.lang.String name, java.lang.Object value)
throws javax.xml.bind.PropertyException
{
super.setProperty(name, value);
}
/**
* Create an instance of XMLTYPE
*
* @throws JAXBException if an error occurs
*/
public com.citibank.latam.common.bind.XMLTYPE createXMLTYPE()
throws javax.xml.bind.JAXBException
{
return new com.citibank.latam.common.bind.impl.XMLTYPEImpl();
}
/**
* Create an instance of RECORDTYPE
*
* @throws JAXBException if an error occurs
*/
public com.citibank.latam.common.bind.RECORDTYPE createRECORDTYPE()
throws javax.xml.bind.JAXBException
{
return new com.citibank.latam.common.bind.impl.RECORDTYPEImpl();
}
/**
* Create an instance of XML
*
* @throws JAXBException if an error occurs
*/
public com.citibank.latam.common.bind.XML createXML()
throws javax.xml.bind.JAXBException
{
return new com.citibank.latam.common.bind.impl.XMLImpl();
}
/**
* Create an instance of RECORDLISTTYPE
*
* @throws JAXBException if an error occurs
*/
public com.citibank.latam.common.bind.RECORDLISTTYPE createRECORDLISTTYPE()
throws javax.xml.bind.JAXBException
{
return new com.citibank.latam.common.bind.impl.RECORDLISTTYPEImpl();
}
private static class GrammarInfoImpl
extends com.citibank.latam.common.bind.impl.runtime.AbstractGrammarInfoImpl
{
public java.lang.Class getDefaultImplementation(java.lang.Class javaContentInterface) {
java.lang.Class c = null;
try {
c = java.lang.Class.forName(((java.lang.String) defaultImplementations.get(javaContentInterface.getName())));
} catch (java.lang.Exception _x) {
c = null;
}
return c;
}
public com.citibank.latam.common.bind.impl.runtime.UnmarshallingEventHandler createUnmarshaller(java.lang.String uri, java.lang.String local, com.citibank.latam.common.bind.impl.runtime.UnmarshallingContext context) {
if (("XML" == local)&&("" == uri)) {
return new com.citibank.latam.common.bind.impl.XMLImpl().createUnmarshaller(context);
}
return null;
}
public java.lang.Class getRootElement(java.lang.String uri, java.lang.String local) {
if (("XML" == local)&&("" == uri)) {
return (com.citibank.latam.common.bind.impl.XMLImpl.class);
}
return null;
}
public boolean recognize(java.lang.String uri, java.lang.String local) {
if (("XML" == local)&&("" == uri)) {
return true;
}
return false;
}
public java.lang.String[] getProbePoints() {
return new java.lang.String[] {"", "XML"};
}
}
}
|
/*
* Copyright 2019 Claire Fauch
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.code.fauch.hedwig;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import org.junit.Assert;
import org.junit.Test;
/**
* TU for Options
*
* @author c.fauch
*
*/
public class OptionTest {
@Test
public void testEncodeBlksize() throws UnsupportedEncodingException {
final byte[] enc = Option.blksize(1024).encode();
final ByteBuffer buff = ByteBuffer.wrap(enc);
final byte[] lbl = new byte[8];
buff.get(lbl, 0, lbl.length);
Assert.assertEquals("blksize\0", new String(lbl, "US-ASCII"));
final byte[] val = new byte[5];
buff.get(val, 0, val.length);
Assert.assertEquals("1024\0", new String(val, "US-ASCII"));
}
@Test
public void testEncodeTimeout() throws UnsupportedEncodingException {
final byte[] enc = Option.timeout(10).encode();
final ByteBuffer buff = ByteBuffer.wrap(enc);
final byte[] lbl = new byte[8];
buff.get(lbl, 0, lbl.length);
Assert.assertEquals("timeout\0", new String(lbl, "US-ASCII"));
final byte[] val = new byte[3];
buff.get(val, 0, val.length);
Assert.assertEquals("10\0", new String(val, "US-ASCII"));
}
@Test
public void testEncodeTSize() throws UnsupportedEncodingException {
final byte[] enc = Option.tsize(673312).encode();
final ByteBuffer buff = ByteBuffer.wrap(enc);
final byte[] lbl = new byte[6];
buff.get(lbl, 0, lbl.length);
Assert.assertEquals("tsize\0", new String(lbl, "US-ASCII"));
final byte[] val = new byte[7];
buff.get(val, 0, val.length);
Assert.assertEquals("673312\0", new String(val, "US-ASCII"));
}
@Test
public void testDecode() throws UnsupportedEncodingException {
final Option opt = Option.blksize(1024);
final byte[] content = opt.encode();
final Option dec = Option.decode(ByteBuffer.wrap(content));
Assert.assertNotNull(dec);
Assert.assertEquals(opt.getLabel(), dec.getLabel());
Assert.assertEquals(opt.getValue(), dec.getValue());
}
@Test(expected=NullPointerException.class)
public void testDecodeMissingBuffer() throws UnsupportedEncodingException {
final Option dec = Option.decode(null);
Assert.assertNotNull(dec);
}
@Test
public void testDecodeEmptyBuffer() throws UnsupportedEncodingException {
final Option dec = Option.decode(ByteBuffer.allocate(0));
Assert.assertNull(dec);
}
@Test
public void testDecodeIncompleteOption() throws UnsupportedEncodingException {
final Option opt = Option.blksize(1024);
final ByteBuffer buff = ByteBuffer.wrap(opt.encode());
buff.position(9);
final Option dec = Option.decode(buff);
Assert.assertNull(dec);
}
}
|
package com.opentangerine.maven;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import com.opentangerine.maven.server.Backend;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.Maven;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.apache.maven.plugins.annotations.ResolutionScope.COMPILE_PLUS_RUNTIME;
import org.apache.maven.shared.invoker.DefaultInvocationRequest;
import org.apache.maven.shared.invoker.DefaultInvoker;
import org.apache.maven.shared.invoker.InvocationRequest;
import org.apache.maven.shared.invoker.Invoker;
import org.apache.maven.shared.invoker.MavenInvocationException;
@Mojo(
name = "g-watch",
requiresDependencyResolution = COMPILE_PLUS_RUNTIME
)
public class Watch extends AbstractMojo {
@Parameter( defaultValue = "${session}", readonly = true )
private MavenSession session;
@Parameter( defaultValue = "${project}", readonly = true )
protected MavenProject project;
@Component
private Maven maven;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
Backend.WEB.start();
new Thread(() -> {
try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
compile(true);
final Path src = project.getBasedir().toPath().resolve("src");
registerAll(src, watchService);
System.out.println("WATCHING: " + src.toFile().getAbsolutePath());
while (true) {
final WatchKey wk = watchService.take();
System.out.println("WAIT");
boolean recompile = false;
final List<WatchEvent<?>> events = wk.pollEvents();
for(WatchEvent<?> it : events) {
recompile = recompile || StringUtils.endsWith(it.context().toString(), "java");
}
if(events.size() > 0) {
compile(recompile);
}
// reset the key
boolean valid = wk.reset();
if (!valid) {
System.out.println("Key has been unregisterede");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}).start();
while(true) {
try {
TimeUnit.SECONDS.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Register the given directory, and all its sub-directories, with the WatchService.
*/
private void registerAll(final Path start, final WatchService watcher) throws IOException {
// register directory and sub-directories
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
return FileVisitResult.CONTINUE;
}
});
}
private void compile(boolean recompile) throws Exception {
final File dir = project.getBasedir();
run(dir, recompile);
}
private void run(final File dir, boolean recompile) throws Exception {
Invoker invoker = new DefaultInvoker();
if(recompile) {
compile(dir, invoker);
}
build(dir, invoker);
}
private void build(File dir, Invoker invoker) throws MavenInvocationException {
InvocationRequest request;
request = new DefaultInvocationRequest();
request.setBaseDirectory(dir);
System.setProperty("exec.mainClass", "com.ggajos.Blog");
request.setGoals(Arrays.asList("--quiet", "org.codehaus.mojo:exec-maven-plugin:1.5.0:java", "-Dexec.mainClass=\"com.ggajos.Blog\""));
invoker.execute(request);
getLog().info("REBUILD");
}
private void compile(File dir, Invoker invoker) throws MavenInvocationException {
InvocationRequest request;
request = new DefaultInvocationRequest();
request.setBaseDirectory(dir);
request.setGoals(Arrays.asList("--quiet", "compile"));
invoker.execute(request);
getLog().info("COMPILED");
}
public static void main(String[] args) throws Exception {
System.setProperty("maven.home", "d:\\arch\\lib\\apache-maven-3.2.1");
new Watch().run(Paths.get("D:\\work\\ot-static\\ggajos-blog").toFile(), true);
}
}
|
package com.flowedu.define.datasource;
public enum BusType {
TERM, VACATION, ETC
}
|
package com.example.zhkh.Comunication.WorkerComunication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.example.zhkh.R;
public class ClosesTaskFragment extends Fragment {
private static final int LAYOUT = R.layout.open_close_task;
private View view;
private FragmentActivity myContext;
EditText taskAdres, taskDesc;
Button stopBut;
public ClosesTaskFragment() {
// Required empty public constructor
}
public static InWorkTaskFragment newInstance(String param1, String param2) {
InWorkTaskFragment fragment = new InWorkTaskFragment();
Bundle args = new Bundle();
args.putString("TaskName", param1);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Context context) {
myContext = (FragmentActivity) myContext;
super.onAttach(context);
}
@Override
public void onStart() {
super.onStart();
Intent intent = getActivity().getIntent();
Bundle bundle = getArguments();
taskDesc.setText(bundle.getString("Description"));
taskAdres.setText(bundle.getString("Adres"));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view =inflater.inflate(LAYOUT, container, false);
taskAdres = view.findViewById(R.id.adresClose);
taskDesc = view.findViewById(R.id.taskClose);
return view;
}
}
|
package com.wrathOfLoD.Utility;
import java.util.Comparator;
/**
* Created by Mitchell on 4/13/2016.
*/
public class RenderPositionComparator implements Comparator<Position>{
@Override
public int compare(Position pos1, Position pos2){
if(pos1.getR() == pos2.getR()){
if(pos1.getQ() == pos2.getQ()){
return pos1.getH() - pos2.getH();
}
else{
return pos1.getQ() - pos2.getQ();
}
}
else{
return pos1.getR() - pos2.getR();
}
}
}
|
package com.arthur.bishi.wangyi0821;
import java.util.Arrays;
import java.util.Scanner;
/**
* @description:
* @author: arthurji
* @date: 2021/8/21 14:32
* @modifiedBy:
* @version: 1.0
*/
public class No3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] s = scanner.nextLine().split(" ");
int[] nums = new int[s.length];
for (int i = 0; i < s.length; i++) {
nums[i] = Integer.valueOf(s[i]);
}
int ans = 0;
int[] count = new int[s.length];
Arrays.fill(count, 1);
for (int i = 1; i < nums.length; i++) {
if(nums[i] > nums[i - 1]) {
count[i] = count[i - 1] + 1;
}
}
if(nums[0] > nums[s.length - 1]) {
count[0]++;
}
for (int i : count) {
ans += i;
}
System.out.println(ans);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package censure;
/**
*
* @author cfmak
*/
public class CensureParam {
public int imageSize;
public float nonMaxSuppThreshold;
public float harrisThreshold;
public CensureParam(int imgSize, float nonMaxSuppressionThreshold, float harrisLineTestThreshold)
{
imageSize = imgSize;
nonMaxSuppThreshold = nonMaxSuppressionThreshold;
harrisThreshold = harrisLineTestThreshold;
}
}
|
package br.com.branquinho.jpa.venda.casosDeUso.dto;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import br.com.branquinho.jpa.venda.model.FormaPagamento;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Builder
@Getter
@Setter
public class VendaView {
private Long id;
private String descricaoProduto;
private BigDecimal valor;
private LocalDateTime data;
private FormaPagamento formaPagamento;
}
|
/* Ara - capture species and specimen data
*
* Copyright (C) 2009 INBio ( Instituto Nacional de Biodiversidad )
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.inbio.ara.dto.label;
import org.inbio.ara.dto.BaseEntityOrDTOFactory;
import org.inbio.ara.persistence.label.OriginalLabel;
/**
*
* @author pcorrales
*/
public class OriginalLabelDTOFactory extends BaseEntityOrDTOFactory<OriginalLabel,OriginalLabelDTO>{
@Override
public OriginalLabel getEntityWithPlainValues(OriginalLabelDTO dto) {
if(dto == null) return null;
OriginalLabel result = new OriginalLabel();
result.setOriginalLabelId(dto.getOriginalLabelID());
result.setContents(dto.getContents());
return result;
}
@Override
public OriginalLabel updateEntityWithPlainValues(OriginalLabelDTO dto, OriginalLabel e) {
if(dto == null || e == null) return null;
e.setOriginalLabelId(dto.getOriginalLabelID());
e.setContents(dto.getContents());
return e;
}
/**
* create the OriginalLabelDTO with the information of entity Originallabel
* @param entity
* @return
*/
public OriginalLabelDTO createDTO(OriginalLabel entity) {
if(entity == null) return null;
OriginalLabelDTO result = new OriginalLabelDTO();
result.setOriginalLabelID(entity.getOriginalLabelId());
result.setContents(entity.getContents());
result.setSelected(false); //Initially must be false
return result;
}
} |
/*
* 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 org.una.clienteaeropuerto.controllers;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import org.una.clienteaeropuerto.dto.MarcaHorarioDTO;
import org.una.clienteaeropuerto.dto.TransaccionDTO;
import org.una.clienteaeropuerto.service.MarcasHorarioService;
import org.una.clienteaeropuerto.service.TransaccionService;
import org.una.clienteaeropuerto.utils.AppContext;
import org.una.clienteaeropuerto.utils.AuthenticationSingleton;
import org.una.clienteaeropuerto.utils.CambiarVentana;
import org.una.clienteaeropuerto.utils.VigenciaToken;
/**
* FXML Controller class
*
* @author Luis
*/
public class ControlMarcasHorarioController implements Initializable {
@FXML
private TableView<MarcaHorarioDTO> tvMarcasHorario;
@FXML
private TableColumn<MarcaHorarioDTO, String> tcId;
@FXML
private TableColumn<MarcaHorarioDTO, String> tcMarcaEntrada;
@FXML
private TableColumn<MarcaHorarioDTO, String> tcMarcaSalida;
@FXML
private TableColumn<MarcaHorarioDTO, String> tcAreaTrabajo;
@FXML
private TableColumn<MarcaHorarioDTO, String> tcEstado;
@FXML
private TableColumn<MarcaHorarioDTO, String> tcUsuario;
private List<MarcaHorarioDTO> marcasList = new ArrayList<MarcaHorarioDTO>();
private List<MarcaHorarioDTO> marcasList2 = new ArrayList<MarcaHorarioDTO>();
MarcaHorarioDTO marcaHorarioDTO = new MarcaHorarioDTO();
MarcasHorarioService marcasHorarioService = new MarcasHorarioService();
CambiarVentana cambiarVentana = new CambiarVentana();
TransaccionDTO transaccionDTO = new TransaccionDTO();
TransaccionService transaccionService = new TransaccionService();
java.util.Date date3 = new java.util.Date();
VigenciaToken vigenciaToken = new VigenciaToken();
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
cargarInformacionMarcasHorario();
}
@FXML
private void accionInactivar(ActionEvent event) throws InterruptedException, ExecutionException, IOException {
if (vigenciaToken.validarVigenciaToken() == true) {
if (marcaHorarioDTO.isEstado() == true) {
marcaHorarioDTO.setEstado(false);
marcasHorarioService.modify(marcaHorarioDTO.getId(), marcaHorarioDTO);
AgregarTransaccion();
cambiarVentana.cambioVentana("ControlMarcasHorario", event);
}
} else {
MensajeTokenVencido();
cambiarVentana.cambioVentana("Login", event);
}
}
@FXML
private void actionBtnInsertarHoraEntrada(ActionEvent event) throws IOException {
if (vigenciaToken.validarVigenciaToken() == true) {
AppContext.getInstance().set("marcaHorarioDTO", marcaHorarioDTO);
AppContext.getInstance().set("ed", "insertar");
cambiarVentana.cambioVentana("CreacionMarcaHorario", event);
} else {
MensajeTokenVencido();
cambiarVentana.cambioVentana("Login", event);
}
}
@FXML
private void accionSalir(ActionEvent event) throws IOException {
if (vigenciaToken.validarVigenciaToken() == true) {
cambiarVentana.cambioVentana("Dashboard", event);
} else {
MensajeTokenVencido();
cambiarVentana.cambioVentana("Login", event);
}
}
@FXML
private void MouseTvMarcas(MouseEvent event) {
if (tvMarcasHorario.getSelectionModel().getSelectedItem() != null) {
marcaHorarioDTO = (MarcaHorarioDTO) tvMarcasHorario.getSelectionModel().getSelectedItem();
}
}
private void cargarInformacionMarcasHorario() {
try {
marcasList = MarcasHorarioService.getInstance().getAll();
} catch (InterruptedException ex) {
Logger.getLogger(ControlMarcasHorarioController.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(ControlMarcasHorarioController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ControlMarcasHorarioController.class.getName()).log(Level.SEVERE, null, ex);
}
actualizarTableView();
}
private void actualizarTableView() {
for (int i = 0; i < marcasList.size(); i++) {
if (marcasList.get(i).isEstado() == true) {
marcasList2.add(marcasList.get(i));
tcId.setCellValueFactory(new PropertyValueFactory<>("id"));
tcEstado.setCellValueFactory(per -> {
String estadoString;
if (per.getValue().isEstado()) {
estadoString = "Activo";
} else {
estadoString = "Inactivo";
}
return new ReadOnlyStringWrapper(estadoString);
});
tcMarcaEntrada.setCellValueFactory((param) -> new SimpleObjectProperty<>(param.getValue().getMarca_entrada().getHours() + ":" + (param.getValue().getMarca_entrada().getMinutes())));
tcMarcaSalida.setCellValueFactory(pe -> {
String horaSalida;
if (pe.getValue().getMarca_salida() == null) {
horaSalida = "Sin definir";
} else {
horaSalida = pe.getValue().getMarca_salida().getHours() + ":" + pe.getValue().getMarca_salida().getMinutes();
}
return new ReadOnlyStringWrapper(horaSalida);
});
tcUsuario.setCellValueFactory((param) -> new SimpleObjectProperty(param.getValue().getUsuariosAreas().getUsuarios().getNombreCompleto()));
tcAreaTrabajo.setCellValueFactory((param) -> new SimpleObjectProperty(param.getValue().getUsuariosAreas().getAreas_trabajo().getNombre()));
tvMarcasHorario.getItems().clear();
tvMarcasHorario.setItems(FXCollections.observableArrayList(marcasList2));
}
}
}
@FXML
private void actionBtnInsertarHoraSalida(ActionEvent event) throws IOException {
if (vigenciaToken.validarVigenciaToken() == true) {
AppContext.getInstance().set("marcaHorarioDTO", marcaHorarioDTO);
AppContext.getInstance().set("ed", "edit");
cambiarVentana.cambioVentana("CreacionMarcaHorario", event);
} else {
MensajeTokenVencido();
cambiarVentana.cambioVentana("Login", event);
}
}
private void AgregarTransaccion() {
try {
transaccionDTO.setNombre("Se inactivó información de marcas de horario");
transaccionDTO.setUsuarios(AuthenticationSingleton.getInstance().getUsuario());
transaccionDTO.setFecha_registro(date3);
transaccionDTO.setEstado(true);
transaccionService.add(transaccionDTO);
} catch (InterruptedException | ExecutionException | IOException ex) {
Logger.getLogger(ControlMarcasHorarioController.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void MensajeTokenVencido() {
Alert alert = new Alert(Alert.AlertType.INFORMATION, "", ButtonType.OK);
alert.setTitle("Mensaje");
alert.setHeaderText("Su sesión ha caducado.");
alert.show();
}
}
|
package com.pdd.pop.sdk.http.api.request;
import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty;
import com.pdd.pop.sdk.http.api.response.PddPromotionGoodsCouponCreateResponse;
import com.pdd.pop.sdk.http.HttpMethod;
import com.pdd.pop.sdk.http.PopBaseHttpRequest;
import com.pdd.pop.sdk.common.util.JsonUtil;
import java.util.Map;
import java.util.TreeMap;
public class PddPromotionGoodsCouponCreateRequest extends PopBaseHttpRequest<PddPromotionGoodsCouponCreateResponse>{
/**
* 描述
*/
@JsonProperty("batch_desc")
private String batchDesc;
/**
* 开始时间,指到格林威治时间 1970 年 01 月 01 日 00 时 00 分 00 秒(北京时间 1970 年 01 月 01 日 08 时 00 分 00 秒)的总毫秒数
*/
@JsonProperty("batch_start_time")
private Long batchStartTime;
/**
* 结束时间,指到格林威治时间 1970 年 01 月 01 日 00 时 00 分 00 秒(北京时间 1970 年 01 月 01 日 08 时 00 分 00 秒)的总毫秒数
*/
@JsonProperty("batch_end_time")
private Long batchEndTime;
/**
* 优惠金额 单位: 分
*/
@JsonProperty("discount")
private Long discount;
/**
* 可领取数量
*/
@JsonProperty("init_quantity")
private Long initQuantity;
/**
* 每个用户限领张数
*/
@JsonProperty("user_limit")
private Long userLimit;
/**
* 商品ID
*/
@JsonProperty("goods_id")
private Long goodsId;
@Override
public String getVersion() {
return "V1";
}
@Override
public String getDataType() {
return "JSON";
}
@Override
public String getType() {
return "pdd.promotion.goods.coupon.create";
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
public Class<PddPromotionGoodsCouponCreateResponse> getResponseClass() {
return PddPromotionGoodsCouponCreateResponse.class;
}
@Override
public Map<String, String> getParamsMap() {
Map<String, String> paramsMap = new TreeMap<String, String>();
paramsMap.put("version", getVersion());
paramsMap.put("data_type", getDataType());
paramsMap.put("type", getType());
paramsMap.put("timestamp", getTimestamp().toString());
if(batchDesc != null) {
paramsMap.put("batch_desc", batchDesc.toString());
}
if(batchStartTime != null) {
paramsMap.put("batch_start_time", batchStartTime.toString());
}
if(batchEndTime != null) {
paramsMap.put("batch_end_time", batchEndTime.toString());
}
if(discount != null) {
paramsMap.put("discount", discount.toString());
}
if(initQuantity != null) {
paramsMap.put("init_quantity", initQuantity.toString());
}
if(userLimit != null) {
paramsMap.put("user_limit", userLimit.toString());
}
if(goodsId != null) {
paramsMap.put("goods_id", goodsId.toString());
}
return paramsMap;
}
public void setBatchDesc(String batchDesc) {
this.batchDesc = batchDesc;
}
public void setBatchStartTime(Long batchStartTime) {
this.batchStartTime = batchStartTime;
}
public void setBatchEndTime(Long batchEndTime) {
this.batchEndTime = batchEndTime;
}
public void setDiscount(Long discount) {
this.discount = discount;
}
public void setInitQuantity(Long initQuantity) {
this.initQuantity = initQuantity;
}
public void setUserLimit(Long userLimit) {
this.userLimit = userLimit;
}
public void setGoodsId(Long goodsId) {
this.goodsId = goodsId;
}
} |
package exercicio01;
public class Empregado
{
private String nome;
double salario;
double horasTrabalhadas;
double aumentoSalario;
public Empregado (String nome, double salario)
{
setNome(this.nome);
setSalario(this.salario);
this.horasTrabalhadas=8;
}
private void setNome(String nome)
{
// TODO Auto-generated method stub
this.nome=nome;
}
private void setSalario(double salario)
{
// TODO Auto-generated method stub
this.salario=salario;
}
private String getNome()
{
return nome;
}
private double getSalario()
{
return salario;
}
private double gethorasTrabalhadas ()
{
return horasTrabalhadas;
}
public void horasTrabalhadas(double horasTrabalhadas)
{
horasTrabalhadas(horasTrabalhadas);
}
public void printInfo ()
{
System.out.println("Nome:"+getNome()+ "\nSalário"+getSalario()+ "\nHoras Trabalhadas"+gethorasTrabalhadas());
}
public void promocao(double aumento)
{
this.aumentoSalario= (aumento * this.salario)/100;
this.salario=this.aumentoSalario+this.salario;
}
public void adicionaGratificacao (double aux)
{
if(gethorasTrabalhadas () >6)
{
this.salario= this.salario+ aux;
}
}
}
|
package com.jhc.servlet;
import com.jhc.dao.*;
import com.jhc.entity.Content;
import com.jhc.entity.Interface;
import com.jhc.entity.User;
import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet(name = "GetContent", value = "/GetContent")
public class GetContentServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// //监督实验:取得当前需要标注的界面
// if(interfaceIdExp == 16){
// InterfaceDao id = new InterfaceDaoImpl();
// Interface inter = ((InterfaceDaoImpl) id).getExpInterface(username,interOffsetExp);
// interfaceId = interOffsetExp;
// interOffset = inter.getOffset();
// number = inter.getNumber();
// } else {
// interfaceId = interfaceIdExp;
// interOffset = interOffsetExp;
// number = numberExp;
// }
//获取下一页内容索引
// int userOffset = -1;
// userOffset = rd.countResultsByUsername(username);
// int contentIndex = userOffset;
// int contentTotal = number;
// //监督实验:取得当前用户对应当前界面的结果数
// int userOffset = -1;
// if(interfaceIdExp == 16){
// userOffset = rd.countResultsByUsernameAndInterfaceId(username, interfaceId);
// }else{
// userOffset = rd.countResultsByUsername(username);
// }
//content 每次取单条内容
// Content content = new Content();
// //context
// switch (interfaceId){
// case 4: case 7: case 9: case 10: case 12: case 13: case 14: case 15:{
// content = td.getContentMix(interOffset,userOffset);
// break;
// }
// default:{
// content = td.getContent(interOffset + userOffset);
// break;
// }
// }
//contents 一次取出全部内容
//从session获取参数
HttpSession session = request.getSession();
List<Content> contents = (ArrayList<Content>) session.getAttribute("contents");
Integer contentIndex = (Integer)session.getAttribute("contentIndex") ;
Integer contentTotal = (Integer)session.getAttribute("contentTotal");
Boolean highlight = (Boolean)session.getAttribute("highlight");
Boolean guideline = (Boolean)session.getAttribute("guideline");
//首次登陆,获取全部内容
if(null == contents){
User user = (User)session.getAttribute("user");
Interface inter = (Interface)session.getAttribute("inter");
String username = inter.getUsername();
ResultDao rd = new ResultDaoImpl();
contentIndex = rd.countResultsByUsername(username);
int interfaceId = inter.getInterfaceId();
int interOffset = inter.getOffset();//当前界面编号
int number = inter.getNumber();//总界面数
ContentDao td = new ContentDaoImpl();
contents = new ArrayList<>();
//context
switch (interfaceId){
case 4: case 7: case 9: case 10: case 12: case 13: case 14: case 15:{
contents = td.getContentMixAll(interOffset, number);
break;
}
default:{
contents = td.getContentAll(interOffset, number);
break;
}
}
//pageNum
contentTotal = number;
//highlight
switch (interfaceId){
case 1: case 5: case 6: case 7: case 11: case 12: case 14: case 15:{
highlight = true;
break;
}
default:{
highlight = false;
break;
}
}
//guideline
switch(interfaceId){
case 2: case 5: case 8: case 9: case 11: case 12: case 13: case 15:{
guideline = true;
break;
}
default: {
guideline = false;
break;
}
}
}
if(contentIndex < contentTotal){
// session.setAttribute("content",content);
session.setAttribute("contents",contents);
session.setAttribute("highlight",highlight);
session.setAttribute("guideline",guideline);
session.setAttribute("contentIndex",contentIndex);
session.setAttribute("contentTotal",contentTotal);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}else {
// //监督实验:标注完一种界面后,继续下一界面的标注,直到全部完成
// if(interOffsetExp == 15){
// request.getRequestDispatcher("/thanks.jsp").forward(request, response);
// }else{
// request.getRequestDispatcher("/breakoff.jsp").forward(request, response);
// }
request.getRequestDispatcher("/thanks.jsp").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
|
/*
Copyright 2013 Andrew Joiner
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 uk.co.tekkies.readings.activity;
import java.util.WeakHashMap;
import uk.co.tekkies.readings.R;
import uk.co.tekkies.readings.ReadingsApplication;
import uk.co.tekkies.readings.fragment.PassageFragment;
import uk.co.tekkies.readings.model.ParcelableReadings;
import uk.co.tekkies.readings.service.IPlayerUi;
import uk.co.tekkies.readings.service.PlayerService;
import uk.co.tekkies.readings.util.Analytics;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;
public class PassageActivity extends BaseActivity implements IPlayerUi {
private static final String TAG_BIND = "BIND";
public static final String ARG_SELECTED_DATE = "selectedDate";
public static final String ARG_PASSAGE = "passage";
public static final String ARG_PASSAGE_ID = "passageId";
PagerAdapter pagerAdapter;
ViewPager viewPager;
private ParcelableReadings passableReadings;
private PlayerService.IPlayerService playerService = null;
private AsyncTask<String, Integer, Long> progressUpdateTask;
private boolean serviceAvailable = false;
private PlayerServiceConnection serviceConnection;
@Override
public void onCreate(Bundle savedInstanceState) {
setChosenTheme();
super.onCreate(savedInstanceState);
ReadingsApplication.checkForMP3Plugin(this);
serviceConnection = new PlayerServiceConnection();
setContentView(R.layout.passage_activity);
passableReadings = (ParcelableReadings) (getIntent().getParcelableExtra(ParcelableReadings.PARCEL_NAME));
if(getPassableReadings() != null) {
setupPager();
gotoPage(getPassableReadings().selected);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_passage, menu);
return super.onCreateOptionsMenu(menu);
}
private void setupPager() {
pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(pagerAdapter);
}
public class PagerAdapter extends FragmentStatePagerAdapter {
WeakHashMap<Integer, Fragment> fragments=new WeakHashMap<Integer, Fragment>();
public PagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
Fragment fragment = new PassageFragment();
fragments.put(i, fragment);
Bundle args = new Bundle();
args.putString(ARG_PASSAGE, getPassableReadings().passages.get(i).getTitle());
args.putInt(ARG_PASSAGE_ID, getPassableReadings().passages.get(i).getPassageId());
args.putLong(ARG_SELECTED_DATE, getPassableReadings().selectedDate.getTimeInMillis());
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
return getPassableReadings().passages.size();
}
@Override
public CharSequence getPageTitle(int position) {
return getPassableReadings().passages.get(position).getTitle();
}
@Override
public void finishUpdate(ViewGroup container) {
super.finishUpdate(container);
}
public Fragment getFragment(int position) {
return fragments.get(position);
}
}
private void gotoPage(String selected) {
for (int page = 0; page < getPassableReadings().passages.size(); page++) {
if (getPassableReadings().passages.get(page).getTitle().equalsIgnoreCase(selected)) {
viewPager.setCurrentItem(page);
break;
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_brightness:
case R.id.menu_brightness_overflow:
doDayNightToggle();
return true;
case R.id.menu_about_content:
showAboutContentDialog();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void showAboutContentDialog() {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage(getContentNotices());
dlgAlert.setTitle(R.string.about_content);
dlgAlert.setPositiveButton(R.string.ok, null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
protected String getContentNotices() {
String notices = getString(R.string.unknown);
String[] row = new String[] { "version" };
Cursor cursor = getContentResolver().query(Uri.parse("content://uk.co.tekkies.plugin.bible.kjv/about"), row,
"", row, "");
if (cursor.moveToFirst()) {
notices = cursor.getString(cursor.getColumnIndex("about"));
}
return notices;
}
public void requestViewPagerDisallowInterceptTouchEvent(boolean disallowIntercept) {
viewPager.requestDisallowInterceptTouchEvent(disallowIntercept);
}
public ParcelableReadings getPassableReadings() {
return passableReadings;
}
public void bindPlayerService() {
if(PlayerService.isServiceRunning(this)) {
Log.i(TAG_BIND, "bindPlayerService");
bindService(new Intent(this, PlayerService.class), getServiceConnection(), Activity.BIND_AUTO_CREATE);
}
}
public PassageActivity getPassageActivity() {
return this;
}
@Override
public void onPassageChange(int passageId) {
//Toast.makeText(this, "PassageID="+passageId, Toast.LENGTH_SHORT).show();
}
private int getPage(int passageId) {
int page=0;
for(int passageIndex=0;passageIndex<passableReadings.passages.size();passageIndex++) {
if(passableReadings.passages.get(passageIndex).getPassageId() == passageId) {
page = passageIndex;
break;
}
}
return page;
}
public PlayerService.IPlayerService getPlayerService() {
return playerService;
}
public void setPlayerService(PlayerService.IPlayerService playerService) {
this.playerService = playerService;
}
public class PlayerServiceConnection implements ServiceConnection
{
public void onServiceConnected(ComponentName className, IBinder playerService) {
Log.i(TAG_BIND, "onServiceConnected");
setPlayerService((PlayerService.IPlayerService) playerService);
try {
getPlayerService().registerActivity(PassageActivity.this, getPassageActivity());
serviceAvailable = true;
progressUpdateTask = new ProgressUpdateTask().execute("");
viewPager.setCurrentItem(getPage(getPlayerService().getPassage()));
//Toast.makeText(getPassageActivity(), "PassageID="+getServiceInterface().getPassage(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Analytics.reportCaughtException(getPassageActivity(), e);
}
}
public void onServiceDisconnected(ComponentName className) {
Log.i(TAG_BIND, "onServiceDisconnected");
serviceAvailable = false;
setPlayerService(null);
}
};
public void unbindPlayerService() {
Log.i(TAG_BIND, "unbindPlayerService");
if(playerService != null) {
playerService.unregisterActivity(this);
}
if(serviceAvailable) {
serviceAvailable = false;
unbindService(getServiceConnection());
}
}
@Override
public void onEndAll() {
unbindPlayerService();
PassageFragment passageFragment = getCurrentPageFragment();
if(passageFragment != null) {
passageFragment.setPlayPauseIcon();
}
}
private PassageFragment getCurrentPageFragment() {
return (PassageFragment) pagerAdapter.getFragment(viewPager.getCurrentItem());
}
public int getCurrentPassageId() {
return passableReadings.passages.get(viewPager.getCurrentItem()).getPassageId();
}
public boolean isServiceAvailable() {
return serviceAvailable;
}
public ServiceConnection getServiceConnection() {
return serviceConnection;
}
public void setServiceConnection(PlayerServiceConnection serviceConnection) {
this.serviceConnection = serviceConnection;
}
private class ProgressUpdateTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... unused) {
while(isServiceAvailable()) {
try {
publishProgress(getPlayerService().getProgress());
Thread.sleep(200);
} catch (InterruptedException e) {
//swallow it
}
}
return 0L;
}
protected void onProgressUpdate(Integer... progress) {
try {
PassageFragment passageFragment = getCurrentPageFragment();
if(passageFragment != null) {
passageFragment.setProgress(progress[0]);
}
} catch (Exception e) {
Analytics.reportCaughtException(getPassageActivity(), e);
}
}
protected void onPostExecute(Long result) {
}
}
@Override
public void onPassageEnding(int passageId) {
//Advance viewPager when beep starts
int nextPage = getPage(passageId)+1;
if(nextPage < passableReadings.passages.size()) {
viewPager.setCurrentItem(nextPage);
}
}
@Override
protected void onPause() {
super.onPause();
if(progressUpdateTask != null) {
progressUpdateTask.cancel(true);
}
unbindPlayerService();
}
@Override
protected void onResume() {
super.onResume();
bindPlayerService();
}
}
|
package org.mydotey.rpc.client.http.apache.async;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Objects;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.mydotey.codec.Codec;
import org.mydotey.codec.CodecException;
import org.mydotey.rpc.client.http.HttpConnectException;
import org.mydotey.rpc.client.http.HttpTimeoutException;
import org.mydotey.rpc.client.http.apache.ApacheHttpRequestException;
/**
* Created by Qiang Zhao on 10/05/2016.
*/
public interface HttpRequestAsyncExecutors {
static <T> CompletableFuture<T> executeAsync(CloseableHttpAsyncClient client, HttpUriRequest request, Codec codec,
Class<T> clazz) {
return executeAsync(ForkJoinPool.commonPool(), client, request, codec, clazz);
}
static <T> CompletableFuture<T> executeAsync(Executor executor, CloseableHttpAsyncClient client,
HttpUriRequest request, Codec codec, Class<T> clazz) {
Objects.requireNonNull(executor, "executor is null");
Objects.requireNonNull(codec, "codec is null");
Objects.requireNonNull(clazz, "clazz is null");
CompletableFuture<HttpResponse> future = executeAsync(client, request);
return future.thenApplyAsync(r -> {
try {
return codec.decode(r.getEntity().getContent(), clazz);
} catch (UnsupportedOperationException | IOException e) {
throw new CodecException(e);
}
}, executor);
}
static CompletableFuture<HttpResponse> executeAsync(CloseableHttpAsyncClient client, HttpUriRequest request) {
Objects.requireNonNull(client, "client is null");
Objects.requireNonNull(request, "request is null");
CompletableFuture<HttpResponse> future = new CompletableFuture<>();
client.execute(request, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse result) {
StatusLine statusLine = result.getStatusLine();
if (statusLine == null || statusLine.getStatusCode() >= 300)
future.completeExceptionally(new ApacheHttpRequestException(result));
else
future.complete(result);
}
@Override
public void failed(Exception ex) {
if (ex instanceof SocketTimeoutException)
ex = new HttpTimeoutException(ex);
else if (ex instanceof IOException)
ex = new HttpConnectException(ex);
future.completeExceptionally(ex);
}
@Override
public void cancelled() {
Exception ex = new CancellationException("Request has been cancelled.");
future.completeExceptionally(ex);
}
});
return future;
}
}
|
package net.awesomekorean.podo.lesson.lessonNumber.numbers;
import net.awesomekorean.podo.R;
import net.awesomekorean.podo.lesson.lessons.LessonInit;
import net.awesomekorean.podo.lesson.lessons.LessonItem;
public class NumberMoney extends LessonInit implements Number, LessonItem {
private String lessonId = "N_money";
private String lessonTitle = "money";
private String lessonSubTitle = "";
private int lessonImage = R.drawable.numbermoney;
private String[] front = {
"100 원", "150 원", "230 원", "260 원", "330 원", "390 원", "410 원", "460 원", "530 원", "580 원",
"600 원", "690 원", "740 원", "810 원", "890 원", "930 원", "990 원", "1,000 원", "1,200 원", "2,500 원",
"2,900 원", "3,300 원", "3,700 원", "4,100 원", "4,200 원", "5,000 원", "5,600 원", "6,200 원", "6,900 원",
"7,300 원", "7,600 원", "8,100 원", "8,200 원", "9,700 원", "9,900 원", "10,000 원", "12,000 원", "21,000 원",
"29,000 원", "34,000 원", "38,000 원", "43,000 원", "45,000 원", "55,000 원", "58,000 원", "66,000 원", "69,000 원",
"70,000 원", "71,000 원", "82,000 원", "86,000 원", "94,000 원", "99,000 원", "100,000 원"
};
private String[] back = {
"백 원[배권]", "백 오십 원", "이백 삼십 원", "이백 육십 원", "삼백 삼십 원", "삼백 구십 원", "사백 십 원",
"사백 육십 원", "오백 삼십 원", "오백 팔십 원", "육백 원", "육백 구십 원", "칠백 사십 원", "팔백 십 원",
"팔백 구십 원", "구백 삼십 원", "구백 구십 원", "천 원", "천 이백 원", "이천 오백 원", "이천 구백 원",
"삼천 삼백 원", "삼천 칠백 원", "사천 백 원", "사천 이백 원", "오천 원", "오천 육백 원", "육천 이백 원",
"육천 구백 원", "칠천 삼백 원", "칠천 육백 원", "팔천 백 원", "팔천 이백 원", "구천 칠백 원", "구천 구백 원",
"만 원", "만 이천 원", "이만 천 원", "이만 구천 원", "삼만 사천 원", "삼만 팔천 원", "사만 삼천 원",
"사만 오천 원", "오만 오천 원", "오만 팔천 원", "육만[융만] 육천 원", "육만[융만] 구천 원", "칠만 원",
"칠만 천 원", "팔만 이천 원", "팔만 육천 원", "구만 사천 원", "구만 구천 원", "십만 원[심마눤]"
};
@Override
public String getLessonSubTitle() {
return lessonSubTitle;
}
@Override
public String getLessonId() {
return lessonId;
}
@Override
public String getLessonTitle() {
return lessonTitle;
}
public int getLessonImage() {
return lessonImage;
}
@Override
public String[] getFront() {
return front;
}
@Override
public String[] getBack() {
return back;
}
}
|
package oop;
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
watchlog watchlog = new watchlog();
char exit;
do {
watchlog.loginstore();
Scanner put = new Scanner(System.in);
System.out.print("Do you want to Logout (Y) or Do you want Exits (N) : ");
String e = put.nextLine();
exit = e.toUpperCase().charAt(0);
System.out.println();
System.out.println("======================= THANK YOU =========================");
System.out.println(" =====================================================");
System.out.println("\n\n\n");
}while(exit == 'Y');
}
}
|
package com.itheima.day_02.sports;
public class PingpongCoach extends Coach implements StudyEnglish {
public PingpongCoach() {
}
public PingpongCoach(String name, int age) {
super(name, age);
}
@Override
public void teach() {
System.out.println("教授乒乓球技巧。。。");
}
@Override
public void eat() {
System.out.println("乒乓球教练正在吃饭。。。");
}
@Override
public void studyEnglish() {
System.out.println("乒乓球教练正在学英语。。。");
}
}
|
package com.flatirons.training.resources;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.flatirons.training.entity.Training;
import com.flatirons.training.services.TrainingServices;
@CrossOrigin
@RestController
public class TrainingResource {
@Autowired
TrainingServices trainingServices;
@RequestMapping(value = "/training", method = RequestMethod.GET)
public List<Training> getAllTraining() {
return trainingServices.getTrainingList();
}
@RequestMapping(value = "/addTraining", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public @ResponseBody void addTraining(@RequestBody(required= true) Training training) {
trainingServices.addTraining(training);
}
@RequestMapping(value = "/deleteTraining", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
public @ResponseBody void deleteTraining(@RequestBody(required= true) String trainingId) {
trainingServices.deleteTraining(trainingId);
}
@RequestMapping(value = "/editTraining", method = RequestMethod.PUT)
@ResponseStatus(value = HttpStatus.OK)
public @ResponseBody void editTraining(@RequestBody(required= true) Training training) {
trainingServices.editTraining(training);
}
}
|
package gui.editors;
import gui.form.TextCellItem;
import java.awt.Component;
import javax.swing.AbstractCellEditor;
import javax.swing.Icon;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import utils.ImageTools;
/** Allows simple text editing using a TextAreaItem. */
public class TextEditor extends AbstractCellEditor implements TableCellEditor
{
private static final long serialVersionUID = 1L;
private TextCellItem editor;
public TextEditor (final String label, final int rows, final int columns)
{
editor = new TextCellItem (null, label, null, rows, columns);
Icon icon = ImageTools.getIcon ("icons/16/documents/Page Edit.gif");
editor.setIcon (icon);
}
// This method is called when a cell value is edited by the user.
public Component getTableCellEditorComponent (final JTable table,
final Object value,
final boolean isSelected,
final int row, final int vCol)
{
editor.setValue (value);
return editor.getComponent();
}
// This method is called when editing is completed.
// It must return the new value to be stored in the cell.
public Object getCellEditorValue()
{
return editor.getValue();
}
}
|
package net.kkolyan.elements.tactics;
/**
* @author nplekhanov
*/
public interface SurfaceTypeAware {
void setSurfaceType(SurfaceType surfaceType);
}
|
package onlineShop.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "authorities")
public class Authorities implements Serializable {
private static final long serialVersionUID = 8734140534986494039L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String emailId;
private String authorities;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getAuthorities() {
return authorities;
}
public void setAuthorities(String authorities) {
this.authorities = authorities;
}
}
|
package com.apecoder.apollo.domain;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import javax.validation.constraints.NotNull;
@Data
public class ArticleEntity extends BaseEntity {
//文章id
// @TableId(value="id",type= IdType.AUTO)
// private Integer id;
@NotNull(message = "文章发布者id必填")
private Long contributorId;
//描述
private String des;
//封面图
private String coverImage;
@NotNull(message = "文章标题必传")
private String title;
@NotNull(message = "文章连接必传")
private String link;
private String tag;//文章标签
/**
* 文章分类(Android、iOS、Java等)0安卓,1 ios, 2 前端,3 java, 4 PHP, 5 python, 6 大数据, 7 人工智能
*/
@NotNull(message="分类不能为空!")
private Integer category;
//文章二级分类(开源库0、资讯1、资料2等)
private Integer sencondCategory;
//审核状态(审核中0、通过1、未通过2)
private Integer auditSatus;
@TableField(exist = false)
private UserBean user;
//收藏量
private Integer collect ;
//点赞量,(之前用的like字段,不能使用mysql关键字当做实体类字段,会导致sql语法错误)
private Integer praise;
//阅读量
private Integer pageViews;
//评论数
private Integer comments;
}
|
package com.ahu.controller;
import com.ahu.constant.MessageConstant;
import com.ahu.constant.RedisConstant;
import com.ahu.entity.Result;
import com.ahu.pojo.Order;
import com.ahu.service.OrderService;
import com.ahu.utils.SMSUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.Map;
/**
* @author :hodor007
* @date :Created in 2020/11/28
* @description :
* @version: 1.0
*/
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private JedisPool jedisPool;
@Reference
private OrderService orderService;
@RequestMapping("/submit")
public Result submit(@RequestBody Map map){
//检查验证码
String validateCode = (String) map.get("validateCode");
//从redis中获取验证码
Jedis jedis = jedisPool.getResource();
String validateCodeInRedis = jedis.get(map.get("telephone") + RedisConstant.SENDTYPE_ORDER);
jedis.close();
if(validateCode == null || validateCodeInRedis == null || !validateCode.equals(validateCodeInRedis)){
return new Result(false, MessageConstant.VALIDATECODE_ERROR);
}
Result result = null;
//调用体检预约服务
try {
map.put("orderType", Order.ORDERTYPE_WEIXIN);
result = orderService.order(map);
} catch (Exception e) {
e.printStackTrace();
//直接返回是可以的,js是弱类型,flag没有复赋值就是false
return result;
}
//发送短信通知
if(result.isFlag()){
try {
String tel = (String) map.get("telephone");
String orderDate = (String) map.get("orderDate");
SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, tel, orderDate);
} catch (ClientException e) {
e.printStackTrace();
}
}
return result;
}
@RequestMapping("/findById")
public Result findById(Integer id){
try {
Map map = orderService.findById(id);
return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS,map);
} catch (Exception e) {
e.printStackTrace();
return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
}
}
}
|
package com.androidbook.Drawing;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.View;
public class DrawBitmap extends Drawing {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new ViewWithBitmap(this));
}
private static class ViewWithBitmap extends View {
public ViewWithBitmap(Context context) {
super(context);
}
@Override protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLUE);
Bitmap jayPic = BitmapFactory.decodeResource(getResources(), R.drawable.bluejay);
// Draw the big middle jay
Bitmap jayPicMedium= Bitmap.createScaledBitmap(jayPic, 200, 300, false);
canvas.drawBitmap(jayPicMedium, 60, 75, null);
// Create the thumbnail jay
Bitmap jayPicSmall= Bitmap.createScaledBitmap(jayPic, 50, 75, false);
Matrix maxTopLeft = new Matrix();
maxTopLeft.preRotate(30);
Matrix maxBottomLeft = new Matrix();
maxBottomLeft.preRotate(-30);
Matrix maxTopRight = new Matrix();
maxTopRight.preRotate(-30); // tilt 30 degrees left
maxTopRight.preScale(-1, 1); // mirror image
Matrix maxBottomRight = new Matrix();
maxBottomRight.preRotate(30); // tilt 30 degrees right
maxBottomRight.preScale(-1, 1); // mirror image
Bitmap jayPicTopLeft = Bitmap.createBitmap(jayPicSmall, 0, 0, jayPicSmall.getWidth(), jayPicSmall.getHeight(), maxTopLeft, false);
Bitmap jayPicBottomLeft = Bitmap.createBitmap(jayPicSmall, 0, 0, jayPicSmall.getWidth(), jayPicSmall.getHeight(), maxBottomLeft, false);
Bitmap jayPicTopRight = Bitmap.createBitmap(jayPicSmall, 0, 0, jayPicSmall.getWidth(), jayPicSmall.getHeight(), maxTopRight, false);
Bitmap jayPicBottomRight = Bitmap.createBitmap(jayPicSmall, 0, 0, jayPicSmall.getWidth(), jayPicSmall.getHeight(), maxBottomRight, false);
// Free up some memory by dumping bitmaps we don't need anymore
jayPicSmall.recycle();
jayPic.recycle();
canvas.drawBitmap(jayPicTopLeft, 30, 30, null);
canvas.drawBitmap(jayPicBottomLeft, 30, 325, null);
canvas.drawBitmap(jayPicTopRight, 225, 30, null);
canvas.drawBitmap(jayPicBottomRight, 225, 325, null);
}
}
}
|
/**
*/
package iso20022;
import java.lang.String;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Model Entity</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* Abstract definition of a model entity.
* The common meta class which is the generalisation of all Meta Classes.
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link iso20022.ModelEntity#getNextVersions <em>Next Versions</em>}</li>
* <li>{@link iso20022.ModelEntity#getPreviousVersion <em>Previous Version</em>}</li>
* <li>{@link iso20022.ModelEntity#getObjectIdentifier <em>Object Identifier</em>}</li>
* </ul>
*
* @see iso20022.Iso20022Package#getModelEntity()
* @model abstract="true"
* annotation="urn:iso:std:iso:20022:2013:ecore:extension basis='IMPLEMENTATION_ENHANCEMENT' description='Abstract meta class which is the common ancestor of all ISO20022 meta classes.'"
* @generated
*/
public interface ModelEntity extends EObject {
/**
* Returns the value of the '<em><b>Next Versions</b></em>' reference list.
* The list contents are of type {@link iso20022.ModelEntity}.
* It is bidirectional and its opposite is '{@link iso20022.ModelEntity#getPreviousVersion <em>Previous Version</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* List of next versions of a ModelEntity that stem from this ModelEntity.
* Allows version control management.
* <!-- end-model-doc -->
* @return the value of the '<em>Next Versions</em>' reference list.
* @see iso20022.Iso20022Package#getModelEntity_NextVersions()
* @see iso20022.ModelEntity#getPreviousVersion
* @model opposite="previousVersion" ordered="false"
* annotation="urn:iso:std:iso:20022:2013:ecore:extension basis='RepositoryManagement' description='Versioning of Repository Objects'"
* @generated
*/
EList<ModelEntity> getNextVersions();
/**
* Returns the value of the '<em><b>Previous Version</b></em>' reference.
* It is bidirectional and its opposite is '{@link iso20022.ModelEntity#getNextVersions <em>Next Versions</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Previous version of a ModelEntity that this ModelEntity stems from.
* Allows version control management.
* <!-- end-model-doc -->
* @return the value of the '<em>Previous Version</em>' reference.
* @see #setPreviousVersion(ModelEntity)
* @see iso20022.Iso20022Package#getModelEntity_PreviousVersion()
* @see iso20022.ModelEntity#getNextVersions
* @model opposite="nextVersions" ordered="false"
* annotation="urn:iso:std:iso:20022:2013:ecore:extension basis='RepositoryManagement' description='Versioning of Repository Concepts'"
* @generated
*/
ModelEntity getPreviousVersion();
/**
* Sets the value of the '{@link iso20022.ModelEntity#getPreviousVersion <em>Previous Version</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Previous Version</em>' reference.
* @see #getPreviousVersion()
* @generated
*/
void setPreviousVersion(ModelEntity value);
/**
* Returns the value of the '<em><b>Object Identifier</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Uniquely identifies the RepositoryConcept
* <!-- end-model-doc -->
* @return the value of the '<em>Object Identifier</em>' attribute.
* @see #setObjectIdentifier(String)
* @see iso20022.Iso20022Package#getModelEntity_ObjectIdentifier()
* @model ordered="false"
* annotation="urn:iso:std:iso:20022:2013:ecore:extension basis='IMPLEMENTATION_ENHANCEMENT' description='ObjectIdentifier moved up to the meta class ModelEntity, that is the common ancestor to all ISO20022 meta classes'"
* @generated
*/
String getObjectIdentifier();
/**
* Sets the value of the '{@link iso20022.ModelEntity#getObjectIdentifier <em>Object Identifier</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Object Identifier</em>' attribute.
* @see #getObjectIdentifier()
* @generated
*/
void setObjectIdentifier(String value);
} // ModelEntity
|
package com.MY.project1;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.TextView;
import java.util.List;
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder>{
private Context context;
private List<Event>eventList;
private ItemActionListener listener;
public EventAdapter(Context context, List<Event> eventList, Fragment fragment) {
this.context = context;
this.eventList = eventList;
listener = (ItemActionListener) fragment;
}
@NonNull
@Override
public EventViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new EventViewHolder(LayoutInflater.from(context)
.inflate(R.layout.event_row, parent, false));
}
@Override
public void onBindViewHolder(@NonNull EventViewHolder holder, final int position) {
holder.nameTV.setText(eventList.get(position).getEventName());
holder.budgetTV.setText(eventList.get(position).getEndDate());
holder.menuTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(context, v);
MenuInflater inflater = popupMenu.getMenuInflater();
inflater.inflate(R.menu.person_menu,popupMenu.getMenu());
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
final String id = eventList.get(position).getEventId();
switch (item.getItemId()){
case R.id.menu_edit:
listener.onItemEdit(id);
break;
case R.id.menu_delete:
listener.onItemDelete(id);
break;
}
return false;
}
});
}
});
}
@Override
public int getItemCount() {
return eventList.size();
}
class EventViewHolder extends RecyclerView.ViewHolder {
TextView nameTV, budgetTV, menuTV;
public EventViewHolder(@NonNull View itemView) {
super(itemView);
nameTV = itemView.findViewById(R.id.row_event_name);
budgetTV = itemView.findViewById(R.id.row_event_budget);
menuTV = itemView.findViewById(R.id.row_event_menu);
}
}
public void updateList(List<Event> events){
this.eventList = events;
notifyDataSetChanged();
}
public interface ItemActionListener{
void onItemEdit(String eventID);
void onItemDelete(String eventID);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.openstack.marconi.v1.features;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import org.jclouds.openstack.marconi.v1.domain.CreateMessage;
import org.jclouds.openstack.marconi.v1.domain.Message;
import org.jclouds.openstack.marconi.v1.domain.MessageStream;
import org.jclouds.openstack.marconi.v1.domain.MessagesCreated;
import org.jclouds.openstack.marconi.v1.internal.BaseMarconiApiLiveTest;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.getOnlyElement;
import static org.jclouds.openstack.marconi.v1.options.StreamMessagesOptions.Builder.echo;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
@Test(groups = "live", testName = "MessageApiLiveTest", singleThreaded = true)
public class MessageApiLiveTest extends BaseMarconiApiLiveTest {
private static final UUID CLIENT_ID = UUID.fromString("3381af92-2b9e-11e3-b191-71861300734c");
private final Map<String, List<String>> messageIds = Maps.newHashMap();
public void createQueues() throws Exception {
for (String regionId : regions) {
QueueApi queueApi = api.getQueueApi(regionId, CLIENT_ID);
queueApi.create("jclouds-test");
}
}
@Test(dependsOnMethods = { "createQueues" })
public void streamZeroPagesOfMessages() throws Exception {
for (String regionId : regions) {
MessageApi messageApi = api.getMessageApi(regionId, CLIENT_ID, "jclouds-test");
MessageStream messageStream = messageApi.stream(echo(true));
assertTrue(Iterables.isEmpty(messageStream));
assertFalse(messageStream.nextMarker().isPresent());
}
}
@Test(dependsOnMethods = { "streamZeroPagesOfMessages" })
public void createMessage() throws Exception {
for (String regionId : regions) {
MessageApi messageApi = api.getMessageApi(regionId, CLIENT_ID, "jclouds-test");
String json1 = "{\"event\":{\"name\":\"Edmonton Java User Group\",\"attendees\":[\"bob\",\"jim\",\"sally\"]}}";
CreateMessage message1 = CreateMessage.builder().ttl(120).body(json1).build();
List<CreateMessage> message = ImmutableList.of(message1);
MessagesCreated messagesCreated = messageApi.create(message);
assertNotNull(messagesCreated);
assertEquals(messagesCreated.getMessageIds().size(), 1);
}
}
@Test(dependsOnMethods = { "createMessage" })
public void streamOnePageOfMessages() throws Exception {
for (String regionId : regions) {
MessageApi messageApi = api.getMessageApi(regionId, CLIENT_ID, "jclouds-test");
MessageStream messageStream = messageApi.stream(echo(true));
while (messageStream.nextMarker().isPresent()) {
assertEquals(Iterables.size(messageStream), 1);
messageStream = messageApi.stream(messageStream.nextStreamOptions());
}
assertFalse(messageStream.nextMarker().isPresent());
}
}
@Test(dependsOnMethods = { "streamOnePageOfMessages" })
public void createMessages() throws Exception {
for (String regionId : regions) {
MessageApi messageApi = api.getMessageApi(regionId, CLIENT_ID, "jclouds-test");
String json1 = "{\"event\":{\"name\":\"Austin Java User Group\",\"attendees\":[\"bob\",\"jim\",\"sally\"]}}";
CreateMessage message1 = CreateMessage.builder().ttl(120).body(json1).build();
String json2 = "{\"event\":{\"name\":\"SF Java User Group\",\"attendees\":[\"bob\",\"jim\",\"sally\"]}}";
CreateMessage message2 = CreateMessage.builder().ttl(120).body(json2).build();
String json3 = "{\"event\":{\"name\":\"HK Java User Group\",\"attendees\":[\"bob\",\"jim\",\"sally\"]}}";
CreateMessage message3 = CreateMessage.builder().ttl(120).body(json3).build();
List<CreateMessage> messages = ImmutableList.of(message1, message2, message3);
MessagesCreated messagesCreated = messageApi.create(messages);
assertNotNull(messagesCreated);
assertEquals(messagesCreated.getMessageIds().size(), 3);
}
}
@Test(dependsOnMethods = { "createMessages" })
public void streamManyPagesOfMessages() throws Exception {
for (String regionId : regions) {
MessageApi messageApi = api.getMessageApi(regionId, CLIENT_ID, "jclouds-test");
messageIds.put(regionId, new ArrayList<String>());
MessageStream messageStream = messageApi.stream(echo(true).limit(2));
while (messageStream.nextMarker().isPresent()) {
assertEquals(Iterables.size(messageStream), 2);
for (Message message : messageStream) {
messageIds.get(regionId).add(message.getId());
}
messageStream = messageApi.stream(messageStream.nextStreamOptions());
}
assertFalse(messageStream.nextMarker().isPresent());
}
}
@Test(dependsOnMethods = { "streamManyPagesOfMessages" })
public void listMessagesByIds() throws Exception {
for (String regionId : regions) {
MessageApi messageApi = api.getMessageApi(regionId, CLIENT_ID, "jclouds-test");
List<Message> messages = messageApi.list(messageIds.get(regionId));
assertEquals(messages.size(), 4);
for (Message message : messages) {
assertNotNull(message.getId());
assertNotNull(message.getBody());
}
}
}
@Test(dependsOnMethods = { "listMessagesByIds" })
public void getMessage() throws Exception {
for (String regionId : regions) {
MessageApi messageApi = api.getMessageApi(regionId, CLIENT_ID, "jclouds-test");
Message message = messageApi.get(getLast(messageIds.get(regionId)));
assertNotNull(message.getId());
assertNotNull(message.getBody());
}
}
@Test(dependsOnMethods = { "getMessage" })
public void deleteMessagesByClaimId() throws Exception {
for (String regionId : regions) {
UUID clientId = UUID.fromString("3381af92-2b9e-11e3-b191-71861300734c");
MessageApi messageApi = api.getMessageApi(regionId, CLIENT_ID, "jclouds-test");
ClaimApi claimApi = api.getClaimApi(regionId, clientId, "jclouds-test");
Message message = getOnlyElement(claimApi.claim(300, 100, 1));
boolean success = messageApi.deleteByClaim(message.getId(), message.getClaimId().get());
assertTrue(success);
}
}
@Test(dependsOnMethods = { "deleteMessagesByClaimId" })
public void deleteMessages() throws Exception {
for (String regionId : regions) {
MessageApi messageApi = api.getMessageApi(regionId, CLIENT_ID, "jclouds-test");
boolean success = messageApi.delete(messageIds.get(regionId));
assertTrue(success);
}
}
@Test(dependsOnMethods = { "deleteMessages" })
public void delete() throws Exception {
for (String regionId : regions) {
QueueApi queueApi = api.getQueueApi(regionId, CLIENT_ID);
boolean success = queueApi.delete("jclouds-test");
assertTrue(success);
}
}
}
|
package com.jackfahdin.otaupdate;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.RecoverySystem;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
/**
* @author user
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "MainActivity";
String[] needPermissions = new String[]{
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//checkPermission();
buildVersionView();
Button updateButton = (Button) findViewById(R.id.version_update);
updateButton.setOnClickListener(this);
}
private void buildVersionView() {
Log.d(TAG, "buildVersionView: " + Build.DISPLAY);
TextView buildTextView = (TextView) findViewById(R.id.build_version);
buildTextView.setText(Build.DISPLAY);
}
private void checkPermission() {
requestPermissions(needPermissions, 1);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.version_update) {
buildUpdateButton();
}
}
/**
* 获取升级包
*
* @return 升级包file
*/
public File getUpdateFile() {
File updateFile = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String updatePath = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "update.zip";
updateFile = new File(updatePath);
boolean isExists = updateFile.exists();
Log.d(TAG, "getUdapteFile: 是否存在升级包 " + isExists);
if (isExists) {
return updateFile;
}
}
return updateFile;
}
/**
* 系统升级
*/
private void buildUpdateButton() {
File updateFileInstall = getUpdateFile();
try {
//签名校验
RecoverySystem.verifyPackage(updateFileInstall, new RecoverySystem.ProgressListener() {
@Override
public void onProgress(int progress) {
Log.d(TAG, "onProgress: 签名校验进度: " + progress);
}
}, null);
//升级
RecoverySystem.installPackage(this, updateFileInstall);
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
}
|
package dk.jrpe.monitor.webservice.cxf.async;
import java.util.Random;
import javax.xml.ws.AsyncHandler;
import javax.xml.ws.Response;
import dk.jrpe.monitor.webservice.cxf.generated.endpoint.SendHTTPAccessDataResponse;
/**
*
* @author Jörgen Persson
*
*/
public class WebServiceAsyncHandler implements AsyncHandler<SendHTTPAccessDataResponse> {
private SendHTTPAccessDataResponse response;
private final Random random = new Random();
public void handleResponse(Response<SendHTTPAccessDataResponse> response) {
try {
/*
* Simulate a delay in the async. call
*/
Thread.sleep(random.nextInt(3000));
this.response = response.get();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public String getStatus() {
return this.response.getStatus();
}
}
|
package com.adwork.microservices.admessage.conrtoller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
@RestController
public class ExceptionController extends ResponseEntityExceptionHandler {
@ExceptionHandler(AdMessagesException.class)
public final ResponseEntity<String> handleAdMessagesException(AdMessagesException ex, WebRequest request) {
return getResponse(ex.getMessage(), ex.getCode());
}
@ExceptionHandler(Exception.class)
public final ResponseEntity<String> handleAllExceptions(Exception ex, WebRequest request) {
String error = "Error: " + ex.getMessage() + "\n" + request.getDescription(false);
return getResponse(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
ResponseEntity<String> getResponse(String message, HttpStatus code) {
return new ResponseEntity<>(message, code);
}
}
|
package com.redstoner.remote_console.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InvalidObjectException;
import java.nio.file.NoSuchFileException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Properties;
import com.redstoner.remote_console.protected_classes.Main;
/**
* This class is responsible for loading the config and dealing with launch parameters.
* It will not repair missing values , but silently use the default values instead.
* If the rmc.repOTG value is set to true, it will repair invalid values it encounters by at first, trying to make sense out of the invalid value and if that doesn't work, restore it with the default value.
* If rmc.repOTG is not set, it will throw an error and load the default value, but it will not touch the config file.
*
* @author Pepich1851
*/
public class ConfigHandler
{
private static final File propertiesFile = new File("plugins/rmc-config.properties");
private static final Properties defaultProps = new Properties();
private static final Properties properties = new Properties(defaultProps);
private static boolean hasBeenModified = false;
private static boolean repairOTG = true;
static
{
try
{
InputStreamReader defaultIn = new InputStreamReader(
ConfigHandler.class.getResourceAsStream("/defaultconfig.properties"));
defaultProps.load(defaultIn);
defaultIn.close();
if (!propertiesFile.exists())
{
Main.logger.info("Missing config file. Restoring defaults...");
propertiesFile.createNewFile();
BufferedReader reader = new BufferedReader(
new InputStreamReader(ConfigHandler.class.getResourceAsStream("/defaultconfig.properties")));
BufferedWriter writer = new BufferedWriter(new FileWriter(propertiesFile));
String line = "";
while ((line = reader.readLine()) != null)
{
writer.write(line);
writer.newLine();
}
writer.flush();
reader.close();
writer.close();
}
FileInputStream customIn = new FileInputStream(propertiesFile);
properties.load(customIn);
customIn.close();
try
{
repairOTG = getBoolean("rmc.rotg");
}
catch (NoSuchElementException | InvalidObjectException e)
{
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* To be called when the plugin gets disabled. Saves the config if it has been modified.
*/
public static void disable()
{
if (hasBeenModified)
{
try
{
FileOutputStream customOut = new FileOutputStream(propertiesFile);
properties.store(customOut, "");
customOut.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* Reads an integer from the config file.
*
* @param path the path to the parameter to be read.
* @return the int.
* @throws NoSuchElementException if the specified path could not be found
* @throws InvalidObjectException if the object from the config could not be deserialized into an int
*/
public static int getInt(String path) throws NoSuchElementException, InvalidObjectException
{
if (properties.getProperty(path) == null) throw new NoSuchElementException("Could not find object at " + path);
try
{
int i = Integer.valueOf(properties.getProperty(path));
return i;
}
catch (NumberFormatException e)
{
if (repairOTG)
{
Main.logger.warning("Found invalid value at " + path + ", attempting to restore the default value.");
properties.setProperty(path, defaultProps.getProperty(path));
hasBeenModified = true;
try
{
int i = Integer.valueOf(properties.getProperty(path));
return i;
}
catch (NumberFormatException e2)
{
throw new InvalidObjectException(
"The value found at " + path + "could not be deserialized into an int.");
}
}
else
throw new InvalidObjectException(
"The value found at " + path + "could not be deserialized into an int.");
}
}
/**
* Reads a boolean from the config file.
*
* @param path the path to the parameter to be read.
* @return the boolean.
* @throws NoSuchElementException if the specified path could not be found
* @throws InvalidObjectException if the object from the config could not be deserialized into a boolean
*/
public static boolean getBoolean(String path) throws NoSuchElementException, InvalidObjectException
{
if (properties.getProperty(path) == null) throw new NoSuchElementException("Could not find object at " + path);
String raw = properties.getProperty(path);
try
{
return toBoolean(raw);
}
catch (InvalidObjectException e)
{
if (repairOTG)
{
Main.logger.warning("Found invalid value at " + path + ", attempting to restore the default value.");
raw = defaultProps.getProperty(path);
properties.setProperty(path, raw);
hasBeenModified = true;
if (raw.equalsIgnoreCase("true") || raw.equalsIgnoreCase("t") || raw.equalsIgnoreCase("yes")
|| raw.equalsIgnoreCase("y") || raw.equals("1") || raw.equals("+"))
return true;
if (raw.equalsIgnoreCase("false") || raw.equalsIgnoreCase("f") || raw.equalsIgnoreCase("no")
|| raw.equalsIgnoreCase("n") || raw.equals("0") || raw.equals("-"))
return false;
else
throw new InvalidObjectException(
"The value found at " + path + "could not be deserialized into a boolean.");
}
else
throw new InvalidObjectException(
"The value found at " + path + "could not be deserialized into a boolean.");
}
}
/**
* Reads a String from the config file.
*
* @param path the path to the parameter to be read.
* @return the String.
* @throws NoSuchElementException if the specified path could not be found
* @throws InvalidObjectException if the object from the config could not be deserialized into a String
*/
public static String getString(String path) throws NoSuchElementException, InvalidObjectException
{
String raw = properties.getProperty(path);
if (raw == null) throw new NoSuchElementException("Could not find object at " + path);
if (!raw.startsWith("\"") || !raw.endsWith("\""))
throw new InvalidObjectException("The value found at " + path + "could not be deserailized into a String.");
return raw.substring(1, raw.length() - 1);
}
/**
* Reads an Array of String from the config file. Invokes getStringArray(path, (char)0);.
*
* @param path the path to the parameter to be read.
* @return the Array of String.
* @throws NoSuchElementException if the specified path could not be found
* @throws InvalidObjectException if the object from the config could not be deserialized into an Array of String
*/
public static String[] getStringArray(String path) throws NoSuchElementException, InvalidObjectException
{
return getStringArray(path, (char) 0);
}
/**
* Reads an Array of String from the config file.
*
* @param path the path to the parameter to be read.
* @param startingChar a char to be expected in front of the array.
* @return the Array of String.
* @throws NoSuchElementException if the specified path could not be found
* @throws InvalidObjectException if the object from the config could not be deserialized into an Array of String
*/
public static String[] getStringArray(String path, char startingChar)
throws NoSuchElementException, InvalidObjectException
{
String raw = properties.getProperty(path);
if (raw == null) throw new NoSuchElementException("Could not find object at " + path);
if (startingChar != (char) 0)
{
if (raw.startsWith("" + startingChar))
raw = raw.substring(1);
else
throw new InvalidObjectException("The value found at " + path
+ " could not be deserialized into an Array of String. Error at char 1, expected "
+ startingChar + " but found '" + raw.charAt(0) + "'.");
}
if (raw.startsWith("[") && raw.endsWith("]"))
{
boolean error = false;
CharSequence[] expected = null;
ArrayList<String> strings = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
boolean inString = true, escaped = false;
int i = 1;
while (raw.charAt(i) == ' ')
i++;
char c = 0;
for (i = 2; i < raw.length(); i++)
{
c = raw.charAt(i);
if (inString)
{
if (escaped)
{
if (c == '\\' || c == '"')
{
sb.append(c);
escaped = false;
}
else
{
error = true;
expected = new CharSequence[] { "'\"'", "'\\'" };
break;
}
}
else if (c == '"')
{
inString = !inString;
}
else if (c == '\\')
{
escaped = true;
}
else
sb.append(c);
}
else
while (raw.charAt(i) == ' ')
i++;
if (c == ',')
{
strings.add(sb.toString());
i++;
while (raw.charAt(i) == ' ')
i++;
if (raw.charAt(i) == '"')
{
sb = new StringBuilder();
inString = true;
}
else
{
error = true;
expected = new CharSequence[] { "'\"'" };
break;
}
}
else if (c == ']' && i == raw.length() - 1)
{
strings.add(sb.toString());
}
else
{
error = true;
expected = new CharSequence[] { "','" };
break;
}
}
if (error) throw new InvalidObjectException(
"The value found at " + path + " could not be deserialized into an Array of String. Error at char "
+ i + ", expected " + String.join(" or ", expected) + " but found '" + c + "'.");
return strings.toArray(new String[] {});
}
else
throw new InvalidObjectException(
"The value found at " + path + " could not be deserialized into an Array of String.");
}
/**
* Reads a File from the config file. Will invoke getFile(path, false).
*
* @param path the path to the parameter to be read.
* @return the boolean.
* @throws NoSuchElementException if the specified path could not be found
* @throws InvalidObjectException if the object from the config could not be deserialized into a valid Path
*/
public static File getFile(String path) throws NoSuchElementException, InvalidObjectException
{
try
{
return getFile(path, false);
}
catch (NoSuchFileException e)
{
return null;
}
}
/**
* Reads a File from the config file.
*
* @param path the path to the parameter to be read.
* @param checkIfExists set to true if you only want the file back if it already exists. If true and the file does not exist, it will generate an exception.
* @return the boolean.
* @throws NoSuchElementException if the specified path could not be found
* @throws InvalidObjectException if the object from the config could not be deserialized into a valid Path
* @throws NoSuchFileException if the file does not exist but the requesting parameter is set.
*/
public static File getFile(String path, boolean checkIfExists)
throws NoSuchElementException, InvalidObjectException, NoSuchFileException
{
String location = getString(path);
if (location == null) throw new NoSuchElementException("Could not find object at " + path);
File f = new File(location);
if (checkIfExists && !f.exists()) throw new NoSuchFileException("Could not find file at " + location + ".");
return f;
}
public static boolean toBoolean(String raw) throws InvalidObjectException
{
if (raw.equalsIgnoreCase("true") || raw.equalsIgnoreCase("t") || raw.equalsIgnoreCase("yes")
|| raw.equalsIgnoreCase("y") || raw.equals("1") || raw.equals("+"))
return true;
if (raw.equalsIgnoreCase("false") || raw.equalsIgnoreCase("f") || raw.equalsIgnoreCase("no")
|| raw.equalsIgnoreCase("n") || raw.equals("0") || raw.equals("-"))
return false;
else
throw new InvalidObjectException("The given String could not be converted into a boolean.");
}
}
|
package com.xt.activemq.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import javax.jms.TextMessage;
@Service
public class SpringMQ_Producer {
@Autowired
private JmsTemplate jmsTemplate;
public static void main(String[] args) {
ApplicationContext ioc = new ClassPathXmlApplicationContext("classpath:beans.xml");
SpringMQ_Producer producer = ioc.getBean("springMQ_Producer", SpringMQ_Producer.class);
producer.jmsTemplate.send((session) -> {
TextMessage textMessage = session.createTextMessage("***Spring 和 ActiveMQ 整合的 case for MessageListener 333....");
return textMessage;
});
System.out.println("******send task over");
}
}
|
package worldData.tileInfo;
public class tileDungeonPoison {
public String tileName; //The name to display the tile as
public String description = null; //A general description of the tile.
public boolean isWalkable = true; // Can the player walk on this tile?
public int localTemp = 72; //Do liquids freeze on this tile?
public boolean isFlammable = true; //Does this tile burn?
public boolean isBurning = false; //Is this tile currently on fire?
public int baseBurnTime = 4; //How many updates does it burn? (-1 is infinite)
public boolean canHoldFluid = true; //Does liquid stay on this tile?
public String fluidOnGround = null; //What liquid is on this tile?
public int fluidLevel = 0; //How many updates till the fluid disperses? (-1 is infinite)
public boolean isTeleporter = false; //Does the player teleport when stepping on this tile?
public int[] teleportTo = new int[]{0, 0, 15, 15}; //Where does the player teleport to? (Format: {Map #, Floor, x, y})
public tileDungeonPoison(String inputData){
tileName = inputData;
}
}
|
package dto;
import entities.GeoCityDetails;
import entities.Photo;
import entities.PhotoCandidates;
import java.util.List;
/**
*
* @author miade
*/
public class StandartDTO {
private String time;
private RealtorDTO realtorDTO;
private String placeID;
private List<String> photoRefs;
private GeoCityDTO geoCityDTO;
private GeoCityDetailsDTO geoCityDetailsDTO;
public StandartDTO(RealtorDTO realtorDTO, String time) {
this.time = time;
this.realtorDTO = realtorDTO;
}
public StandartDTO(String placeID, String time) {
this.time = time;
this.placeID = placeID;
}
public StandartDTO(List<String> photoRefs, String time) {
this.time = time;
this.photoRefs = photoRefs;
}
public StandartDTO(GeoCityDTO geoCityDTO, String time) {
this.time = time;
this.geoCityDTO = geoCityDTO;
}
public StandartDTO(GeoCityDetailsDTO geoCityDetailsDTO, String time) {
this.time = time;
this.geoCityDetailsDTO = geoCityDetailsDTO;
}
}
|
package com.chao.wifiscaner.action;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import me.drakeet.materialdialog.MaterialDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import com.chao.wifiscaner.controller.Controller;
import com.chao.wifiscaner.model.WifiItem;
import com.chao.wifiscaner.ui.PutActivity;
import com.chao.wifiscaner.ui.WebActivity;
import com.chao.wifiscaner.utils.FileUtil;
import com.chao.wifiscaner.utils.ToolUtil;
import com.chao.wifiscaner.view.LoadingDialog;
public class OutputAction extends PutAction {
private String outPath;
private MaterialDialog mDialog;
private String timeStamp="";
private String filename="";
public OutputAction(Controller controller) {
super(controller);
dialog.setLoadingText("导出数据……");
}
@Override
public void run(Object... params) {
outPath=FileUtil.getBackupPath()+"/";
timeStamp=ToolUtil.getCurrentTime(ToolUtil.TIME_STAMP);
filename=getFileName();
mDialog=new MaterialDialog(activity).setTitle("导出成功")
.setMessage("WiFi密码:"+wifiItems.size()+"\n你可以把导出的文件("+FileUtil.getBackupPath()+")复制到新的手机上导入")
.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
}
})
.setNegativeButton("查看", new OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
String url="file://"+outPath+filename+".html";
String title=ToolUtil.getNormalTimeByStamp(timeStamp);
Intent intent=WebActivity.creatURLIntent(activity, url, title);
ToolUtil.startActivityWithAnim(activity, intent);
}
});
new OutputTask().execute(filename);
}
class OutputTask extends AsyncTask<String, Integer, Void>{
@Override
protected void onPreExecute() {
dialog.show();
}
@Override
protected Void doInBackground(String... params) {
output(params[0], getContent());
return null;
}
@Override
protected void onPostExecute(Void result) {
//刷新一下导出列表
controller.runAction(ActionCode.GET_PUT);
dialog.dismiss();
mDialog.show();
}
}
private String getFileName(){
//wsbak_1426852920337_5
return "wsbak_"+timeStamp+"_"+wifiItems.size();
}
private String getContent(){
StringBuilder content = new StringBuilder();
String part1="<!DOCTYPE html><html lang='cn'><head><meta charset='UTF-8'><title>WiFi密码查看器导出文件</title></head><body><h1>WiFi密码查看器导出文件</h1><h2>";
String part2=ToolUtil.getNormalTimeByStamp(timeStamp);
String part3="</h2><table border='1'><tr><th>WiFi热点</th><th>密码</th></tr>";
//part4--mainContent
StringBuilder part4 = new StringBuilder();
String part5="</table><h3>WiFi密码查看器,无线你的生活<br><a href='http://wifiscaner.bmob.cn/'>点此下载</a></h3></body></html>";
for(WifiItem item:wifiItems){
part4.append("<tr><td>"+item.getName()+"</td><td >"+item.getPassword()+"</td></tr>");
}
return content.append(part1).append(part2).append(part3).append(part4).append(part5).toString();
}
public void output(String filename,String content) {
try {
File f = new File(outPath+filename+".html");
if (f.exists()) {
System.out.print("文件存在");
} else {
System.out.print("文件不存在");
f.createNewFile();
}
BufferedWriter output = new BufferedWriter(new FileWriter(f));
output.write(content);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package org.vaadin.addons.tokenfilter.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class TestFilterType extends AbstractFilterType<String> {
public TestFilterType(String val) {
super(val);
}
public TestFilterType(String val, String... options) {
super(val);
Collection<TestFilterOption> optionList = new ArrayList<>();
for (String o : options) {
TestFilterOption filterOption = new TestFilterOption(o);
optionList.add(filterOption);
addOption(filterOption);
}
setSelected((Collection) optionList);
}
@Override
public String getTitle() {
return getIdentifier();
}
}
|
package com.stylefeng.guns.rest.modular.auth.validator.impl;
import com.alibaba.dubbo.config.annotation.Reference;
import com.cskaoyan.service.UserService;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.rest.modular.auth.validator.IReqValidator;
import com.stylefeng.guns.rest.modular.auth.validator.dto.Credence;
import org.springframework.stereotype.Component;
/**
* @Author: yyc
* @Date: 2019/6/4 20:05
*/
@Component("userValidator")
public class UserValidator implements IReqValidator {
@Reference
UserService userService;
@Override
public boolean validate(Credence credence) {
String pwd = userService.getPwdByUsername(credence.getCredenceName());
return MD5Util.encrypt(credence.getCredenceCode()).equals(pwd);
}
}
|
package net.cglab.hotelpraktikum.utils;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import net.cglab.hotelpraktikum.dto.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class StrutsSessionUtil{
public final static Logger LOG = Logger.getLogger(StrutsSessionUtil.class);
public static void putToSession(ActionContext context, String key, Object value){
try {
if(context.getSession().containsKey(key)){
context.getSession().remove(key);
}
} catch (Exception e) {
// nothig to do
}
context.getSession().put(key, value);
}
public static void putToSession(Map<String, Object> session, String key, Object value){
try {
if(session.containsKey(key)){
session.remove(key);
}
} catch (Exception e) {
// nothig to do
}
session.put(key, value);
}
public static void putToSession(HttpServletRequest request, String key, Object value){
try {
if(request.getSession().getAttribute(key)!=null ){
request.getSession().removeAttribute(key);
}
} catch (Exception e) {
// nothig to do
}
request.getSession().setAttribute(key, value);
}
public static Object getFromSession(ActionContext context, String key){
try {
if(context.getSession().containsKey(key)){
return context.getSession().get(key);
}
} catch (Exception e) {
LOG.debug("Wasn't able to retreive attribute "+key+" from session...");
}
return null;
}
public static Object getFromServletContext(ServletContext context, String key){
try {
if(context.getAttribute(key) != null){
return context.getAttribute(key);
}
} catch (Exception e) {
LOG.debug("Wasn't able to retreive attribute "+key+" from servlet context...");
}
return null;
}
public static void initJobDurations(ActionSupport action) {
HashMap<String, String> jobDurations = new HashMap<String, String>(); action.getLocale().getLanguage();
jobDurations.put("lessThen3Months", action.getText("job.lessThen3Months"));
jobDurations.put("3Months", action.getText("job.3Months"));
jobDurations.put("4to5Months",action.getText("job.4to5Months"));
jobDurations.put("6Months",action.getText("job.6Months"));
jobDurations.put("moreThen6Months", action.getText("job.moreThen6Months"));
putToSession(ActionContext.getContext(), ApplicationConstants.JOB_DURATIONS, jobDurations);
}
public static void initJobLocations(ActionSupport action) {
HashMap<String, String> jobLocations = new HashMap<String, String>();
jobLocations.put("france", action.getText("job.country.france"));
jobLocations.put("germany", action.getText("job.country.germany"));
jobLocations.put("greatBritain",action.getText("job.country.greatBritain"));
jobLocations.put("irland",action.getText("job.country.irland"));
jobLocations.put("spPeninsula", action.getText("job.country.spPeninsula"));
jobLocations.put("spCanarias", action.getText("job.country.spCanarias"));
jobLocations.put("spBalearias", action.getText("job.country.spBalearias"));
putToSession(ActionContext.getContext(), ApplicationConstants.JOB_LOCATIONS, jobLocations);
}
public static void initUserLanguages(ActionSupport action) {
// TODO Auto-generated method stub
HashMap<String, String> userLanguages = new HashMap<String, String>();
userLanguages.put("en",action.getText("user.language.en"));
userLanguages.put("es",action.getText("user.language.es"));
userLanguages.put("fr",action.getText("user.language.fr"));
userLanguages.put("de", action.getText("user.language.de"));
putToSession(ActionContext.getContext(), ApplicationConstants.USER_LANGUAGES, userLanguages);
}
public static void initJobPayments(ActionSupport action) {
HashMap<String, String> jobPayments = new HashMap<String, String>();
jobPayments.put("0",action.getText("job.unpayed"));
jobPayments.put("1",action.getText("job.payed"));
putToSession(ActionContext.getContext(), ApplicationConstants.JOB_PAYMENTS, jobPayments);
}
public static void initJobActivityFields(ActionSupport action) {
HashMap<String, String> jobActivityFields = new HashMap<String, String>();
jobActivityFields.put("animation_fitness",action.getText("job.animation_fitness"));
jobActivityFields.put("housekeeping",action.getText("job.housekeeping"));
jobActivityFields.put("kitchen",action.getText("job.kitchen"));
jobActivityFields.put("reception",action.getText("job.reception"));
jobActivityFields.put("administration",action.getText("job.administration"));
jobActivityFields.put("marketing",action.getText("job.marketing"));
jobActivityFields.put("management",action.getText("job.management"));
jobActivityFields.put("sells",action.getText("job.sells"));
jobActivityFields.put("service",action.getText("job.service"));
jobActivityFields.put("other",action.getText("job.other"));
putToSession(ActionContext.getContext(), ApplicationConstants.JOB_ACTIVITY_FIELDS, jobActivityFields);
}
public static void initSelectYesNo(ActionSupport action) {
HashMap<String, String> selectYesNo = new HashMap<String, String>();
selectYesNo.put("1",action.getText("select.yes"));
selectYesNo.put("0",action.getText("select.no"));
putToSession(ActionContext.getContext(), ApplicationConstants.SELECT_YES_NO, selectYesNo);
}
public static void initProperties(ActionSupport action, HttpServletRequest request) {
try{
Locale locale;
if(StringUtils.contains(request.getQueryString(), ApplicationConstants.LOCALE_REQUEST_PARAM)){
locale = new Locale(request.getParameter(ApplicationConstants.LOCALE_REQUEST_PARAM));
}else if(request.getSession().getAttribute(ApplicationConstants.SESSION_ATTR_USER )!= null){
User user = (User)request.getSession().getAttribute(ApplicationConstants.SESSION_ATTR_USER );
locale = new Locale(user.getLanguage());
}else{
locale = request.getLocale();
}
ActionContext.getContext().setLocale(locale);
StrutsSessionUtil.initSelectYesNo(action);
StrutsSessionUtil.initUserLanguages(action);
StrutsSessionUtil.initJobLocations(action);
StrutsSessionUtil.initJobDurations(action);
StrutsSessionUtil.initJobPayments(action);
StrutsSessionUtil.initJobActivityFields(action);
}catch(Exception e){
LOG.error(e);//NOTHING TO DO
}
}
}
|
package twice.pbdtest;
import android.util.Log;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Alif on 23/02/2017.
*/
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
private FirebaseAuth mAuth;
@Override
public void onTokenRefresh() {
//Getting registration token
String token = FirebaseInstanceId.getInstance().getToken();
//Displaying token on logcat
Log.d(TAG, "Refreshed token: " + token);
mAuth = FirebaseAuth.getInstance();
if(mAuth.getCurrentUser()!=null) {
FirebaseDatabase fbdb = FirebaseDatabase.getInstance();
final DatabaseReference databaseReference = fbdb.getReference("users");
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference userRef = databaseReference.child(user_id);
Map<String, Object> userUpdates = new HashMap<String, Object>();
userUpdates.put("token", token);
userRef.updateChildren(userUpdates);
}
}
private void sendRegistrationToServer(String token) {
//You can implement this method to store the token on your server
}
}
|
package bis.project.model;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.fasterxml.jackson.annotation.JsonIgnore;
import bis.project.security.User;
@Entity
public class Bank {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(nullable=false, length=3)
private int bankCode;
@Column(nullable=false, length=50)
private String name;
@Column(nullable=false, length=8)
private String swiftCode;
@Column(nullable=false, length=18)
private String billingAccount;
@OneToMany(mappedBy="bank")
@JsonIgnore
private Set<BankAccount> accounts;
@OneToMany(mappedBy="senderBank")
@JsonIgnore
private Set<InterbankTransfer> sentTransfers;
@OneToMany(mappedBy="recipientBank")
@JsonIgnore
private Set<InterbankTransfer> receivedTransfers;
@OneToMany(mappedBy="bank")
@JsonIgnore
private Set<User> users;
public Bank() {}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getBankCode() {
return bankCode;
}
public void setBankCode(int bankCode) {
this.bankCode = bankCode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSwiftCode() {
return swiftCode;
}
public void setSwiftCode(String swiftCode) {
this.swiftCode = swiftCode;
}
public String getBillingAccount() {
return billingAccount;
}
public void setBillingAccount(String billingAccount) {
this.billingAccount = billingAccount;
}
public Set<BankAccount> getAccounts() {
return accounts;
}
public void setAccounts(Set<BankAccount> accounts) {
this.accounts = accounts;
}
public Set<InterbankTransfer> getSentTransfers() {
return sentTransfers;
}
public void setSentTransfers(Set<InterbankTransfer> sentTransfers) {
this.sentTransfers = sentTransfers;
}
public Set<InterbankTransfer> getReceivedTransfers() {
return receivedTransfers;
}
public void setReceivedTransfers(Set<InterbankTransfer> receivedTransfers) {
this.receivedTransfers = receivedTransfers;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
|
package model;
public class Board_Type_DTO {
private String board_type;
private int row_index;
public String getBoard_type() {
return board_type;
}
public void setBoard_type(String board_type) {
this.board_type = board_type;
}
public int getRow_index() {
return row_index;
}
public void setRow_index(int row_index) {
this.row_index = row_index;
}
public Board_Type_DTO() {}
}
|
package com.blackbird.model.zone;
import java.io.Serializable;
public class Zone implements Serializable {
private static final long serialVersionUID = 1L;
private Integer zoneId;
private String zoneName;
private Integer accountId;
public Zone(Integer zoneId, String zoneName, Integer accountId) {
this.zoneId = zoneId;
this.zoneName = zoneName;
this.accountId = accountId;
}
public Integer getZoneId() {
return zoneId;
}
public void setZoneId(Integer zoneId) {
this.zoneId = zoneId;
}
public String getZoneName() {
return zoneName;
}
public void setZoneName(String zoneName) {
this.zoneName = zoneName;
}
public Integer getAccountId() {
return accountId;
}
public void setAccountId(Integer accountId) {
this.accountId = accountId;
}
}
|
package algebra;
import java.util.ArrayList;
import java.util.List;
/**
* Decomposition a number into a series of prime factors
*
* Partial problem of Eratosthenes Sieve
*/
public class PrimeDecomposition {
List<Integer> primeDecompose(int n) {
List<Integer> primeFactors = new ArrayList<>();
int factor = 2;
while (factor * factor <= n) {
if (n % factor == 0) {
primeFactors.add(factor);
n = n / factor;
} else {
factor++;
}
}
primeFactors.add(n);
return primeFactors;
}
public static void main(String[] args) {
PrimeDecomposition primeDecomposition = new PrimeDecomposition();
List<Integer> factors = primeDecomposition.primeDecompose(256);
System.out.println(factors);
}
}
|
package com.company.semaphore;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Semaphore {
private static final Logger logger = LoggerFactory.getLogger(Semaphore.class.getSimpleName());
private LinkedHashSet<String> pendingThreadSet = new LinkedHashSet<String>();
private LinkedList<String> permitThreadList = new LinkedList<String>();
private int maxPermits = 0;
private Integer permitCounter = 0;
public Semaphore() {
this.maxPermits = 1;
}
public Semaphore(int permits) {
if (permits > 0) {
this.maxPermits = permits;
}
}
// if there are available permits
// - increase the permit counter
// - add the acquiring thread to permitThreadList
// else
// - add the acquiring thread to pendingThreadSet
// - block the acquiring thread
public synchronized void acquire() throws InterruptedException {
String currentThreadName = new String(Thread.currentThread().getName());
logger.info("Acquiring a permit: {}", toString());
if (permitCounter >= maxPermits) {
pendingThreadSet.add(currentThreadName);
while (permitCounter >= maxPermits && getQueuedThreads().contains(currentThreadName)) {
logger.info("Waiting for a permit: {}", toString());
this.wait();
}
logger.info("Re-acquiring a permit: {}", toString());
}
permitThreadList.add(currentThreadName);
permitCounter += 1;
logger.info("Acquired a permit: {}", toString());
}
/**
* decrement permit counter remove the releasing thread from the permitThreadList if there are threads on pendingThreadSet - notify the first blocking thread
* and - remove it from the pendingThreadSet
*/
public synchronized void release() {
logger.info("Releasing a permit: {}", toString());
permitCounter -= 1;
String currentThreadName = new String(Thread.currentThread().getName());
permitThreadList.remove(currentThreadName);
if (pendingThreadSet.size() > 0) {
Iterator<String> it = pendingThreadSet.iterator();
String nextThreadName = it.next();
it.remove();
logger.info("Notifying thread: {}", nextThreadName);
this.notifyAll();
}
}
public int availablePermits() {
return (maxPermits - permitCounter);
}
public int getQueueLength() {
return pendingThreadSet.size();
}
public Collection<String> getQueuedThreads() {
return pendingThreadSet;
}
public Collection<String> getAcquiredThreads() {
return permitThreadList;
}
public boolean tryAcquire() {
// TODO Auto-generated method stub
return false;
}
public String toString() {
return String.format("Permits: max=%s; available=%s; Queued threads=%s; Acquired threads=%s", maxPermits, availablePermits(), getQueuedThreads(),
getAcquiredThreads());
}
}
|
package com.ccspace.facade.domain.common.util;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* @AUTHOR CF
* @DATE Created on 2017/9/8 16:21.
*/
public class SecurityLogic {
static Logger logger = LoggerFactory.getLogger(SecurityLogic.class);
public static final String TOKEN_AES_KEY = "N13iJFLBjrlBA5aw";
// 加密
private static String encryptAES(String sSrc, String sKey) throws Exception {
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
// 解密
public static String decryptAES(String sSrc, String sKey) throws Exception {
try {
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} catch (Exception e) {
logger.info(e.toString());
return null;
}
} catch (Exception ex) {
logger.info(ex.toString());
return null;
}
}
/**
* 加密 token
*
* @param userId
* @param token
* @return
*/
public static String encryptToken(Long userId, String token) {
String toEncrypt = userId + "|" + token;
try {
return encryptAES(toEncrypt, TOKEN_AES_KEY);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 加密密码
*
* @param password
* @return
*/
public static String encryptPassword(String password) {
return SecurityUtil.SHA1(SecurityUtil.MD5(password));
}
/**
* @param
* @return
* @description md5加密
* @author CF create on 2017/7/12 9:37
*/
public static String encryptMD5(String password) {
return SecurityUtil.MD5(password);
}
public static String sha1Encrypt(String password) {
return SecurityUtil.SHA1(password);
}
public static void main(String[] args) throws Exception {
// System.out.println(encryptPassword("123456"));
System.out.println(SecurityUtil.MD5("123456"));//e10adc3949ba59abbe56e057f20f883e
System.out.println(SecurityUtil.SHA1("e10adc3949ba59abbe56e057f20f883e"));//e10adc3949ba59abbe56e057f20f883e
// System.out.println(SecurityUtil.SHA1("123456"));
}
}
|
class resizable_main extends ResizableCircle
{
public static void main(String[] args)
{
ResizableCircle rc=new ResizableCircle(10.0);
System.out.println("perimeter"+rc.getPerimeter());
System.out.println("area"+rc.getArea());
}
} |
package enshud.s2.parser.parsers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import enshud.minipascal.SyntaxSetting;
public class NonterminalParser extends AbstractNonterminalParser {
private static HashMap<String, Map<Integer, ArrayList<IParser>>> parseRuleMemo;
public NonterminalParser(String variableName) {
this.variableName = variableName;
this.generativeRule = SyntaxSetting.generativeRule.get(variableName);
parseRuleMemo = new HashMap<String, Map<Integer, ArrayList<IParser>>>();
}
@Override
public Set<Integer> first() {
if(parseRule == null && !parseRuleMemo.containsKey(this.variableName)) {
super.first();
parseRuleMemo.put(this.variableName, this.parseRule);
}
this.parseRule = parseRuleMemo.get(this.variableName);
return parseRule.keySet();
}
}
|
package de.kopis.db.dao;
import java.util.List;
import de.kopis.db.model.Report;
public interface ReportDAO {
void saveReport(Report report);
List<Report> listReports();
}
|
// Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.reviewit.widget;
import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.support.annotation.ColorRes;
import android.support.annotation.IdRes;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gerrit.extensions.common.AccountInfo;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.reviewit.R;
import com.google.reviewit.app.Change;
import com.google.reviewit.app.Preferences;
import com.google.reviewit.app.ReviewItApp;
import com.google.reviewit.util.FormatUtil;
import com.google.reviewit.util.ObservableAsyncTask;
import com.google.reviewit.util.WidgetUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ChangeBox extends RelativeLayout {
private static final String TAG = ChangeBox.class.getName();
private final WidgetUtil widgetUtil;
public ChangeBox(Context context) {
this(context, null);
}
public ChangeBox(Context context, AttributeSet attrs) {
super(context, attrs);
this.widgetUtil = new WidgetUtil(context);
inflate(context, R.layout.change_box, this);
RelativeLayout.LayoutParams layoutParams =
new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
int activityHorizontalMargin = widgetUtil.getDimension(
R.dimen.activity_horizontal_margin);
int activityVerticalMargin = widgetUtil.getDimension(
R.dimen.activity_vertical_margin);
int reviewitBottomAreaHeight = widgetUtil.getDimension(
R.dimen.reviewit_bottom_area_height);
layoutParams.setMargins(activityHorizontalMargin, activityVerticalMargin,
activityHorizontalMargin, reviewitBottomAreaHeight);
setLayoutParams(layoutParams);
if (getId() < 0) {
setId(R.id.changeBox);
}
GradientDrawable gd = new GradientDrawable();
gd.setColor(widgetUtil.color(R.color.commitMessage));
gd.setCornerRadius(widgetUtil.dpToPx(20));
gd.setStroke(1, widgetUtil.color(R.color.commitMessage4));
WidgetUtil.setBackground(this, gd);
}
public void display(ReviewItApp app, Change change) {
configureInfo(app);
ChangeInfo info = change.info;
((ProjectBranchTopicAgeView)v(R.id.projectBranchTopicAge)).init(change);
((UserView)v(R.id.owner)).init(app, info.owner);
WidgetUtil.setText(v(R.id.subject), info.subject);
WidgetUtil.setText(v(R.id.commitMessage),
FormatUtil.formatMessage(change));
WidgetUtil.setText(v(R.id.patchsets),
FormatUtil.format(change.currentRevision()._number));
setInlineCommentCount(app, change);
Change.Voters codeReviewVoters = change.voters("Code-Review");
WidgetUtil.setText(this, R.id.likes,
FormatUtil.format(codeReviewVoters.likers.size()));
WidgetUtil.setText(this, R.id.dislikes,
FormatUtil.format(codeReviewVoters.dislikers.size()));
Collection<AccountInfo> reviewers = change.reviewers(true);
WidgetUtil.setText(v(R.id.reviewers),
FormatUtil.format(reviewers.size()));
setCommitMessageFont(app);
colorIcons(app, codeReviewVoters, reviewers);
}
private void configureInfo(ReviewItApp app) {
Preferences prefs = app.getPrefs();
WidgetUtil.setVisible(prefs.showPatchSets,
v(R.id.patchsets, R.id.patchSetIcon));
WidgetUtil.setVisible(prefs.showPositiveCodeReviewVotes,
v(R.id.likes, R.id.positiveReviewIcon));
WidgetUtil.setVisible(prefs.showNegativeCodeReviewVotes,
v(R.id.dislikes, R.id.negativeReviewIcon));
WidgetUtil.setVisible(prefs.showComments,
v(R.id.comments, R.id.commentIcon));
WidgetUtil.setVisible(prefs.showReviewers,
v(R.id.reviewers, R.id.reviewerIcon));
}
private void setCommitMessageFont(ReviewItApp app) {
Preferences prefs = app.getPrefs();
if (!prefs.autoFontSizeForCommitMessage()) {
MaxFontSizeTextView commitMessage =
((MaxFontSizeTextView) v(R.id.commitMessage));
commitMessage.setMinTextSize(prefs.commitMessageFontSize);
commitMessage.setMaxTextSize(prefs.commitMessageFontSize);
}
}
/**
* Highlight icons for the current user by a different color.
*/
private void colorIcons(
ReviewItApp app, Change.Voters codeReviewVoters,
Collection<AccountInfo> reviewers) {
colorIcon(R.id.positiveReviewIcon,
containsSelf(app, codeReviewVoters.likers)
? R.color.iconHighlightedGreen
: R.color.icon);
colorIcon(R.id.negativeReviewIcon,
containsSelf(app, codeReviewVoters.dislikers)
? R.color.iconHighlightedRed
: R.color.icon);
colorIcon(R.id.commentIcon, R.color.icon);
colorIcon(R.id.reviewerIcon,
containsSelf(app, reviewers)
? R.color.iconHighlightedGreen
: R.color.icon);
}
private void colorIcon(@IdRes int id, @ColorRes int colorId) {
((ImageView) v(id)).setColorFilter(widgetUtil.color(colorId));
}
private void setInlineCommentCount(final ReviewItApp app, Change change) {
new ObservableAsyncTask<Change, Void, Integer>() {
private TextView comments;
@Override
protected void preExecute() {
super.preExecute();
comments = (TextView) v(R.id.comments);
}
@Override
protected Integer doInBackground(Change... changes) {
Change change = changes[0];
try {
return change.getInlineCommentCount();
} catch (RestApiException e) {
Log.e(TAG, "Failed to count inline comments of change "
+ change.info._number, e);
return null;
}
}
@Override
protected void postExecute(Integer count) {
if (count == null) {
return;
}
comments.setText(FormatUtil.format(count));
if (app.getPrefs().showComments) {
WidgetUtil.setVisible(comments);
}
}
}.executeOnExecutor(app.getExecutor(), change);
}
private boolean containsSelf(
ReviewItApp app, Collection<AccountInfo> accounts) {
AccountInfo self = app.getSelf();
if (self == null) {
return false;
}
for (AccountInfo account : accounts) {
if (self._accountId.equals(account._accountId)) {
return true;
}
}
return false;
}
private View v(@IdRes int id) {
return findViewById(id);
}
private View[] v(@IdRes int id, @IdRes int... moreIds) {
List<View> views = new ArrayList<>(moreIds.length + 1);
views.add(v(id));
for (@IdRes int yaId : moreIds) {
views.add(v(yaId));
}
return views.toArray(new View[views.size()]);
}
}
|
package com.Action;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import com.dao.zzglDao;
public class uploadwdAciton {
public String toList() throws Exception {
String a="";
String b="";
String f="";
String d="";
// SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
//同时支持Excel 2003、2007
File excelFile = new File("c:/5/5.xls"); //创建文件对象
FileInputStream is = new FileInputStream(excelFile); //文件流
Workbook workbook = WorkbookFactory.create(is); //这种方式 Excel 2003/2007/2010 都是可以处理的
int sheetCount = workbook.getNumberOfSheets(); //Sheet的数量
//遍历每个Sheet
for (int s = 0; s < sheetCount; s++) {
Sheet sheet = workbook.getSheetAt(s);
int rowCount = sheet.getPhysicalNumberOfRows(); //获取总行数
//遍历每一行
for (int r = 0; r < rowCount; r++) {
Row row = sheet.getRow(r); /*获取行*/
// int cellCount = row.getPhysicalNumberOfCells(); //获取总列数
Cell cell = row.getCell(0); /*获取列*/
a=cell.getRichStringCellValue().toString();
cell = row.getCell(1); /*获取列*/
b=cell.getRichStringCellValue().toString();
cell = row.getCell(2); /*获取列*/
f=cell.getRichStringCellValue().toString();
cell = row.getCell(3); /*获取列*/
d=cell.getRichStringCellValue().toString();
zzglDao gl=new zzglDao();
gl.tset(a, b, f,d);
//遍历每一列
// for (int c = 0; c < cellCount; c++) {
//
// Cell cell = row.getCell(c); /*获取列*/
// int cellType = cell.getCellType();
// String cellValue = null;
// switch(cellType) {
// case Cell.CELL_TYPE_STRING: //文本
// cellValue = cell.getStringCellValue();
// break;
// case Cell.CELL_TYPE_NUMERIC: //数字、日期
// if(DateUtil.isCellDateFormatted(cell)) {
// cellValue = fmt.format(cell.getDateCellValue()); //日期型
// }
// else {
// cellValue = String.valueOf(cell.getNumericCellValue()); //数字
// }
// break;
// case Cell.CELL_TYPE_BOOLEAN: //布尔型
// cellValue = String.valueOf(cell.getBooleanCellValue());
// break;
// case Cell.CELL_TYPE_BLANK: //空白
// cellValue = cell.getStringCellValue();
// break;
// case Cell.CELL_TYPE_ERROR: //错误
// cellValue = "错误";
// break;
// case Cell.CELL_TYPE_FORMULA: //公式
// cellValue = "错误";
// break;
// default:
// cellValue = "错误";
// }
// System.out.print(cell.getStringCellValue() + " ");
}
// System.out.println();
}
// }
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
package org.vaadin.peter.contextmenu.client;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.Timer;
import com.vaadin.client.ServerConnector;
import com.vaadin.client.communication.RpcProxy;
/**
* ContextMenuItemWidgetHandler is context menu item specific object that
* handles the server communication when item is interacted with.
*
* @author Peter Lehto / Vaadin Ltd
*
*/
public class ContextMenuItemWidgetHandler implements ClickHandler,
MouseOverHandler, MouseOutHandler, KeyUpHandler {
private ContextMenuServerRpc contextMenuRpc;
private final Timer openTimer = new Timer() {
@Override
public void run() {
onItemClicked();
}
};
private ContextMenuItemWidget widget;
public ContextMenuItemWidgetHandler(ContextMenuItemWidget widget,
ServerConnector connector) {
this.widget = widget;
contextMenuRpc = RpcProxy.create(ContextMenuServerRpc.class, connector);
}
@Override
public void onKeyUp(KeyUpEvent event) {
int keycode = event.getNativeEvent().getKeyCode();
if (keycode == KeyCodes.KEY_LEFT) {
onLeftPressed();
} else if (keycode == KeyCodes.KEY_RIGHT) {
onRightPressed();
} else if (keycode == KeyCodes.KEY_UP) {
onUpPressed();
} else if (keycode == KeyCodes.KEY_DOWN) {
onDownPressed();
} else if (keycode == KeyCodes.KEY_ENTER) {
onEnterPressed();
}
}
@Override
public void onMouseOut(MouseOutEvent event) {
openTimer.cancel();
widget.setFocus(false);
}
@Override
public void onMouseOver(MouseOverEvent event) {
openTimer.cancel();
if (isEnabled()) {
if (!widget.isSubmenuOpen()) {
widget.closeSiblingMenus();
}
widget.setFocus(true);
if (widget.hasSubMenu() && !widget.isSubmenuOpen()) {
openTimer.schedule(500);
}
}
}
@Override
public void onClick(ClickEvent event) {
if (isEnabled()) {
openTimer.cancel();
if (widget.hasSubMenu()) {
if (!widget.isSubmenuOpen()) {
widget.onItemClicked();
contextMenuRpc.itemClicked(widget.getId(), false);
}
} else {
boolean menuClosed = widget.onItemClicked();
contextMenuRpc.itemClicked(widget.getId(), menuClosed);
}
}
}
private boolean isEnabled() {
return widget.isEnabled();
}
private void onLeftPressed() {
if (isEnabled()) {
widget.closeThisAndSelectParent();
}
}
private void onRightPressed() {
if (isEnabled()) {
if (widget.hasSubMenu()) {
onItemClicked();
}
}
}
private void onUpPressed() {
if (isEnabled()) {
widget.selectUpperSibling();
}
}
private void onDownPressed() {
if (isEnabled()) {
widget.selectLowerSibling();
}
}
private void onEnterPressed() {
if (isEnabled()) {
if (widget.hasSubMenu()) {
if (!widget.isSubmenuOpen()) {
boolean menuClosed = widget.onItemClicked();
contextMenuRpc.itemClicked(widget.getId(), menuClosed);
}
} else {
boolean menuClosed = widget.onItemClicked();
contextMenuRpc.itemClicked(widget.getId(), menuClosed);
}
}
}
private void onItemClicked() {
boolean menuClosed = widget.onItemClicked();
contextMenuRpc.itemClicked(widget.getId(), menuClosed);
}
}
|
/*
* 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 com.sg.bullsandcows.data;
import com.sg.bullsandcows.models.Game;
import com.sg.bullsandcows.models.Round;
import java.util.List;
/**
*
* @author aeshe
*/
public interface RoundDao {
public Round addRound(Round round, int gameId);
public List<Round> getAllRounds();
public Round getARound(int roundId);
public void updateRound(Round round);
public void deleteRound(int roundId);
}
|
package com.bjit.spring.model;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity(name = "product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "product_id")
private int id;
@Column(name = "product_name", length = 64, nullable = false)
private String productName;
@Column(name = "product_quantity")
private int productQuantity;
@Column(name = "original_price")
private int originalPrice;
@Column(name = "discount_price", columnDefinition = "int default 0")
private int discountPrice;
@Column(name = "product_description", columnDefinition = "text")
private String productDescription;
@Column(name = "product_image", length = 128)
private String productImage;
// @Column(name = "category_id")
// private String categoryId;
@Column(name = "created_on", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private Timestamp createdOn;
@Column(name = "updated_on", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
private Timestamp updatedOn;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
public Product() {
super();
// TODO Auto-generated constructor stub
}
public Product(int id, String productName, int productQuantity, int originalPrice, int discountPrice,
String productDescription, String productImage, Timestamp createdOn, Timestamp updatedOn,
Category category) {
super();
this.id = id;
this.productName = productName;
this.productQuantity = productQuantity;
this.originalPrice = originalPrice;
this.discountPrice = discountPrice;
this.productDescription = productDescription;
this.productImage = productImage;
this.createdOn = createdOn;
this.updatedOn = updatedOn;
this.category = category;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getProductQuantity() {
return productQuantity;
}
public void setProductQuantity(int productQuantity) {
this.productQuantity = productQuantity;
}
public int getOriginalPrice() {
return originalPrice;
}
public void setOriginalPrice(int originalPrice) {
this.originalPrice = originalPrice;
}
public int getDiscountPrice() {
return discountPrice;
}
public void setDiscountPrice(int discountPrice) {
this.discountPrice = discountPrice;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
public Timestamp getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Timestamp updatedOn) {
this.updatedOn = updatedOn;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@Override
public String toString() {
return "Product [id=" + id + ", productName=" + productName + ", productQuantity=" + productQuantity
+ ", originalPrice=" + originalPrice + ", discountPrice=" + discountPrice + ", productDescription="
+ productDescription + ", productImage=" + productImage + ", createdOn=" + createdOn + ", updatedOn="
+ updatedOn + ", category=" + category.getCategoryName() + "]";
}
}
|
package com.bakerystudios.game.questions;
import java.util.List;
public class Question {
private String text;
private List<Answer> answers;
private int correctIndex;
public Question(String text, List<Answer> answers, int correctIndex) {
this.text = text;
this.answers = answers;
this.setCorrectIndex(correctIndex);
}
public String getText() {return text;}
public void setText(String text) {this.text = text;}
public List<Answer> getAnswers() {return answers;}
public void setAnswers(List<Answer> answers) {this.answers = answers;}
public int getCorrectIndex() {
return correctIndex;
}
public void setCorrectIndex(int correctIndex) {
this.correctIndex = correctIndex;
}
}
|
package org.uva.forcepushql.parser.ast.elements.expressionnodes;
import org.uva.forcepushql.parser.ast.visitors.ASTExpressionVisitor;
import org.uva.forcepushql.parser.ast.visitors.ASTVisitor;
import org.uva.forcepushql.parser.ast.elements.ExpressionNode;
public class DecimalNode extends ExpressionNode
{
private double value;
public DecimalNode() {
super(false);
}
public void setValue(double value)
{
this.value = value;
}
public double getValue()
{
return this.value;
}
@Override
public String accept(ASTVisitor visitor)
{
return visitor.visit(this);
}
@Override
public Double accept(ASTExpressionVisitor visitor)
{
return visitor.visit(this);
}
}
|
package com.cisc181.core;
import java.util.UUID;
public class Enrollment {
private int SectionID;
private UUID StudentID;
private UUID EnrollmentID;
private double grade;
public Enrollment(int SectionID, UUID StudentID, double grade){
this.SectionID = SectionID;
this.StudentID = StudentID;
this.grade = grade;
}
public int getSectionID(){
return this.SectionID;
}
public UUID getStudentID(){
return this.StudentID;
}
public void setSectionID (int SectionID)
{
this.SectionID = SectionID;
}
public void setStudentID (UUID StudentID)
{
this.StudentID = StudentID;
}
public void setGrade(double grade)
{
this.grade = grade;
}
public void setEnrollmentID(UUID EnrollmentID){
this.EnrollmentID = EnrollmentID;
}
private Enrollment(){
}
public Enrollment(UUID SectionID, UUID StudentID){
this();
setEnrollmentID(EnrollmentID);
}
}
|
package exchange_match_engine;
import java.util.ArrayList;
public class Create extends Request {
ArrayList<RequestElement> requestElements;
public Create() {
super(Type.CREATE);
this.requestElements = new ArrayList<>();
}
}
|
package ir.ac.kntu.objects;
import java.io.Serializable;
public class OrangeWall extends MyObjects implements Serializable {
public OrangeWall(double x, double y, double width, double length){
super(x, y, width, length, true, "./src/main/java/resources/map/wall1.jpg");
}
}
|
package cal;
import java.util.Stack;
/**
* 表达式计算
* 中缀表达式转换为后缀表达式,进行表达式运算
*/
public class Postfix {
public static void main(String[] args) {
String s1 = "3*(3+2)+3*7*2*(2+1)";
//String s2 = "14+5*32*12+*+";
StringBuilder s2 = ch(s1);
System.out.println(s2);
String reg = "[0-9]";
/**
* 扫面接收的字符串,数字直接入栈,遇到运算符,弹出前两个数字进行运算,并将结果压入栈
*
*/
Stack<Integer> s = new Stack<>();//创建一个栈用来保存数字
for (int i = 0;i<s2.length();i++){
String a = String.valueOf(s2.charAt(i));//扫描接收到的后缀表达式
if (a.matches(reg)){
s.push(Integer.valueOf(a));//如果扫描到的元素是数字直接压入栈中
}else if (a.equals("+")){//如果是运算符则弹出栈顶俩个元素进行相应的运算再将结果压入栈中
int v = s.pop()+s.pop();
s.push(v);
}else if (a.equals("-")){
int v = s.pop() - s.pop();
s.push(v);
}else if (a.equals("*")){
int v = s.pop() * s.pop();
s.push(v);
}else if (a.equals("/")){
int v = s.pop()/s.pop();
s.push(v);
}
}
//最后获得栈顶元素即为结果
int r = s.peek();
System.out.println(r);
}
/**
* 接收一个中缀表达式字符串转换为后缀表达式字符串并返回
* @param str
* @return
*/
public static StringBuilder ch(String str){
// Stack<String> s = new Stack();//s:用来保存输出的后缀表达式的栈
StringBuilder stb = new StringBuilder();//输出字符串
Stack<String> s1 = new Stack();//用来储存运算符的栈
s1.push("#");//将运算符栈先压入“#”,防止之后在在弹出的时候调用peek()会报空栈异常
for(int i = 0;i<str.length();i++) {
String a = String.valueOf(str.charAt(i));//扫描表达式每一个字符并转换为字符串类型
if (a.equals("+") || a.equals("-") || a.equals("*") || a.equals("/")) {//判断是否是运算符
if (s1.peek().equals("#")){//如果栈内没有其他运算符,直接压入栈
s1.push(a);
}else if (s1.peek().equals("*")||s1.peek().equals("/")){
/*
如果栈顶运算符为“×”或者“/”,那么弹出运算符直到一个优先级低于本次扫描到的元素
或者栈内没有其他运算符,或者遇到一个作括号,并将弹出的元素依次保存到输出栈内
*/
while (!s1.peek().equals("#")){
if (s1.peek().equals("(")){
break;
}
if (a.equals("+")||a.equals("-")){
String s3 = s1.pop();//s3表示从s1弹出的运算符
//s.push(s3);
stb.append(s3);
}else{
if(s1.peek().equals("+")||s1.equals("-")){
break;
}
String s3 = s1.pop();
//s.push(s3);
stb.append(s3);
}
}
s1.push(a);//将本次扫描到的运算符压入栈
}else if (s1.peek().equals("+")||s1.peek().equals("-")){
if (a.equals("+")||a.equals("-")){
while (!s1.equals("#")){
if (s1.peek().equals("(")){
break;
}
String s3 = s1.pop();
//s.push(s3);
stb.append(s3);
}
s1.push(a);
}else {
s1.push(a);
}
}else{
s1.push(a);
}
}else if (a.equals("(")){
/*
如果扫描到左括号,直接入运算符栈
*/
s1.push(a);
}else if (a.equals(")")){
/*
如果扫描到右括号那么弹出运算符保存到输出栈直到遇到的第一个左括号
*/
while(!s1.peek().equals("(")){
String s2 = s1.pop();
//s.push(s2);
stb.append(s2);
}
s1.pop();
}else{
//s.push(a);
stb.append(a);
}
}
/*
将运算符栈内其他运算符依次弹出压入输出栈内
*/
while (!s1.peek().equals("#")){
String f = s1.pop();
//s.push(f);
stb.append(f);
}
/*
遍历输出栈,拼接成字符串并返回
*/
/*String s5 = "";
for (String s4:s){
s5 += s4;
}*/
return stb;
}
}
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.test.headlessui;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import pl.edu.icm.unity.server.JettyServer;
/**
* This is a base class for Selenium WebDriver based headless Web UI testing.
* <p>
* Provides: startup of the test server, setup of a web driver and its cleanup.
* What's more utility methods are provided so Selenium programming is more concise.
*
* @author K. Benedyczak
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:META-INF/components.xml", "classpath:META-INF/test-selenium.xml"})
@ActiveProfiles("test")
public class SeleniumTestBase
{
protected String baseUrl = "https://localhost:2443";
public static final int WAIT_TIME_S = Integer.parseInt(
System.getProperty("unity.selenium.wait", "30"));
public static final int SLEEP_TIME_MS = 250;
public static final int SIMPLE_WAIT_TIME_MS = Integer.parseInt(
System.getProperty("unity.selenium.delay", "2000"));
protected WebDriver driver;
private StringBuffer verificationErrors = new StringBuffer();
@Autowired
protected JettyServer httpServer;
@Before
public void setUp() throws Exception
{
httpServer.start();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(WAIT_TIME_S, TimeUnit.SECONDS);
}
@After
public void tearDown() throws Exception
{
driver.manage().deleteAllCookies();
httpServer.stop();
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString))
{
Assert.fail(verificationErrorString);
}
}
protected WebElement waitForElement(By by)
{
for (int i = 0;; i++)
{
if (i >= WAIT_TIME_S*1000/SLEEP_TIME_MS)
Assert.fail("timeout");
try
{
WebElement elementPresent = isElementPresent(by);
if (elementPresent != null)
return elementPresent;
Thread.sleep(SLEEP_TIME_MS);
} catch (InterruptedException e)
{
//OK
}
}
}
protected WebElement isElementPresent(By by)
{
try
{
WebElement ret = driver.findElement(by);
if (ret == null || !ret.isDisplayed())
return null;
return ret;
} catch (NoSuchElementException e)
{
return null;
}
}
protected void simpleWait()
{
try
{
Thread.sleep(SIMPLE_WAIT_TIME_MS);
} catch (InterruptedException e)
{
//OK
}
}
}
|
package com.codingchili.logging.configuration;
import com.codingchili.common.Strings;
import com.codingchili.core.configuration.ServiceConfigurable;
import com.codingchili.core.files.Configurations;
import com.codingchili.core.protocol.Serializer;
import com.codingchili.core.storage.JsonMap;
import io.vertx.core.json.JsonObject;
/**
* @author Robin Duda
* Contains settings for the logserver.
*/
public class LogServerSettings extends ServiceConfigurable {
static final String PATH_LOGSERVER = Strings.getService("logging");
private byte[] loggingSecret;
private byte[] clientSecret;
private Boolean console = true;
private Boolean storage = false;
private String db = "logging";
private String collection = "events";
private String plugin = JsonMap.class.getCanonicalName();
private JsonObject elastic;
public LogServerSettings() {
this.path = PATH_LOGSERVER;
}
public static LogServerSettings get() {
return Configurations.get(PATH_LOGSERVER, LogServerSettings.class);
}
/**
* @return true if received messages are to be printed to console.
*/
public Boolean getConsole() {
return console;
}
/**
* @param console indicates whether received messages are printed to console.
*/
public void setConsole(Boolean console) {
this.console = console;
}
/**
* @return the secret key for logging tokens.
*/
public byte[] getLoggingSecret() {
return loggingSecret;
}
/**
* @param secret sets the secret key for logging tokens.
*/
public void setLoggingSecret(byte[] secret) {
this.loggingSecret = secret;
}
/**
* @return the secret used to verify client tokens.
*/
public byte[] getClientSecret() {
return clientSecret;
}
/**
* @param clientSecret the secret used to verify client tokens.
*/
public void setClientSecret(byte[] clientSecret) {
this.clientSecret = clientSecret;
}
/**
* @return the database that logs are stored in.
*/
public String getDb() {
return db;
}
/**
* @param db sets the database that logs are stored in.
*/
public void setDb(String db) {
this.db = db;
}
/**
* @return the handler of the collection that messages are stored in.
*/
public String getCollection() {
return collection;
}
/**
* @param collection sets the handler of the collection where messages are stored.
*/
public void setCollection(String collection) {
this.collection = collection;
}
/**
* @return the plugin to use for storing received log messages.
*/
public String getPlugin() {
return plugin;
}
/**
* @param plugin sets the plugin to use for storing received log messages.
*/
public void setPlugin(String plugin) {
this.plugin = plugin;
}
/**
* @return elasticsearch mapping and index settings.
*/
public JsonObject getElastic() {
return elastic;
}
/**
* @param elastic contains elasticsearch 'mapping' and/or 'index' settings.
*/
public void setElastic(Object elastic) {
this.elastic = Serializer.json(elastic);
}
/**
* @return true if plugin-based storage should be used.
*/
public Boolean getStorage() {
return storage;
}
/**
* @param storage true if plugin-based storage should be used.
* @return fluent
*/
public LogServerSettings setStorage(Boolean storage) {
this.storage = storage;
return this;
}
} |
package com.taim.content.controller.vendor;
import com.taim.backendservice.client.vendor.VendorClient;
import com.taim.content.mapper.VendorOverviewMapper;
import com.taim.content.model.VendorOverviewView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import java.util.stream.Collectors;
@Controller
public class VendorResourceController {
private final VendorClient vendorClient;
private final VendorOverviewMapper vendorOverviewMapper;
@Autowired
public VendorResourceController(VendorClient vendorClient, VendorOverviewMapper vendorOverviewMapper) {
this.vendorClient = vendorClient;
this.vendorOverviewMapper = vendorOverviewMapper;
}
@ModelAttribute("vendorlist")
public List<VendorOverviewView> getVendorList() {
List<VendorOverviewView> vendorOverviewViews = this.vendorClient.getAllVendors().stream()
.map(vendorOverviewMapper::map)
.collect(Collectors.toList());
return vendorOverviewViews;
}
@RequestMapping(
method = RequestMethod.GET,
value = "/vendors"
)
public ModelAndView getVendorOverview() {
ModelAndView modelAndView = new ModelAndView("overview/vendor-overview");
return modelAndView;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.