text stringlengths 10 2.72M |
|---|
package nesto.base.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.concurrent.TimeUnit;
/**
* Created on 2016/7/8.
* By nesto
*/
public class LineView extends View {
private Paint paint;
private int position;
private boolean run = true;
private Thread thread;
public LineView(Context context) {
this(context, null);
}
public LineView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setAntiAlias(true);
position = 0;
}
private Handler handler = new Handler(msg -> {
start();
return true;
});
public void startAnim() {
thread = new Thread(() -> {
while (run) {
try {
TimeUnit.MILLISECONDS.sleep(10);
handler.obtainMessage().sendToTarget();
} catch (InterruptedException e) {
break;
}
}
});
run = true;
thread.start();
}
public void stopAnim() {
run = false;
if (thread != null) {
thread.interrupt();
}
}
private void start() {
position += 1;
invalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.rgb(getColor(position / 2), getColor(position / 3), getColor(position / 4)));
for (int i = 1; i < 6; i++) {
int pos = (position / 2 * i) % getHeight();
canvas.drawLine(0, getHeight() - pos,
getWidth() - pos, getHeight(), paint);
canvas.drawLine(0, getHeight() - pos,
pos, 0, paint);
canvas.drawLine(getWidth() - pos, getHeight(),
getWidth(), pos, paint);
canvas.drawLine(getWidth(), pos,
pos, 0, paint);
canvas.drawLine(getWidth() - pos, 0,
getWidth(), getHeight() - pos, paint);
canvas.drawLine(getWidth() - pos, 0,
0, pos, paint);
canvas.drawLine(getWidth(), getHeight() - pos,
pos, getHeight(), paint);
canvas.drawLine(pos, getHeight(),
0, pos, paint);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, pos / 2, paint);
}
}
private int getColor(int position) {
return Math.abs(position % 511 - 255);
}
}
|
package rl4j;
import java.util.Map;
public interface CollaborativeFilter {
public Map<String, String[]> generateRecommendations(LabeledMatrix testExamples, int numNeighbors,
int numRecommendations);
public TopNList recommendationsAsTopNList(LabeledMatrix testExamples, int numNeighbors, int numRecommendations);
}
|
package com.mcl.mancala.service;
import com.mcl.mancala.beans.GameState;
import com.mcl.mancala.beans.Mancala;
import com.mcl.mancala.beans.PlayerMove;
import com.mcl.mancala.game.Mechanics;
import com.mcl.mancala.repository.MancalaRepository;
import com.mcl.mancala.repository.PlayerStateRepository;
import com.mcl.mancala.repository.entity.MancalaEntity;
import com.mcl.mancala.repository.entity.PlayerState;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class SameScreenWithPersistenceServiceTest {
@Mock
MancalaRepository mancalaRepository;
@Mock
PlayerStateRepository playerStateRepository;
@InjectMocks
private SameScreenWithPersistenceService sameScreenWithPersistenceService;
private Mechanics gameMechanics;
@Before
public void setup() {
gameMechanics = new Mechanics(new Mechanics().start(), false);
PlayerState player1 = new PlayerState(gameMechanics.getMancala().getPlayer1());
player1.setId(1L);
PlayerState player2 = new PlayerState(gameMechanics.getMancala().getPlayer2());
player2.setId(2L);
MancalaEntity mancalaEntity = new MancalaEntity(player1, player2);
mancalaEntity.setId(3L);
when(mancalaRepository.save(any(MancalaEntity.class))).thenReturn(mancalaEntity);
when(mancalaRepository.findById(eq(3L))).thenReturn(Optional.of(mancalaEntity));
}
@Test
public void newGame() {
GameState resultingGameState = new GameState(3L, gameMechanics.getMancala(), gameMechanics.isGameOver(), gameMechanics.whichPlayerWon());
assertEquals(resultingGameState, sameScreenWithPersistenceService.continueGame(-1));
verify(mancalaRepository, never()).findById(3L);
verify(playerStateRepository, never()).findById(1L);
verify(playerStateRepository, never()).findById(2L);
verify(mancalaRepository, atLeastOnce()).save(any(MancalaEntity.class));
verify(playerStateRepository, atLeast(2)).save(any(PlayerState.class));
}
@Test
public void continueExistingGame() {
GameState resultingGameState = new GameState(3L, gameMechanics.getMancala(), gameMechanics.isGameOver(), gameMechanics.whichPlayerWon());
assertEquals(resultingGameState, sameScreenWithPersistenceService.continueGame(3L));
verify(mancalaRepository, atLeastOnce()).findById(3L);
verify(playerStateRepository, never()).findById(1L);
verify(playerStateRepository, never()).findById(2L);
verify(mancalaRepository, never()).save(any(MancalaEntity.class));
verify(playerStateRepository, never()).save(any(PlayerState.class));
}
@Test
public void makeMove() {
PlayerMove playerMove = new PlayerMove(new Mechanics().start(), 1, 5);
gameMechanics.playerMove(1, 5);
GameState resultingGameState = new GameState(3L, gameMechanics.getMancala(), gameMechanics.isGameOver(), gameMechanics.whichPlayerWon());
PlayerState player1 = new PlayerState(gameMechanics.getMancala().getPlayer1());
player1.setId(1L);
PlayerState player2 = new PlayerState(gameMechanics.getMancala().getPlayer2());
player2.setId(2L);
MancalaEntity mancalaEntity = new MancalaEntity(player1, player2);
mancalaEntity.setId(3L);
when(mancalaRepository.save(any(MancalaEntity.class))).thenReturn(mancalaEntity);
when(playerStateRepository.save(any(PlayerState.class))).thenReturn(player1, player2);
assertEquals(resultingGameState, sameScreenWithPersistenceService.makeMove(playerMove, 3L));
ArgumentCaptor<MancalaEntity> mancalaEntityArgumentCaptor = ArgumentCaptor.forClass(MancalaEntity.class);
verify(mancalaRepository, times(1)).save(mancalaEntityArgumentCaptor.capture());
assertEquals(mancalaEntity, mancalaEntityArgumentCaptor.getValue());
ArgumentCaptor<PlayerState> playerStateArgumentCaptor = ArgumentCaptor.forClass(PlayerState.class);
verify(playerStateRepository, times(2)).save(playerStateArgumentCaptor.capture());
assertEquals(player1, playerStateArgumentCaptor.getAllValues().get(0));
assertEquals(player2, playerStateArgumentCaptor.getAllValues().get(1));
}
}
|
package com.example.c0753560_mad3125_midterm;
import android.content.Context;
import com.example.c0753560_mad3125_midterm.JavaClasses.FlightMain;
import com.example.c0753560_mad3125_midterm.JavaClasses.LaunchSite;
import com.example.c0753560_mad3125_midterm.JavaClasses.Links;
import com.example.c0753560_mad3125_midterm.JavaClasses.Rocket;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.io.IOException;
public class FlightData
{
Context context;
public ArrayList<FlightMain> mFlightList ;
public ArrayList<FlightMain> getmSpaceXFlightList() {
return mFlightList;
}
public FlightData(Context context)
{
this.context = context;
}
public String loadJSONFromAsset() {
String json;
try {
InputStream is = context.getAssets().open("Flight.json");
int size = is.available();
byte[] buffer = new byte[size];
int count = is.read(buffer);
is.close();
//Log.d("-- COUNT --", String.format("%d Bytes",count));
json = new String(buffer, "UTF8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
public void processJSON()
{
String jsonString = this.loadJSONFromAsset();
if (jsonString != null)
{
try {
JSONArray mJSONArray = new JSONArray(jsonString);
mFlightList = new ArrayList<FlightMain>();
for (int i = 0; i < mJSONArray.length(); i++) {
FlightMain mFlight = getFlightObjectFromJSON(mJSONArray.getJSONObject(i));
mFlightList.add(mFlight);
//Log.d("-- JSON -- ", mSpaceXFlight.toString());
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}
}
public FlightMain getFlightObjectFromJSON(JSONObject userJsonObject) throws JSONException
{
String flight_number = userJsonObject.getString("flight_number");
String mission_name = userJsonObject.getString("mission_name");
String upcoming = userJsonObject.getString("upcoming");
String launch_year = userJsonObject.getString("launch_year");
String launch_window = userJsonObject.getString("launch_window");
String details = userJsonObject.getString("details");
//Read Rocket
JSONObject rocket = new JSONObject(userJsonObject.getJSONObject("rocket").toString());
String rocket_id = rocket.getString("rocket_id");
String rocket_name = rocket.getString("rocket_name");
String rocket_type = rocket.getString("rocket_type");
//Read Launch Site
JSONObject launchSite = new JSONObject(userJsonObject.getJSONObject("launch_site").toString());
String site_id = launchSite.getString("site_id");
String site_name = launchSite.getString("site_name");
String site_name_long = launchSite.getString("site_name_long");
//Read Links
JSONObject links = new JSONObject(userJsonObject.getJSONObject("links").toString());
String mission_patch = links.getString("mission_patch");
String mission_patch_small = links.getString("mission_patch_small");
String article_link = links.getString("article_link");
String wikipedia = links.getString("wikipedia");
String video_link = links.getString("video_link");
//start creating User object
FlightMain mFlightMain = new FlightMain();
mFlightMain.setFilghtNumber(flight_number);
mFlightMain.setMissionName(mission_name);
mFlightMain.setUpcoming(upcoming);
mFlightMain.setLaunchYear(launch_year);
mFlightMain.setLaunchWindow(launch_window);
mFlightMain.setDetails(details);
Rocket mRocket = new Rocket();
mRocket.setRocketId(rocket_id);
mRocket.setRocketName(rocket_name);
mRocket.setRocketType(rocket_type);
mFlightMain.setRocket(mRocket);
LaunchSite mLaunchSite = new LaunchSite();
mLaunchSite.setSiteID(site_id);
mLaunchSite.setSiteName(site_name);
mLaunchSite.setSiteNameLong(site_name_long);
mFlightMain.setLaunchSite(mLaunchSite);
Links mLinks = new Links();
mLinks.setMissionPatchSmall(mission_patch_small);
mLinks.setArticleLink(article_link);
mLinks.setWikipedia(wikipedia);
mLinks.setVideoLink(video_link);
mFlightMain.setLinks(mLinks);
return mFlightMain;
}
}
|
package Problem_1758;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
PriorityQueue<Integer> pq = new PriorityQueue<>((o1, o2)-> { return o2-o1; });
// input
for(int i = 0; i<N; i++) pq.add(Integer.parseInt(br.readLine()));
long answer = 0;
long temp = 0;
for(int i = 1; !pq.isEmpty(); i++) {
temp = pq.poll() - (i-1);
answer += temp > 0 ? temp : 0;
}
System.out.println(answer);
}
}
|
package com.comp3617.finalproject.data.search;
import java.io.Serializable;
/**
* Created by calmdynamic on 11/20/2017.
*/
public class FoodSearchData implements Serializable{
private String foodGroup;
private String foodName;
private String foodNDBNO;
public FoodSearchData(String foodGroup, String foodName, String foodNDBNO) {
this.foodGroup = foodGroup;
this.foodName = foodName;
this.foodNDBNO = foodNDBNO;
}
public String getFoodGroup() {
return foodGroup;
}
public void setFoodGroup(String foodGroup) {
this.foodGroup = foodGroup;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public String getFoodNDBNO() {
return foodNDBNO;
}
public void setFoodNDBNO(String foodNDBNO) {
this.foodNDBNO = foodNDBNO;
}
@Override
public String toString() {
return "FoodSearchData{" +
"foodGroup='" + foodGroup + '\'' +
", foodName='" + foodName + '\'' +
", foodNDBNO='" + foodNDBNO + '\'' +
'}';
}
}
|
package uk.co.mtford.jalp.abduction.rules;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uk.co.mtford.jalp.JALP;
import uk.co.mtford.jalp.abduction.logic.instance.DenialInstance;
import uk.co.mtford.jalp.abduction.logic.instance.IInferableInstance;
import uk.co.mtford.jalp.abduction.logic.instance.NegationInstance;
import uk.co.mtford.jalp.abduction.logic.instance.PredicateInstance;
import uk.co.mtford.jalp.abduction.logic.instance.term.VariableInstance;
import uk.co.mtford.jalp.abduction.parse.query.JALPQueryParser;
import uk.co.mtford.jalp.abduction.tools.UniqueIdGenerator;
import java.util.LinkedList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: mtford
* Date: 07/06/2012
* Time: 17:20
* To change this template use File | Settings | File Templates.
*/
public class N2Test {
public N2Test() {
}
@Before
public void noSetup() {
}
@After
public void noTearDown() {
}
@Test
public void test1() throws Exception {
UniqueIdGenerator.reset();
N2RuleNode ruleNode = new N2RuleNode();
LinkedList<IInferableInstance> goals = new LinkedList<IInferableInstance>();
VariableInstance X = new VariableInstance("X");
VariableInstance Y = new VariableInstance("Y");
VariableInstance Z = new VariableInstance("Z");
PredicateInstance p = new PredicateInstance("P",X,Y,Z);
NegationInstance n = new NegationInstance(p);
goals.add(n);
DenialInstance d = new DenialInstance(goals);
ruleNode.getGoals().add(d);
JALP.applyRule(ruleNode);
JALP.getVisualizer("debug/rules/N2/Test1",ruleNode);
}
}
|
package ALIXAR.U5_HERENCIA.T2.A3;
public interface Figura {
public int getArea();
}
|
package com.leador.toggleview.ui;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by xuwei on 2016/11/27.
* 自定义控件编写
*
* android界面绘制流程:
*
* 测量 摆放 绘制
* measure --> layout --> draw
* | | |
* onMeasure-> onLaout-> onDraw 重写这些方法,实现自定义控件
* 注意:对于没有子控件的view,则不用重写onLayout()方法,即继承View的自定义控件。
* 继承ViewGroup的控件有子控件,则需要重写onLayout()方法
*
* View:
* onMeasure()在这个方法中绘制自己的宽高 --> onDraw() 绘制自己的内容
*
* ViewGroup:
* onMeasure()在这个方法中绘制自己的宽高和子view的宽高 -->onLayout()摆放所有子view --> onDraw() 绘制自己的内容
*
* 控件如果放置在activity或fragment中,以上三个方法都是执行完onResume()方法之后执行
*/
public class ToggleView extends View {
private Bitmap slideBtnBitmap;
private Bitmap switchBgBitmap;
private boolean isOpen = false; //默认关闭状态
private float currentX;
private OnStateChangeListener onStateChangeListener;
private boolean state;
//用于代码创建控件
public ToggleView(Context context) {
super(context);
}
//用于在xml中使用,可指定自定义属性
public ToggleView(Context context, AttributeSet attrs) {
super(context, attrs);
//获取配置的自定义属性
String nameSpace = "http://schemas.android.com/apk/res/com.leador.toggleview"; //命名空间
int switchBgResource = attrs.getAttributeResourceValue(nameSpace,"switch_background",-1);
int slideBtnResource = attrs.getAttributeResourceValue(nameSpace,"slide_button",-1);
boolean state = attrs.getAttributeBooleanValue(nameSpace,"state",false);
setSwitchBackgroundResource(switchBgResource);
setSlideButtonResource(slideBtnResource);
setSwitchState(state);
}
//用于在xml中使用,可指定自定义属性,如果定义了样式,走此构造函数
public ToggleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* 绘制控件的宽高
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(switchBgBitmap.getWidth(),switchBgBitmap.getHeight());
}
/**
* 绘制内容
* @param canvas:画布:显示绘制的内容
*/
@Override
protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
//1.绘制背景
Paint paint = new Paint();
canvas.drawBitmap(switchBgBitmap,0,0,paint);
//2.绘制滑块
if(isTouchMode) { //触摸状态时根据当前用户触摸到的位置画滑块
float maxLeft = switchBgBitmap.getWidth() - slideBtnBitmap.getWidth();
//让滑块向左移动自身一半大小位置
float newLeft = currentX - slideBtnBitmap.getWidth()/2.0f;
//限定滑块范围
if(newLeft<0) { // 左边范围
newLeft = 0;
}else if(newLeft>maxLeft) {
newLeft = maxLeft; // 右边范围
}
canvas.drawBitmap(slideBtnBitmap,newLeft,0,paint);
}else { // 根据开关状态直接绘制图片位置
if(isOpen) {
canvas.drawBitmap(slideBtnBitmap,switchBgBitmap.getWidth()-slideBtnBitmap.getWidth(),0,paint);
}else {
canvas.drawBitmap(slideBtnBitmap,0,0,paint);
}
}
}
boolean isTouchMode = false; //默认不是触摸状态
/**
* 重写触摸事件,响应用户的触摸
* @param event
* @return
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isTouchMode = true;
currentX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
currentX = event.getX();
break;
case MotionEvent.ACTION_UP:
isTouchMode = false;
currentX = event.getX();
float center = switchBgBitmap.getWidth()/2.0f;
//根据当前滑动位置和控件中心位置判断开关状态
state = currentX > center;
if(state != isOpen && onStateChangeListener != null) { //如果开关状态变化则调用监听方法
onStateChangeListener.onStateChange(state);
}
isOpen = state;
break;
}
invalidate(); //会引发onDraw方法重新调用,里面的变量重新生效,界面会刷新
return true; // 返回true:消费了用户的触摸事件,才可以收到到其他的事件
}
/**
* 设置图片切换开关状态:true为开
* @param isOpen
*/
public void setSwitchState(boolean isOpen) {
this.isOpen = isOpen;
}
/**
* 设置滑块图片
* @param slide_button
*/
public void setSlideButtonResource(int slide_button) {
slideBtnBitmap = BitmapFactory.decodeResource(getResources(),slide_button);
}
/**
* 设置背景图片
* @param switch_background
*/
public void setSwitchBackgroundResource(int switch_background) {
switchBgBitmap = BitmapFactory.decodeResource(getResources(),switch_background);
}
public void setOnStateChangeListener(OnStateChangeListener onStateChangeListener) {
this.onStateChangeListener = onStateChangeListener;
}
public interface OnStateChangeListener {
void onStateChange(boolean isOpen); //接口回调,将当前状态传递出去
}
}
|
package controllers.chorbi;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import services.ChorbiService;
import services.EventService;
import controllers.AbstractController;
import domain.Chorbi;
import domain.Event;
@Controller
@RequestMapping("/event/chorbi")
public class EventChorbiController extends AbstractController {
// Services ---------------------------------------------------------------
@Autowired
private EventService eventService;
@Autowired
private ChorbiService chorbiService;
// Constructors -----------------------------------------------------------
public EventChorbiController() {
super();
}
// ListingByChorbi --------------------------------------------------------
@RequestMapping(value = "/listByChorbi", method = RequestMethod.GET)
public ModelAndView listByChorbi() {
ModelAndView result;
Collection<Event> events;
Chorbi chorbi;
chorbi = this.chorbiService.findByPrincipal();
events = this.eventService.findByChorbiId(chorbi.getId());
result = new ModelAndView("event/list");
result.addObject("requestURI", "event/listByChorbi.do");
result.addObject("events", events);
return result;
}
// Register ---------------------------------------------------------------
@RequestMapping(value = "/register", method = RequestMethod.POST, params = "register")
public ModelAndView register(@RequestParam final int eventId) {
ModelAndView result;
Event event;
event = this.eventService.findOne(eventId);
this.eventService.register(event);
result = new ModelAndView("redirect:../list.do");
return result;
}
// Unregister -------------------------------------------------------------
@RequestMapping(value = "/unregister", method = RequestMethod.POST, params = "unregister")
public ModelAndView unregister(@RequestParam final int eventId) {
ModelAndView result;
Event event;
event = this.eventService.findOne(eventId);
this.eventService.unregister(event);
result = new ModelAndView("redirect:../list.do");
return result;
}
}
|
package com.ctg.itrdc.janus.rpc.cluster;
import com.ctg.itrdc.janus.common.URL;
import com.ctg.itrdc.janus.common.extension.SPI;
import java.util.List;
/**
* 规则转换器
*
* @author Administrator
*/
@SPI
public interface RuleConverter {
List<URL> convert(URL subscribeUrl, Object source);
}
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TheaterJToggle {
private int rows = 10;
private int columns = 10;
private Icon res = (UIManager.getIcon("OptionPane.errorIcon"));
public TheaterJToggle() {
JPanel panel = new JPanel(new GridLayout(columns, rows));
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
String mlb = "<html>" + "Vacant:" + "<br>" + "Row " + row +" Seat " + column
+ "</html>";
final JToggleButton button = new JToggleButton(mlb);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
if (selected) {
button.setText("Book");
} else {
button.setText("Unbook");
}
}
});
panel.add(button);
}
}
final JFrame frame = new JFrame("JToggleButton Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
TheaterJToggle theaterJToggle = new TheaterJToggle();
}
});
}
} |
package com.t.core.remote;
/**
* @author tb
* @date 2018/12/18 16:47
*/
public interface ChannelEventListener {
void onChannelConnect(final String remoteAddr, final Channel channel);
void onChannelClose(final String remoteAddr, final Channel channel);
void onChannelException(final String remoteAddr, final Channel channel);
void onChannelIdle(IdleState idleState, final String remoteAddr, final Channel channel);
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.vebo.dados.dto;
import br.com.vebo.dados.mapeamento.Perfume;
import java.io.Serializable;
/**
*
* @author mohfus
*/
public class PrecoDTO implements Serializable{
private String nomeCalculo;
private Perfume perfume;
private Double custo;
private Double valorRevendedor;
private Double valorFinal;
private Double lucroRevendedor;
public Double getCusto() {
return custo;
}
public void setCusto(Double custo) {
this.custo = custo;
}
public String getNomeCalculo() {
return nomeCalculo;
}
public void setNomeCalculo(String nomeCalculo) {
this.nomeCalculo = nomeCalculo;
}
public Perfume getPerfume() {
return perfume;
}
public void setPerfume(Perfume perfume) {
this.perfume = perfume;
}
public Double getLucroRevendedor() {
return lucroRevendedor;
}
public void setLucroRevendedor(Double lucroRevendedor) {
this.lucroRevendedor = lucroRevendedor;
}
public Double getValorFinal() {
return valorFinal;
}
public void setValorFinal(Double valorFinal) {
this.valorFinal = valorFinal;
}
public Double getValorRevendedor() {
return valorRevendedor;
}
public void setValorRevendedor(Double valorRevendedor) {
this.valorRevendedor = valorRevendedor;
}
}
|
package com.cht.training;
import java.util.Arrays;
import java.util.Comparator;
class TotalComparator implements Comparator<Asset2> {
@Override
public int compare(Asset2 o1, Asset2 o2) {
return o1.getTotal() - o2.getTotal();
}
}
class Asset2 {
private String name;
private int twd;
private int usd;
private static final int RATE = 31;
public Asset2(String name, int twd, int usd){
this.name = name;
this.twd = twd;
this.usd = usd;
}
@Override
public String toString() {
return String.format("[%s]TWD==>%d, USD==>%d, ==> total==>%d",
name, twd, usd, twd + usd * RATE);
}
public int getTotal(){
return twd + usd * RATE;
}
}
public class Main64 {
public static void main(String[] args) {
Asset2 [] customers = {new Asset2("Mark", 0, 100), new Asset2("John", 100, 0),
new Asset2("Tim", 50, 50), new Asset2("Ken", 75,25)};
System.out.println("original:" + Arrays.toString(customers));
Arrays.sort(customers, new TotalComparator());
System.out.println("after sort:" + Arrays.toString(customers));
}
}
|
package com.zjf.myself.codebase.activity.ExerciseLibrary;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.zjf.myself.codebase.R;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
/**
* Created by Administrator on 2016/12/21.
*/
public class DataStorageAct extends Activity {
private EditText edtDataStorage;
private Button btnSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.win_data_storage);
edtDataStorage = (EditText) findViewById(R.id.edtDataStorage);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String inputText = edtDataStorage.getText().toString();
save(inputText);
}
});
}
// @Override
// protected void onDestroy() {
// super.onDestroy();
//
// }
public void save(String inputText) {
FileOutputStream out =null;
BufferedWriter writer = null;
try {
out = openFileOutput("zjfdata", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
Toast.makeText(DataStorageAct.this,"已保存",Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
package com.example.raghu.fellowpassenger.definations;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.raghu.fellowpassenger.activities.ActivityDataHandler;
import java.util.ArrayList;
import java.util.List;
/**
* Created by raghu on 22/09/16.
*/
public class DbHandler extends SQLiteOpenHelper {
private static final String DB_NAME = "data.db";
private static final int VERSION = 1;
private static final String TABLE_NAME = "locations";
private static final String ID = "_id";
private static final String NAME = "name";
private static final String LATITUDE = "lat";
private static final String LONGITUDE = "lng";
private static final String STATUS = "status";
private static final String DISTANCE = "distance";
private SQLiteDatabase database;
public DbHandler(Context context) {
super(context, DB_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String queryTable = "CREATE TABLE " + TABLE_NAME +
" (" +
ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
NAME + " TEXT NOT NULL, " +
LATITUDE + " REAL NOT NULL, " +
LONGITUDE + " REAL NOT NULL, " +
STATUS + " INTEGER NOT NULL, " +
DISTANCE + " REAL " +
")";
sqLiteDatabase.execSQL(queryTable);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void openDB(){
database = getWritableDatabase();
}
public void closeDB(){
if(database != null && database.isOpen()){
database.close();
}
}
public void insert(int id, String name, Double lat, Double lng, int status, Float distance){
this.openDB();
ContentValues contentValues = new ContentValues();
if(id != -1)
contentValues.put(ID,id);
contentValues.put(NAME,name);
contentValues.put(LATITUDE,lat);
contentValues.put(LONGITUDE,lng);
contentValues.put(STATUS,status);
contentValues.put(DISTANCE,distance);
database.insert(TABLE_NAME,null,contentValues);
this.closeDB();
}
public void updateStatus(int id,boolean status){
int statusFlag = 0;
if(status == true){
statusFlag = 1;
}
this.openDB();
ContentValues contentValues = new ContentValues();
contentValues.put(STATUS,statusFlag);
String where = ID + " = " + id;
database.update(TABLE_NAME,contentValues,where,null);
this.closeDB();
}
public void updateDistance(int id,float distance){
this.openDB();
ContentValues contentValues = new ContentValues();
contentValues.put(DISTANCE,distance);
String where = ID + " = " + id;
database.update(TABLE_NAME,contentValues,where,null);
this.closeDB();
}
public void delete(int id){
this.openDB();
String where = ID + " = " + id;
database.delete(TABLE_NAME,where,null);
this.closeDB();
}
public List<LocationData> getAllRecords(){
this.openDB();
List ls = new ArrayList();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = database.rawQuery(query,null);
if (cursor.moveToFirst()){
do{
int id = cursor.getInt(cursor.getColumnIndex(ID));
String name = cursor.getString(cursor.getColumnIndex(NAME));
Double lat = cursor.getDouble(cursor.getColumnIndex(LATITUDE));
Double lng = cursor.getDouble(cursor.getColumnIndex(LONGITUDE));
int status = cursor.getInt(cursor.getColumnIndex(STATUS));
Float distance = cursor.getFloat(cursor.getColumnIndex(DISTANCE));
LocationData ld = new LocationData(id,name,lat,lng,status,distance);
ls.add(ld);
}while(cursor.moveToNext());
}
cursor.close();
this.closeDB();
return ls;
}
} |
package com.fotoable.fotoime.locksceen;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import java.io.File;
/**
* Created by dll on 16/4/15.
* 用来监测是否有app在使用充电屏保
*/
public class ChargeLockHelper {
private String KFolderName = ".fotoable_charge";
private String KFileFolderPath = null;
/**
* 当前app是否需要充电屏保
*/
private boolean needChargeLock = false;
private static ChargeLockHelper chargeLockHelper = null;
public static ChargeLockHelper getInstance() {
if (chargeLockHelper == null) {
chargeLockHelper = new ChargeLockHelper();
}
return chargeLockHelper;
}
public boolean checkIsNeedChargeLock(Context context) {
try {
if (isOtherChargeLockOpened(context)) {
needChargeLock = false;
} else {
needChargeLock = true;
setChargeLockOpened(context);
}
return needChargeLock;
} catch (Exception e) {
e.printStackTrace();
Log.i("ttt", "e.getMessage()7=" + e.getMessage());
return true;
}
}
private String fileFolderPath(Context context) {
try {
if (KFileFolderPath != null && KFileFolderPath.length() > 0) {
File file = new File(KFileFolderPath);
if (!file.exists()) {
file.mkdirs();
}
return KFileFolderPath;
}
boolean bHaveSdcard = false;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
bHaveSdcard = true;
}
String path = null;
if (bHaveSdcard) {
String extStorageDirectory = Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_DCIM).toString();
path = extStorageDirectory + "/" + KFolderName + "/";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
} else {
File f = context.getDir("Download", Context.MODE_WORLD_READABLE);
path = f.getAbsolutePath();
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
}
KFileFolderPath = path;
Log.i("ttt1", "KFileFolderPath=" + KFileFolderPath);
return path;
} catch (Exception e) {
e.printStackTrace();
Log.i("ttt1", "e.getMessage()23=" + e.getMessage());
return null;
}
}
private boolean isOtherChargeLockOpened(Context context) {
try {
File file = new File(fileFolderPath(context));
String[] arr = file.list();
Log.i("ttt", "arr=" + arr);
if (arr != null && arr.length != 0) {
Log.i("ttt", "arr.length=" + arr.length);
for (int index = 0; index < arr.length; index++) {
String apkName = arr[index];
File f = new File(fileFolderPath(context), apkName);
if (f.exists() & f.isFile()) {
f.delete();
continue;
}
Log.i("ttt", "arr.length2=" + arr.length);
if (f.isDirectory()) {
Log.i("ttt", "apkName=" + apkName);
Log.i("ttt", "context.getPackageName()=" + context.getPackageName());
if (!apkName.equalsIgnoreCase(context.getPackageName())) {
Log.i("ttt", "checkApkExist(context, apkName)=" + checkApkExist
(context, apkName));
if (checkApkExist(context, apkName)) {
return true;
} else {
Log.i("ttt", "else=");
if (f.exists()) {
f.delete();
}
Log.i("ttt", "f.delete()");
return false;
}
} else {
return false;
}
}
}
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
Log.i("ttt", "getMessage=" + e.getMessage());
}
return true;
}
private boolean checkApkExist(Context context, String packageName) {
if (packageName == null || "".equals(packageName))
return false;
try {
ApplicationInfo info = context.getPackageManager()
.getApplicationInfo(packageName,
PackageManager.GET_UNINSTALLED_PACKAGES);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
private void setChargeLockOpened(Context context) {
try {
Log.i("ttt", "context.getPackageName()=" + context.getPackageName());
File file = new File(fileFolderPath(context), context.getPackageName());
Log.i("ttt", "file.exists()=" + file.exists());
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
Log.i("ttt", "e.getMessage()45=" + e.getMessage());
}
}
public void setChargeLockClosed(Context context) {
try {
Log.i("ttt", "context.getPackageName2()=" + context.getPackageName());
File file = new File(fileFolderPath(context), context.getPackageName());
Log.i("ttt", "file.exists2()=" + file.exists());
Log.i("ttt", "file.isDirectory2()=" + file.isDirectory());
if (file.isDirectory() && file.exists()) {
delete(file);
}
System.gc();
Log.i("ttt", "after gc");
} catch (Exception e) {
e.printStackTrace();
Log.i("ttt", "e.getMessage()245=" + e.getMessage());
}
}
private void delete(File file) {
try {
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
delete(files[i]);
}
file.delete();
} catch (Exception e) {
Log.i("ttt", "e.getMessage()1245=" + e.getMessage());
}
}
}
|
package com.example.demo.mongodb.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.example.demo.mongodb.model.Localizaciones;
public interface LocalizacionesRepository extends MongoRepository<Localizaciones,String> {
Localizaciones findByNombre(String idLocalizacion);
void deleteByNombre(String id);
}
|
package StepDefinition;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import junit.framework.Assert;
public class Login {
WebDriver driver;
@Before
public void bt() {
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
@After
public void at() throws InterruptedException {
Thread.sleep(3000);
driver.close();
}
@Given("I am able to navigate on to login page")
public void i_am_able_to_navigate_on_to_login_page() {
driver.navigate().to("https://opensource-demo.orangehrmlive.com/");
}
@When("I update the username as {string}")
public void i_update_the_username_as(String string) {
driver.findElement(By.xpath("//*[@id='txtUsername']")).sendKeys(string);
}
@When("I update the password as {string}")
public void i_update_the_password_as(String string) {
driver.findElement(By.xpath("//*[@id='txtPassword']")).sendKeys(string);
}
@When("I click on the login button")
public void i_click_on_the_login_button() {
driver.findElement(By.id("btnLogin")).click();
}
@Then("I should see username as {string}")
public void i_should_see_username_as(String string) throws InterruptedException {
Thread.sleep(6000);
String expected = driver.findElement(By.xpath("//*[@id='welcome']")).getText();
Assert.assertEquals(expected, string);
Thread.sleep(3000);
driver.findElement(By.xpath("//*[@id='welcome']")).click();
Thread.sleep(3000);
driver.findElement(By.xpath("//*[@id='welcome-menu']/ul/li[2]/a")).click();
}
@Then("I should see error message as {string}")
public void i_should_see_error_message_as(String string) throws InterruptedException {
Thread.sleep(6000);
String expected = driver.findElement(By.id("spanMessage")).getText();
Assert.assertEquals(expected, string);
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.scripting;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Serializable;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.Column;
import javax.persistence.Lob;
import javax.persistence.MappedSuperclass;
import javax.persistence.Table;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import org.apache.log4j.Logger;
import org.hibernate.annotations.AccessType;
import org.hibernate.annotations.Proxy;
import org.hibernate.annotations.Type;
import org.objectweb.proactive.annotation.PublicAPI;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.ow2.proactive.utils.SchedulerLoggers;
/**
* A simple script to evaluate using java 6 scripting API.
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*
*
* @param <E> Template class's type of the result.
*/
@PublicAPI
@MappedSuperclass
@Table(name = "SCRIPT")
@AccessType("field")
@Proxy(lazy = false)
public abstract class Script<E> implements Serializable {
/** */
private static final long serialVersionUID = 31L;
/** Loggers */
public static final Logger logger_dev = ProActiveLogger.getLogger(SchedulerLoggers.SCRIPT);
/** Variable name for script arguments */
public static final String ARGUMENTS_NAME = "args";
/** Name of the script engine */
@Column(name = "SCRIPTENGINE")
protected String scriptEngine = null;
/** The script to evaluate */
@Column(name = "SCRIPT", length = Integer.MAX_VALUE)
@Lob
protected String script = null;
/** Id of this script */
@Column(name = "SCRIPT_ID", length = Integer.MAX_VALUE)
@Lob
protected String id = null;
/** The parameters of the script */
@Column(name = "PARAMETERS", columnDefinition = "BLOB")
@Type(type = "org.ow2.proactive.scheduler.core.db.schedulerType.CharacterLargeOBject")
protected String[] parameters = null;
/** ProActive needed constructor */
public Script() {
}
/** Directly create a script with a string.
* @param script String representing the script's source code
* @param engineName String representing the execution engine
* @param parameters script's execution arguments.
* @throws InvalidScriptException if the creation fails.
*/
public Script(String script, String engineName, String[] parameters) throws InvalidScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName(engineName);
if (engine == null) {
throw new InvalidScriptException("The engine '" + engineName + "' is not valid");
} else {
scriptEngine = engine.getFactory().getNames().get(0);
}
this.script = script;
this.id = script;
this.parameters = parameters;
}
/** Directly create a script with a string.
* @param script String representing the script's source code
* @param engineName String representing the execution engine
* @throws InvalidScriptException if the creation fails.
*/
public Script(String script, String engineName) throws InvalidScriptException {
this(script, engineName, null);
}
/** Create a script from a file.
* @param file a file containing the script's source code.
* @param parameters script's execution arguments.
* @throws InvalidScriptException if the creation fails.
*/
public Script(File file, String[] parameters) throws InvalidScriptException {
getEngineName(file.getPath());
try {
storeScript(file);
} catch (IOException e) {
throw new InvalidScriptException("Unable to read script : " + file.getAbsolutePath(), e);
}
this.id = file.getPath();
this.parameters = parameters;
}
/** Create a script from a file.
* @param file a file containing a script's source code.
* @throws InvalidScriptException if Constructor fails.
*/
public Script(File file) throws InvalidScriptException {
this(file, null);
}
/** Create a script from an URL.
* @param url representing a script source code.
* @param parameters execution arguments.
* @throws InvalidScriptException if the creation fails.
*/
public Script(URL url, String[] parameters) throws InvalidScriptException {
getEngineName(url.getFile());
try {
storeScript(url);
} catch (IOException e) {
throw new InvalidScriptException("Unable to read script : " + url.getPath(), e);
}
this.id = url.toExternalForm();
this.parameters = parameters;
}
/** Create a script from an URL.
* @param url representing a script source code.
* @throws InvalidScriptException if the creation fails.
*/
public Script(URL url) throws InvalidScriptException {
this(url, null);
}
/** Create a script from another script object
* @param script2 script object source
* @throws InvalidScriptException if the creation fails.
*/
public Script(Script<?> script2) throws InvalidScriptException {
this(script2.script, script2.scriptEngine, script2.parameters);
}
/**
* Get the script.
*
* @return the script.
*/
public String getScript() {
return script;
}
/**
* Set the script content, ie the executed code
*
* @param script the new script content
*/
public void setScript(String script) {
this.script = script;
}
/**
* Get the parameters.
*
* @return the parameters.
*/
public String[] getParameters() {
return parameters;
}
/**
* Add a binding to the script that will be handle by this handler.
*
* @param name the name of the variable
* @param value the value of the variable
*/
public void addBinding(String name, Object value) {
}
/**
* Execute the script and return the ScriptResult corresponding.
*
* @return a ScriptResult object.
*/
public ScriptResult<E> execute() {
return execute(null);
}
/**
* Execute the script and return the ScriptResult corresponding.
* This method can add an additional user bindings if needed.
*
* @param aBindings the additional user bindings to add if needed. Can be null or empty.
* @return a ScriptResult object.
*/
public ScriptResult<E> execute(Map<String, Object> aBindings) {
ScriptEngine engine = getEngine();
if (engine == null) {
return new ScriptResult<E>(new Exception("No Script Engine Found"));
}
try {
Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
//add additional bindings
if (aBindings != null) {
for (Entry<String, Object> e : aBindings.entrySet()) {
bindings.put(e.getKey(), e.getValue());
}
}
prepareBindings(bindings);
engine.eval(getReader());
return getResult(bindings);
} catch (Throwable e) {
logger_dev.error("", e);
return new ScriptResult<E>(new Exception("An exception occured while executing the script ", e));
}
}
/** String identifying the script.
* @return a String identifying the script.
*/
public abstract String getId();
/** The reader used to read the script. */
protected abstract Reader getReader();
/** The Script Engine used to evaluate the script. */
protected abstract ScriptEngine getEngine();
/** Specify the variable awaited from the script execution */
protected abstract void prepareSpecialBindings(Bindings bindings);
/** Return the variable awaited from the script execution */
protected abstract ScriptResult<E> getResult(Bindings bindings);
/** Set parameters in bindings if any */
protected final void prepareBindings(Bindings bindings) {
//add parameters
if (this.parameters != null) {
bindings.put(Script.ARGUMENTS_NAME, this.parameters);
}
// add special bindings
this.prepareSpecialBindings(bindings);
}
/** Create string script from url */
protected void storeScript(URL url) throws IOException {
BufferedReader buf = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder builder = new StringBuilder();
String tmp = null;
while ((tmp = buf.readLine()) != null) {
builder.append(tmp + "\n");
}
script = builder.toString();
}
/** Create string script from file */
protected void storeScript(File file) throws IOException {
BufferedReader buf = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
StringBuilder builder = new StringBuilder();
String tmp = null;
while ((tmp = buf.readLine()) != null) {
builder.append(tmp + "\n");
}
script = builder.toString();
}
/** Set the scriptEngine from filepath */
protected void getEngineName(String filepath) throws InvalidScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
for (ScriptEngineFactory sef : manager.getEngineFactories())
for (String ext : sef.getExtensions())
if (filepath.endsWith(ext)) {
scriptEngine = sef.getNames().get(0);
break;
}
if (scriptEngine == null) {
throw new InvalidScriptException("No script engine corresponding for file : " + filepath);
}
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object o) {
if (o instanceof Script) {
Script<E> new_name = (Script<E>) o;
return this.getId().equals(new_name.getId());
}
return false;
}
}
|
package pl.kur.firstapp;
import java.util.Scanner;
public class Start
{
public static void main(String[] args)
{
Zadanie1 zadanie1 = new Zadanie1();
zadanie1.Temp();
Zadanie2 zadanie2 = new Zadanie2();
zadanie2.Sekwencja();
Zadanie3 zadanie3 = new Zadanie3();
zadanie3.Trojkat();
Zadanie4 zadanie4 = new Zadanie4();
zadanie4.Gwiazdki();
Zadanie5 zadanie5 = new Zadanie5();
zadanie5.Zwrot();
Zadanie6 zadanie6 = new Zadanie6();
zadanie6.Zamiana();
}
}
|
import java.util.Scanner;
public class MainApotek {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] obat = {"A", "B", "C", "D", "E"};
int[] harga = {10000, 5000, 2000, 2500, 3000, 8000};
String item[] = new String[10];
int jumlah[] = new int[10];
System.out.println("Selamat datang di Apotek Overload");
System.out.println("---------------------------------");
System.out.println("Isi biodata berikut untuk memesan");
System.out.print("Input nama: ");
String nama = in.next();
System.out.print("Input alamat: ");
String alamat = in.next();
Apotek pasien = new Apotek(nama, alamat);
Apotek beli = new Apotek(obat, harga);
beli.listHarga();
for (int i = 0; i < item.length; i++) {
System.out.print("Nama obat: ");
item[i] = in.next();
System.out.print("Jumlah obat: ");
jumlah[i] = in.nextInt();
System.out.print("Tekan 'y' untuk tambah obat: ");
String lagi = in.next();
if (!"y".equalsIgnoreCase(lagi)) {
break;
}
}
System.out.println("------------------------------");
pasien.cetakBio();
beli.listHarga(item, jumlah);
System.out.println("Silahkan untuk melunasi pembayaran");
System.out.println("Terima kasih...");
}
}
|
package com.sinodynamic.hkgta.dto.crm;
import java.io.Serializable;
import java.util.Date;
public class SitePoiDto implements Serializable {
private static final long serialVersionUID = 1L;
private Long poiId;
private String createBy;
private Date createDate;
private String description;
private String updateBy;
private Date updateDate;
private String venueCode;
private String targetTypeCode;
public Long getPoiId() {
return poiId;
}
public void setPoiId(Long poiId) {
this.poiId = poiId;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public String getVenueCode() {
return venueCode;
}
public void setVenueCode(String venueCode) {
this.venueCode = venueCode;
}
public String getTargetTypeCode() {
return targetTypeCode;
}
public void setTargetTypeCode(String targetTypeCode) {
this.targetTypeCode = targetTypeCode;
}
}
|
package com.esum.wp.ims.documentstat.dao.impl;
import java.util.List;
import com.esum.appframework.dao.impl.SqlMapDAO;
import com.esum.appframework.exception.ApplicationException;
import com.esum.wp.ims.documentstat.dao.IDocumentStatDAO;
public class DocumentStatDAO extends SqlMapDAO implements IDocumentStatDAO {
/**
* Default constructor. Can be used in place of getInstance()
*/
public DocumentStatDAO () {}
public String collectStatID = "";
public String selectCollectStatID = "";
public String getLastCollectTimeID = "";
public String docNameListFromDocStatID = "";
public String docNameListFromDocLogID = "";
public String searchTpIdID = "";
public String dailyByDaySearchID = "";
public String dailyByTimeSearchID = "";
public String periodByDaySearchID = "";
public String periodByTimeSearchID = "";
public String dailyByDayListID = "";
public String dailyByTimeListID = "";
public String periodByDayListID = "";
public String periodByTimeListID = "";
public Object collectStat(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().insert(collectStatID, object);
} catch (Exception e) {
e.printStackTrace();
throw new ApplicationException(e);
}
}
public List selectCollectStat(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(selectCollectStatID, object);
} catch (Exception e) {
e.printStackTrace();
throw new ApplicationException(e);
}
}
public Object getLastCollectTime(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForObject(getLastCollectTimeID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List docNameListFromDocStat(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(docNameListFromDocStatID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List docNameListFromDocLog(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(docNameListFromDocLogID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List searchTpId(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(searchTpIdID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List dailyByDaySearch(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(dailyByDaySearchID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List dailyByTimeSearch(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(dailyByTimeSearchID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public Object periodByDaySearch(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForObject(periodByDaySearchID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public Object periodByTimeSearch(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForObject(periodByTimeSearchID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List dailyByDayList(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(dailyByDayListID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List dailyByTimeList(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(dailyByTimeListID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List periodByDayList(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(periodByDayListID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List periodByTimeList(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(periodByTimeListID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public String getGetLastCollectTimeID() {
return getLastCollectTimeID;
}
public void setGetLastCollectTimeID(String getLastCollectTimeID) {
this.getLastCollectTimeID = getLastCollectTimeID;
}
public String getCollectStatID() {
return collectStatID;
}
public void setCollectStatID(String collectStatID) {
this.collectStatID = collectStatID;
}
public String getSelectCollectStatID() {
return selectCollectStatID;
}
public void setSelectCollectStatID(String selectCollectStatID) {
this.selectCollectStatID = selectCollectStatID;
}
public String getSearchTpIdID() {
return searchTpIdID;
}
public void setSearchTpIdID(String searchTpIdID) {
this.searchTpIdID = searchTpIdID;
}
public String getPeriodByDayListID() {
return periodByDayListID;
}
public void setPeriodByDayListID(String periodByDayListID) {
this.periodByDayListID = periodByDayListID;
}
public String getPeriodByDaySearchID() {
return periodByDaySearchID;
}
public void setPeriodByDaySearchID(String periodByDaySearchID) {
this.periodByDaySearchID = periodByDaySearchID;
}
public String getPeriodByTimeListID() {
return periodByTimeListID;
}
public void setPeriodByTimeListID(String periodByTimeListID) {
this.periodByTimeListID = periodByTimeListID;
}
public String getPeriodByTimeSearchID() {
return periodByTimeSearchID;
}
public void setPeriodByTimeSearchID(String periodByTimeSearchID) {
this.periodByTimeSearchID = periodByTimeSearchID;
}
public String getDocNameListFromDocLogID() {
return docNameListFromDocLogID;
}
public void setDocNameListFromDocLogID(String docNameListFromDocLogID) {
this.docNameListFromDocLogID = docNameListFromDocLogID;
}
public String getDocNameListFromDocStatID() {
return docNameListFromDocStatID;
}
public void setDocNameListFromDocStatID(String docNameListFromDocStatID) {
this.docNameListFromDocStatID = docNameListFromDocStatID;
}
public String getDailyByDayListID() {
return dailyByDayListID;
}
public void setDailyByDayListID(String dailyByDayListID) {
this.dailyByDayListID = dailyByDayListID;
}
public String getDailyByDaySearchID() {
return dailyByDaySearchID;
}
public void setDailyByDaySearchID(String dailyByDaySearchID) {
this.dailyByDaySearchID = dailyByDaySearchID;
}
public String getDailyByTimeListID() {
return dailyByTimeListID;
}
public void setDailyByTimeListID(String dailyByTimeListID) {
this.dailyByTimeListID = dailyByTimeListID;
}
public String getDailyByTimeSearchID() {
return dailyByTimeSearchID;
}
public void setDailyByTimeSearchID(String dailyByTimeSearchID) {
this.dailyByTimeSearchID = dailyByTimeSearchID;
}
} |
package classes;
/**
* @author dylan
*
*/
public class OutFielder implements BaseBallPlayer {
private int heightInInches;
private float weight;
private float battingAverage;
/**
* @param heightInInches
* @param weight
* @param battingAverage
*/
public OutFielder(int heightInInches, float weight, float battingAverage) {
super();
this.heightInInches = heightInInches;
this.weight = weight;
this.battingAverage = battingAverage;
}
public OutFielder() {
}
@Override
public int getHeightInInches() {
System.out.println("getting Outfielder's height");
return this.heightInInches;
}
@Override
public void setHeightInInches(int height) {
System.out.println("setting Outfielder's height");
this.heightInInches = height;
}
@Override
public float getWeight() {
System.out.println("getting Outfielder's weight");
return this.getWeight();
}
@Override
public void setWeight(float weight) {
System.out.println("setting Outfielder's weight");
this.weight = weight;
}
public float getBattingAverage() {
return battingAverage;
}
public void setBattingAverage(float battingAverage) {
this.battingAverage = battingAverage;
}
/*
* (non-Javadoc)
*
* @see classes.BaseBallPlayer#warmTheBench()
*/
@Override
public void warmTheBench() {
System.out.println("Outfielder is warming the bench!");
}
}
|
package kr.or.ddit.successboard.dao;
import java.util.List;
import java.util.Map;
import kr.or.ddit.vo.JoinVO;
import kr.or.ddit.vo.ProjectVO;
import kr.or.ddit.vo.SuccessBoardCommentVO;
import kr.or.ddit.vo.SuccessBoardVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.lowagie.text.Paragraph;
@Repository
public class SuccessBoardDaoImpl implements ISuccessBoardDao {
@Autowired
private SqlMapClient client;
@Override
public List<SuccessBoardVO> successboardList() throws Exception {
return client.queryForList("successboard.successboardList");
}
@Override
public SuccessBoardVO selectSuccessBoardInfo(Map<String, String> params)
throws Exception {
return (SuccessBoardVO) client.queryForObject("successboard.selectSuccessBoardInfo", params);
}
@Override
public int insertSuccessBoard(SuccessBoardVO successboardInfo)
throws Exception {
int chk = 0;
Object obj = client.insert("successboard.insertSuccessBoard", successboardInfo);
if (obj == null) {
chk = 1;
}
return chk;
}
@Override
public int modifySuccessBoard(SuccessBoardVO successboardInfo)
throws Exception {
return client.update("successboard.modifySuccessBoard", successboardInfo);
}
@Override
public int deleteSuccessBoard(Map<String, String> params) throws Exception {
return client.update("successboard.deleteSuccessBoard", params);
}
@Override
public int updateHit(Map<String, String> params) throws Exception {
return client.update("successboard.updateHit", params);
}
@Override
public List<SuccessBoardCommentVO> selectCommentList(
Map<String, String> params) throws Exception {
return client.queryForList("successboard_comment.selectCommentList", params);
}
@Override
public int insertSuccessComment(SuccessBoardCommentVO successCommentInfo)
throws Exception {
int chk = 0;
Object obj = client.insert("successboard_comment.insertSuccessComment", successCommentInfo);
if (obj == null) {
chk = 1;
}
return chk;
}
@Override
public int deleteSuccessComment(Map<String, String> params)
throws Exception {
return client.delete("successboard_comment.deleteSuccessComment", params);
}
@Override
public int modifySuccessComment(Map<String, String> params)
throws Exception {
return client.update("successboard_comment.modifySuccessComment", params);
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.desktopapp.client.property;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.dom.ScrollSupport.ScrollMode;
import com.sencha.gxt.data.shared.IconProvider;
import com.sencha.gxt.desktopapp.client.filemanager.images.Images;
import com.sencha.gxt.desktopapp.client.persistence.FileModel;
import com.sencha.gxt.widget.core.client.Window;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.HtmlLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.event.HideEvent;
import com.sencha.gxt.widget.core.client.event.HideEvent.HideHandler;
public class PropertyViewImpl implements PropertyView, HideHandler {
private static final String TITLE = "Property";
private PropertyPresenter propertyPresenter;
private Window window;
private PropertyIconProvider propertyIconProvider;
private PropertyToolBar propertyToolBar;
private VerticalLayoutContainer verticalLayoutContainer;
private HtmlLayoutContainer htmlContainer;
private TextButton btn;
public PropertyViewImpl(PropertyPresenter propertyPresenter) {
this.propertyPresenter = propertyPresenter;
}
@Override
public Widget asWidget() {
return getWindow();
}
private IconProvider<FileModel> getPropertyIconProvider() {
if (propertyIconProvider == null) {
propertyIconProvider = new PropertyIconProvider();
}
return propertyIconProvider;
}
private PropertyPresenter getPropertyPresenter() {
return propertyPresenter;
}
private PropertyToolBar getPropertyToolBar() {
if (propertyToolBar == null) {
propertyToolBar = new PropertyToolBar(getPropertyPresenter());
}
return propertyToolBar;
}
private String getTitle(FileModel fileModel) {
return TITLE;
}
private Window getWindow() {
if (window == null) {
window = new Window();
window.setHeadingText(getTitle(null));
window.getHeader().setIcon(Images.getImageResources().folder());
window.setMinimizable(true);
window.setMaximizable(true);
window.setClosable(false);
window.setOnEsc(false);
window.addHideHandler(this);
window.setWidget(getVerticalLayoutContainer());
}
return window;
}
private Widget getContainer(String html) {
btn = new TextButton(html);
return btn;
}
@Override
public void onHide(HideEvent event) {
}
private VerticalLayoutContainer getVerticalLayoutContainer() {
if (verticalLayoutContainer == null) {
verticalLayoutContainer = new VerticalLayoutContainer();
verticalLayoutContainer.setBorders(false);
verticalLayoutContainer.add(getPropertyToolBar(),
new VerticalLayoutData(1, -1));
verticalLayoutContainer.add(getContainer("hello world"),
new VerticalLayoutData(1, 1));
verticalLayoutContainer.setScrollMode(ScrollMode.AUTO);
}
return verticalLayoutContainer;
}
@Override
public void showProperty(String string) {
btn.setText(string);
window.forceLayout();
}
}
|
package com.iss.webviewexample;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.iss.webviewexample.R;
public class WebviewActivity extends AppCompatActivity {
private String mUrl;
private WebView mWebView;
private ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
mUrl = intent.getStringExtra(MainActivity.EXTERNAL_URL);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mProgressBar.setMax(100); // WebChromeClient reports in range 0-100
mWebView = (WebView) findViewById(R.id.web_view);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView webView, int newProgress) {
if (newProgress == 100) {
mProgressBar.setVisibility(View.GONE);
} else {
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setProgress(newProgress);
}
}
});
mWebView.setWebViewClient(new MyWebViewClient());
mWebView.loadUrl(mUrl);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
private class MyWebViewClient extends WebViewClient {
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if ("developer.android.com".equals(Uri.parse(url).getHost())) {
// This is the website my WebView will load the page
return false;
}
// Otherwise, launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
}
|
// 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.app;
import android.support.annotation.NonNull;
public class ServerConfig implements Comparable<ServerConfig> {
public final String id;
public final String name;
public final String url;
public final String user;
public final String password;
private ServerConfig(
String id, String name, String url, String user, String password) {
this.id = id;
this.name = name;
this.url = url;
this.user = user;
this.password = password;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(Object o) {
return o instanceof ServerConfig
&& ((ServerConfig) o).id.equals(id);
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public int compareTo(@NonNull ServerConfig another) {
return name.compareTo(another.name);
}
public static class Builder {
private String id;
private String name;
private String url;
private String user;
private String password;
public Builder setId(String id) {
this.id = id;
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setUrl(String url) {
this.url = url;
return this;
}
public Builder setUser(String user) {
this.user = user;
return this;
}
public Builder setPassword(String password) {
this.password = password;
return this;
}
public ServerConfig build() {
return new ServerConfig(id, name, url, user, password);
}
}
}
|
import java.util.ArrayList;
public class Metrics {
//I seen that this only had to be static
public static int verifyDistribution(ArrayList<Double> gasnum, double mean, double stdDeviation, double numberofStdDeviation){
int index = 0;//this will be used to go to the next index of the ArrayList
int count = 0; //to count the number of randomnumbers that deviation away from the mean; also for calculating percentage
while(index < gasnum.size()){ //keep running so long as we don't go beyond the ArrayList size
//this is pretty much the same logic as in the assignment sheet; check if the numbers fall between (0.0-(1.0*1.0)) and (0.0+(1.0*1.0))
if((gasnum.get(index) < (mean + (stdDeviation*numberofStdDeviation))) && (gasnum.get(index) > (mean - (stdDeviation*numberofStdDeviation)))){
count++; //if show increase count by one
}
index++;//go to the next index of the ArrayList
}
return ((count*100)/gasnum.size()); //calculate the percentage within the standard deviation
}
}
|
/*
* #%L
* Diana UI Core
* %%
* Copyright (C) 2014 Diana UI
* %%
* 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.
* #L%
*/
package com.dianaui.universal.core.client.ui;
import com.dianaui.universal.core.client.ui.base.HasResponsiveness;
import com.dianaui.universal.core.client.ui.constants.IconPosition;
import com.dianaui.universal.core.client.ui.constants.IconSize;
import com.dianaui.universal.core.client.ui.constants.IconType;
import com.dianaui.universal.core.client.ui.constants.Styles;
import com.dianaui.universal.core.client.ui.html.UnorderedList;
/**
* Support for Bootstrap pager (http://getbootstrap.com/components/#pagination-pager)
*
* @author Joshua Godi
*/
public class Pager extends UnorderedList implements HasResponsiveness {
private static final String DEFAULT_PREVIOUS = "Previous";
private static final String DEFAULT_NEXT = "Next";
private final AnchorListItem previous;
private final AnchorListItem next;
public Pager() {
setStyleName(Styles.PAGER);
previous = new AnchorListItem(DEFAULT_PREVIOUS);
next = new AnchorListItem(DEFAULT_NEXT);
add(previous);
add(next);
}
public void setAlignToSides(final boolean alignToSides) {
if (alignToSides) {
previous.setStyleName(Styles.PREVIOUS);
next.setStyleName(Styles.NEXT);
} else {
previous.removeStyleName(Styles.PREVIOUS);
next.removeStyleName(Styles.NEXT);
}
}
public AnchorListItem getPrevious() {
return previous;
}
public AnchorListItem getNext() {
return next;
}
public void setPreviousText(final String text) {
previous.setText(text);
}
public void setPreviousIcon(final IconType icon) {
previous.setFontAwesomeIcon(icon);
}
public void setPreviousIconSize(final IconSize iconSize) {
previous.setIconSize(iconSize);
}
public void setNextText(final String text) {
next.setText(text);
}
public void setNextIcon(final IconType icon) {
next.setFontAwesomeIcon(icon);
next.setIconPosition(IconPosition.RIGHT);
}
public void setNextIconSize(final IconSize iconSize) {
next.setIconSize(iconSize);
}
}
|
package app;
public class HouseInfo {
private Long id;
private String s1;
private String s2;
private String s3;
public HouseInfo(Long id, String s1, String s2, String s3) {
this.id=id;
this.s1=s1;
this.s2=s2;
this.s3=s3;
}
}
|
package com.gogodogstudio.remindmeapp.fragments;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.gogodogstudio.remindmeapp.R;
public class ToDoFragment extends AbstractTabFragmnet {
private View view;
private Context context;
public static ToDoFragment getInstance(Context context){
Bundle args = new Bundle();
ToDoFragment exampleFragment = new ToDoFragment();
exampleFragment.setArguments(args);
exampleFragment.setContext(context);
exampleFragment.setTitle(context.getString(R.string.TabToDo));
return exampleFragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.example_layout, container, false);
return view;
}
public void setContext(Context context) {
this.context = context;
}
}
|
package sop.reports.vo;
import java.math.BigDecimal;
/**
* @Author: LCF
* @Date: 2020/1/9 10:27
* @Package: sop.reports.vo
*/
public class SimplifiedOff {
private String no;
private String date;
private String vto;
private String attn;
private String code;
private BigDecimal price;
private String fob;
private String itno;
private String itname;
private BigDecimal it_pkg_20_qty;
private BigDecimal it_pkg_40_qty;
private BigDecimal it_pkg_40HQ_qty;
private String off2_desc_offer_sh;
private BigDecimal cbm;
private String it_uom;
private String it_pkg_exp_pcs;
private String it_image_1;
private String it_pkg_detail;
private String it_desc_of_sh;
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getVto() {
return vto;
}
public void setVto(String vto) {
this.vto = vto;
}
public String getAttn() {
return attn;
}
public void setAttn(String attn) {
this.attn = attn;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getFob() {
return fob;
}
public void setFob(String fob) {
this.fob = fob;
}
public String getItno() {
return itno;
}
public void setItno(String itno) {
this.itno = itno;
}
public String getItname() {
return itname;
}
public void setItname(String itname) {
this.itname = itname;
}
public BigDecimal getIt_pkg_20_qty() {
return it_pkg_20_qty;
}
public void setIt_pkg_20_qty(BigDecimal it_pkg_20_qty) {
this.it_pkg_20_qty = it_pkg_20_qty;
}
public BigDecimal getIt_pkg_40_qty() {
return it_pkg_40_qty;
}
public void setIt_pkg_40_qty(BigDecimal it_pkg_40_qty) {
this.it_pkg_40_qty = it_pkg_40_qty;
}
public BigDecimal getIt_pkg_40HQ_qty() {
return it_pkg_40HQ_qty;
}
public void setIt_pkg_40HQ_qty(BigDecimal it_pkg_40HQ_qty) {
this.it_pkg_40HQ_qty = it_pkg_40HQ_qty;
}
public String getOff2_desc_offer_sh() {
return off2_desc_offer_sh;
}
public void setOff2_desc_offer_sh(String off2_desc_offer_sh) {
this.off2_desc_offer_sh = off2_desc_offer_sh;
}
public BigDecimal getCbm() {
return cbm;
}
public void setCbm(BigDecimal cbm) {
this.cbm = cbm;
}
public String getIt_uom() {
return it_uom;
}
public void setIt_uom(String it_uom) {
this.it_uom = it_uom;
}
public String getIt_pkg_exp_pcs() {
return it_pkg_exp_pcs;
}
public void setIt_pkg_exp_pcs(String it_pkg_exp_pcs) {
this.it_pkg_exp_pcs = it_pkg_exp_pcs;
}
public String getIt_image_1() {
return it_image_1;
}
public void setIt_image_1(String it_image_1) {
this.it_image_1 = it_image_1;
}
public String getIt_pkg_detail() {
return it_pkg_detail;
}
public void setIt_pkg_detail(String it_pkg_detail) {
this.it_pkg_detail = it_pkg_detail;
}
public String getIt_desc_of_sh() {
return it_desc_of_sh;
}
public void setIt_desc_of_sh(String it_desc_of_sh) {
this.it_desc_of_sh = it_desc_of_sh;
}
}
|
package com.test.reddittopnews.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
public class RetrofitController implements Callback<RedditTopNews> {
public static final String BASE_URL = "https://www.reddit.com/";
public IAPIReddit start() {
ObjectMapper objectMapper = new ObjectMapper();
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(JacksonConverterFactory.create(objectMapper))
.build();
IAPIReddit iapiReddit = retrofit.create(IAPIReddit.class);
//Call<RedditTopNews> call = iapiReddit.getNews("");
//call.enqueue(this);
return iapiReddit;
}
@Override
public void onResponse(Call<RedditTopNews> call, Response<RedditTopNews> response) {
if (response.isSuccessful()) {
}
}
@Override
public void onFailure(Call<RedditTopNews> call, Throwable t) {
}
}
|
package com.hhdb.csadmin.plugin.about;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UnsupportedLookAndFeelException;
import com.hhdb.csadmin.common.util.UiUtil;
import com.hhdb.csadmin.plugin.menu.util.UIUtils;
public class test1 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UiUtil.setLookAndFeel();
final AboutPanel jpanel = new AboutPanel(new Color(107, 148, 200),
//背景图、版本信息及文字介绍位置
"etc/icon/backgroundImg/splash.png","etc/icon/backgroundImg/splash2.png",
"etc/icon/backgroundImg/splash3.png","etc/icon/backgroundImg/splash4.png",
new Color(107, 107, 107), 21, 165);
//dbp.jpanel.repaint();
//实例化界面
final JFrame jframe = new JFrame();
Dimension size = new Dimension(jpanel.imgWidth,jpanel.imgHight);
jframe.setSize(size);
jframe.setLayout(new BorderLayout());
// jframe.add(BorderLayout.CENTER, this);
//上一张下一张按钮
JPanel panel_down = new JPanel();
panel_down.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
JButton btn_last = new JButton("上一张");
panel_down.add(btn_last);
JButton btn_next = new JButton("下一张");
panel_down.add(btn_next);
panel_down.setBackground(null);
panel_down.setOpaque(false);
//将按钮添加至图片上
jpanel.add(panel_down, BorderLayout.SOUTH);
//关系窗口按钮
JPanel panel_close=new JPanel();
panel_close.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
JButton btn_close = new JButton("关闭");
panel_close.add(btn_close);
jpanel.add(btn_close,BorderLayout.SOUTH);
jframe.add(jpanel);
jframe.setLocation(UIUtils.getPointToCenter(jframe, size));
jframe.setUndecorated(true);
jframe.validate();
jframe.setVisible(true);
//监听按钮换图
btn_last.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jpanel.index--;
if(jpanel.index<0){
jpanel.index=3;
}
jpanel.repaint();
}
}
);
btn_next.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jpanel.index++;
jpanel.repaint();
}
}
);
btn_close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//关闭
//jframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
jframe.setVisible(false);
}
});
}
}
|
package me.roybailey.springboot.neo4j.domain;
import lombok.*;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
@NodeEntity
public class Person {
@GraphId
Long id;
@Getter
String name;
@Getter
Integer born;
} |
package com.mytech.tkpost.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mytech.tkpost.dao.PostRepository;
import com.mytech.tkpost.entities.Post;
@Service
public class PostServiceImplimentation {
@Autowired
PostRepository postRepository;
public List<Post> getAllPost() {
return postRepository.findAll();
}
public Optional<Post> getPost(Long id) {
return postRepository.findById(id);
}
public List<Post> getPostByStatus(String status) {
return null;
}
public Post addPost(Post post) {
return postRepository.save(post);
}
public boolean updatePost() {
return true;
}
public void deletePost(Long id) {
postRepository.deleteById(id);
}
}
|
package com.niksoftware.snapseed.views;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import com.niksoftware.snapseed.core.DeviceDefs;
import com.niksoftware.snapseed.core.NotificationCenter;
import com.niksoftware.snapseed.core.NotificationCenterListener;
import com.niksoftware.snapseed.core.NotificationCenterListener.ListenerType;
public class ScaleParameterDisplay extends ViewGroup {
NotificationCenterListener _l1;
NotificationCenterListener _l2;
NotificationCenterListener _l3;
NotificationCenterListener _l4;
private ScaleParameterDisplayView _scaleParameterDisplayView = null;
private ScaleParameterValueView _scaleParameterValueView = null;
private int _valueHeight;
private int _valueWidth;
public ScaleParameterDisplay(Context context) {
super(context);
init();
}
public ScaleParameterDisplay(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ScaleParameterDisplay(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
protected void init() {
setWillNotDraw(true);
this._scaleParameterDisplayView = new ScaleParameterDisplayView();
addView(this._scaleParameterDisplayView);
if (DeviceDefs.isTablet()) {
this._scaleParameterValueView = new ScaleParameterValueView();
addView(this._scaleParameterValueView);
}
NotificationCenter instance = NotificationCenter.getInstance();
NotificationCenterListener anonymousClass1 = new NotificationCenterListener() {
public void performAction(Object arg) {
if (DeviceDefs.isTablet()) {
ScaleParameterDisplay.this._scaleParameterDisplayView.fill_backgrounds();
}
ScaleParameterDisplay.this._scaleParameterDisplayView.invalidate();
}
};
this._l1 = anonymousClass1;
instance.addListener(anonymousClass1, ListenerType.DidActivateFilter);
instance = NotificationCenter.getInstance();
anonymousClass1 = new NotificationCenterListener() {
public void performAction(Object arg) {
ScaleParameterDisplay.this._scaleParameterDisplayView.invalidate();
if (DeviceDefs.isTablet()) {
ScaleParameterDisplay.this._scaleParameterValueView.invalidate();
}
}
};
this._l2 = anonymousClass1;
instance.addListener(anonymousClass1, ListenerType.DidChangeActiveFilterParameter);
instance = NotificationCenter.getInstance();
anonymousClass1 = new NotificationCenterListener() {
public void performAction(Object arg) {
if (DeviceDefs.isTablet()) {
ScaleParameterDisplay.this._scaleParameterValueView.invalidate();
} else {
ScaleParameterDisplay.this._scaleParameterDisplayView.invalidate();
}
}
};
this._l3 = anonymousClass1;
instance.addListener(anonymousClass1, ListenerType.DidChangeFilterParameterValue);
instance = NotificationCenter.getInstance();
anonymousClass1 = new NotificationCenterListener() {
public void performAction(Object arg) {
ScaleParameterDisplay.this._scaleParameterDisplayView.invalidate();
if (DeviceDefs.isTablet()) {
ScaleParameterDisplay.this._scaleParameterValueView.invalidate();
}
}
};
this._l4 = anonymousClass1;
instance.addListener(anonymousClass1, ListenerType.UndoRedoPerformed);
}
public void cleanup() {
NotificationCenter center = NotificationCenter.getInstance();
if (this._l1 != null) {
center.removeListener(this._l1, ListenerType.DidActivateFilter);
}
if (this._l2 != null) {
center.removeListener(this._l2, ListenerType.DidChangeActiveFilterParameter);
}
if (this._l3 != null) {
center.removeListener(this._l3, ListenerType.DidChangeFilterParameterValue);
}
if (this._l4 != null) {
center.removeListener(this._l4, ListenerType.UndoRedoPerformed);
}
this._l4 = null;
this._l3 = null;
this._l2 = null;
this._l1 = null;
}
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int displayWidth = this._scaleParameterDisplayView.getMeasuredWidth();
this._scaleParameterDisplayView.layout(0, 0, displayWidth, this._scaleParameterDisplayView.getMeasuredHeight());
if (DeviceDefs.isTablet()) {
int x = (displayWidth - this._valueWidth) / 2;
int y = Math.round(((float) getHeight()) * 0.44f);
this._scaleParameterValueView.layout(x, y, this._valueWidth + x, this._valueHeight + y);
}
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
this._scaleParameterDisplayView.measure(MeasureSpec.makeMeasureSpec(0, 0), MeasureSpec.makeMeasureSpec(0, 0));
setMeasuredDimension(MeasureSpec.makeMeasureSpec(this._scaleParameterDisplayView.getMeasuredWidth(), 1073741824), MeasureSpec.makeMeasureSpec(this._scaleParameterDisplayView.getMeasuredHeight(), 1073741824));
if (DeviceDefs.isTablet()) {
this._scaleParameterValueView.measure(MeasureSpec.makeMeasureSpec(0, 0), MeasureSpec.makeMeasureSpec(0, 0));
this._valueWidth = this._scaleParameterValueView.getMeasuredWidth();
this._valueHeight = this._scaleParameterValueView.getMeasuredHeight();
}
}
}
|
package com.ipincloud.iotbj.srv.service;
import com.ipincloud.iotbj.srv.domain.RoleData;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
//(Iotbj) 服务接口
//generate by redcloud,2020-07-24 19:59:20
public interface RoleDataService {
//@param id 主键
//@return 实例对象RoleData
RoleData queryById(Long id);
//@param jsonObj 过滤条件等
//@return 实例对象RoleData
List<Map> roleDataQuery(JSONObject jsonObj);
//@param jsonObj 过滤条件等
//@return JSONObject
void roleDataSetRelation(JSONObject jsonObj);
}
|
package com.xh.util;
import java.util.List;
public class TimeSort {
/**
*
* 时间类
*
*/
private List<String> list;
private String separator;
private String[] stSort;
/**
*
* @param list是时间数组
* ,separator是时间格式的分隔符,比如说“2014-05-6”他的分隔符就是“-” 时间先后顺序,年 月 日 时 分
* 秒,格式要一致
*/
public TimeSort(List<String> list, String separator) {
// TODO Auto-generated constructor stub
this.list = list;
this.separator = separator;
this.stSort = list.toArray(new String[list.size()]);
}
private int timePrecision(String time, String separator) {
if ((null == time || "".equals(time))
|| (null == separator || "".equals(separator)))
return 0;
switch (time.split(separator).length) {
case 1:
System.out.println("Time precision for years");
return 1;
case 2:
System.out.println("Time precision for months");
return 2;
case 3:
System.out.println("Time precision for the day");
return 3;
case 4:
System.out.println("Accuracy of time too");
return 4;
case 5:
System.out.println("For precision time points");
return 5;
case 6:
System.out.println("Accuracy for the second time");
return 6;
default:
return 7;
}
}
public void ascend() {
switch (timePrecision(stSort[0], separator)) {
case 0:
System.out.println("没有输入时间不需要排序");
break;
case 1:
System.out.println("输入的时间精度为年,只需要比较年");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i]);
int time2 = Integer.parseInt(stSort[j]);
String exchangeCapacity;
if (time1 < time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
break;
case 2:
System.out.println("输入的时间精度为月,先比较年,年相同比较月");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i].split(separator)[0]);
int time2 = Integer.parseInt(stSort[j].split(separator)[0]);
int time11 = Integer
.parseInt(stSort[i].split(separator)[1]);
int time21 = Integer
.parseInt(stSort[j].split(separator)[1]);
String exchangeCapacity;
if (time1 < time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time1 == time2) {
if (time11 < time21) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
}
break;
case 3:
System.out.println("输入的时间精度为日,先比较年,年相同比较月,月相同比较日");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i].split(separator)[0]);
int time2 = Integer.parseInt(stSort[j].split(separator)[0]);
int time11 = Integer
.parseInt(stSort[i].split(separator)[1]);
int time21 = Integer
.parseInt(stSort[j].split(separator)[1]);
int time12 = Integer
.parseInt(stSort[i].split(separator)[2]);
int time22 = Integer
.parseInt(stSort[j].split(separator)[2]);
String exchangeCapacity;
if (time1 < time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
// System.out
// .println("这是 time1=" + time1 + ",这是 time2=" + time2
// + "这是相等=" + (time1 == time2 ? "相等" : "不想等"));
if (time1 == time2) {
if (time11 < time21) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time11 == time21)
if (time12 < time22) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
}
break;
case 4:
System.out.println("输入的时间精度为时,先比较年,年相同比较月,月相同比较日,日相同比较时");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i].split(separator)[0]);
int time2 = Integer.parseInt(stSort[j].split(separator)[0]);
int time11 = Integer
.parseInt(stSort[i].split(separator)[1]);
int time21 = Integer
.parseInt(stSort[j].split(separator)[1]);
int time12 = Integer
.parseInt(stSort[i].split(separator)[2]);
int time22 = Integer
.parseInt(stSort[j].split(separator)[2]);
int time13 = Integer
.parseInt(stSort[i].split(separator)[3]);
int time23 = Integer
.parseInt(stSort[j].split(separator)[3]);
String exchangeCapacity;
if (time1 < time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time1 == time2) {
if (time11 < time21) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time11 == time21) {
if (time12 < time22) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time12 == time22)
if (time13 < time23) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
}
}
break;
case 5:
System.out.println("输入的时间精度为分,先比较年,年相同比较月,月相同比较日,日相同比较时,时相同比较分");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i].split(separator)[0]);
int time2 = Integer.parseInt(stSort[j].split(separator)[0]);
int time11 = Integer
.parseInt(stSort[i].split(separator)[1]);
int time21 = Integer
.parseInt(stSort[j].split(separator)[1]);
int time12 = Integer
.parseInt(stSort[i].split(separator)[2]);
int time22 = Integer
.parseInt(stSort[j].split(separator)[2]);
int time13 = Integer
.parseInt(stSort[i].split(separator)[3]);
int time23 = Integer
.parseInt(stSort[j].split(separator)[3]);
int time14 = Integer
.parseInt(stSort[i].split(separator)[4]);
int time24 = Integer
.parseInt(stSort[j].split(separator)[4]);
String exchangeCapacity;
if (time1 < time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time1 == time2) {
if (time11 < time21) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time11 == time21) {
if (time12 < time22) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time12 == time22) {
if (time13 < time23) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time13 == time23)
if (time14 < time24) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
}
}
}
break;
case 6:
System.out
.println("输入的时间精度为秒,先比较年,年相同比较月,月相同比较日,日相同比较时,时相同比较分,分相同比较秒");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i].split(separator)[0]);
int time2 = Integer.parseInt(stSort[j].split(separator)[0]);
int time11 = Integer
.parseInt(stSort[i].split(separator)[1]);
int time21 = Integer
.parseInt(stSort[j].split(separator)[1]);
int time12 = Integer
.parseInt(stSort[i].split(separator)[2]);
int time22 = Integer
.parseInt(stSort[j].split(separator)[2]);
int time13 = Integer
.parseInt(stSort[i].split(separator)[3]);
int time23 = Integer
.parseInt(stSort[j].split(separator)[3]);
int time14 = Integer
.parseInt(stSort[i].split(separator)[4]);
int time24 = Integer
.parseInt(stSort[j].split(separator)[4]);
int time15 = Integer
.parseInt(stSort[i].split(separator)[5]);
int time25 = Integer
.parseInt(stSort[j].split(separator)[5]);
String exchangeCapacity;
if (time1 < time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time1 == time2) {
if (time11 < time21) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time11 == time21) {
if (time12 < time22) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time12 == time22) {
if (time13 < time23) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time13 == time23) {
if (time14 < time24) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time14 == time24)
if (time15 < time25) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
}
}
}
}
break;
default:
break;
}
}
public void order() {
switch (timePrecision(stSort[0], separator)) {
case 0:
System.out.println("没有输入时间不需要排序");
break;
case 1:
System.out.println("输入的时间精度为年,只需要比较年");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i]);
int time2 = Integer.parseInt(stSort[j]);
String exchangeCapacity;
if (time1 > time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
break;
case 2:
System.out.println("输入的时间精度为月,先比较年,年相同比较月");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i].split(separator)[0]);
int time2 = Integer.parseInt(stSort[j].split(separator)[0]);
int time11 = Integer
.parseInt(stSort[i].split(separator)[1]);
int time21 = Integer
.parseInt(stSort[j].split(separator)[1]);
String exchangeCapacity;
if (time1 > time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time1 == time2) {
if (time11 > time21) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
}
break;
case 3:
System.out.println("输入的时间精度为日,先比较年,年相同比较月,月相同比较日");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i + 1; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i].split(separator)[0]);
int time2 = Integer.parseInt(stSort[j].split(separator)[0]);
int time11 = Integer
.parseInt(stSort[i].split(separator)[1]);
int time21 = Integer
.parseInt(stSort[j].split(separator)[1]);
int time12 = Integer
.parseInt(stSort[i].split(separator)[2]);
int time22 = Integer
.parseInt(stSort[j].split(separator)[2]);
String exchangeCapacity;
// System.out.println("这是 time1" + time1 + ",这是 time2" +
// time2
// + ",这是循环的步数" + i);
if (time1 > time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time1 == time2) {
if (time11 > time21) {
// System.out.println("===============我是纯洁的分隔线");
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time11 == time21)
if (time12 > time22) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
}
break;
case 4:
System.out.println("输入的时间精度为时,先比较年,年相同比较月,月相同比较日,日相同比较时");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i].split(separator)[0]);
int time2 = Integer.parseInt(stSort[j].split(separator)[0]);
int time11 = Integer
.parseInt(stSort[i].split(separator)[1]);
int time21 = Integer
.parseInt(stSort[j].split(separator)[1]);
int time12 = Integer
.parseInt(stSort[i].split(separator)[2]);
int time22 = Integer
.parseInt(stSort[j].split(separator)[2]);
int time13 = Integer
.parseInt(stSort[i].split(separator)[3]);
int time23 = Integer
.parseInt(stSort[j].split(separator)[3]);
String exchangeCapacity;
if (time1 > time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time1 == time2) {
if (time11 > time21) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time11 == time21) {
if (time12 > time22) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time12 == time22)
if (time13 > time23) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
}
}
break;
case 5:
System.out.println("输入的时间精度为分,先比较年,年相同比较月,月相同比较日,日相同比较时,时相同比较分");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i].split(separator)[0]);
int time2 = Integer.parseInt(stSort[j].split(separator)[0]);
int time11 = Integer
.parseInt(stSort[i].split(separator)[1]);
int time21 = Integer
.parseInt(stSort[j].split(separator)[1]);
int time12 = Integer
.parseInt(stSort[i].split(separator)[2]);
int time22 = Integer
.parseInt(stSort[j].split(separator)[2]);
int time13 = Integer
.parseInt(stSort[i].split(separator)[3]);
int time23 = Integer
.parseInt(stSort[j].split(separator)[3]);
int time14 = Integer
.parseInt(stSort[i].split(separator)[4]);
int time24 = Integer
.parseInt(stSort[j].split(separator)[4]);
String exchangeCapacity;
if (time1 > time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time1 == time2) {
if (time11 > time21) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time11 == time21) {
if (time12 > time22) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time12 == time22) {
if (time13 > time23) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time13 == time23)
if (time14 > time24) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
}
}
}
break;
case 6:
System.out
.println("输入的时间精度为秒,先比较年,年相同比较月,月相同比较日,日相同比较时,时相同比较分,分相同比较秒");
for (int i = 0; i < stSort.length - 1; i++) {
for (int j = i; j < stSort.length; j++) {
int time1 = Integer.parseInt(stSort[i].split(separator)[0]);
int time2 = Integer.parseInt(stSort[j].split(separator)[0]);
int time11 = Integer
.parseInt(stSort[i].split(separator)[1]);
int time21 = Integer
.parseInt(stSort[j].split(separator)[1]);
int time12 = Integer
.parseInt(stSort[i].split(separator)[2]);
int time22 = Integer
.parseInt(stSort[j].split(separator)[2]);
int time13 = Integer
.parseInt(stSort[i].split(separator)[3]);
int time23 = Integer
.parseInt(stSort[j].split(separator)[3]);
int time14 = Integer
.parseInt(stSort[i].split(separator)[4]);
int time24 = Integer
.parseInt(stSort[j].split(separator)[4]);
int time15 = Integer
.parseInt(stSort[i].split(separator)[5]);
int time25 = Integer
.parseInt(stSort[j].split(separator)[5]);
String exchangeCapacity;
if (time1 > time2) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time1 == time2) {
if (time11 > time21) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time11 == time21) {
if (time12 > time22) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time12 == time22) {
if (time13 > time23) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time13 == time23) {
if (time14 > time24) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
if (time14 == time24)
if (time15 > time25) {
exchangeCapacity = stSort[i];
stSort[i] = stSort[j];
stSort[j] = exchangeCapacity;
}
}
}
}
}
}
}
break;
default:
break;
}
}
// public String ascend(String year1, String year2) {
// int year = Integer.parseInt(year1);
// int year3 = Integer.parseInt(year2);
// if (year >= year3)
// return year1;
// else
// return year2;
// }
public int[] ascendInt() {
ascend();
int[] ascendInt = new int[list.size()];
for (int i = 0; i < ascendInt.length; i++) {
System.out.println(list.get(i) + "这是list");
System.out.println(stSort[i] + "这是stSort");
ascendInt[i] = list.indexOf(stSort[i]);
}
return ascendInt;
}
public int[] orderInt() {
order();
int[] ascendInt = new int[list.size()];
for (int i = 0; i < ascendInt.length; i++) {
ascendInt[i] = list.indexOf(stSort[i]);
}
return ascendInt;
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://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.springframework.web.reactive.socket.client;
import java.net.URI;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;
import reactor.netty5.http.client.HttpClient;
import reactor.netty5.http.client.WebsocketClientSpec;
import reactor.netty5.http.websocket.WebsocketInbound;
import org.springframework.core.io.buffer.Netty5DataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.socket.HandshakeInfo;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import org.springframework.web.reactive.socket.adapter.ReactorNetty2WebSocketSession;
/**
* {@link WebSocketClient} implementation for use with Reactor Netty for Netty 5.
*
* <p>This class is based on {@link ReactorNettyWebSocketClient}.
*
* @author Violeta Georgieva
* @since 6.0
*/
public class ReactorNetty2WebSocketClient implements WebSocketClient {
private static final Log logger = LogFactory.getLog(ReactorNetty2WebSocketClient.class);
private final HttpClient httpClient;
private final Supplier<WebsocketClientSpec.Builder> specBuilderSupplier;
@Nullable
private Boolean handlePing;
/**
* Default constructor.
*/
public ReactorNetty2WebSocketClient() {
this(HttpClient.create());
}
/**
* Constructor that accepts an existing {@link HttpClient} builder
* with a default {@link WebsocketClientSpec.Builder}.
* @since 5.1
*/
public ReactorNetty2WebSocketClient(HttpClient httpClient) {
this(httpClient, WebsocketClientSpec.builder());
}
/**
* Constructor that accepts an existing {@link HttpClient} builder
* and a pre-configured {@link WebsocketClientSpec.Builder}.
*/
public ReactorNetty2WebSocketClient(
HttpClient httpClient, Supplier<WebsocketClientSpec.Builder> builderSupplier) {
Assert.notNull(httpClient, "HttpClient is required");
Assert.notNull(builderSupplier, "WebsocketClientSpec.Builder is required");
this.httpClient = httpClient;
this.specBuilderSupplier = builderSupplier;
}
/**
* Return the configured {@link HttpClient}.
*/
public HttpClient getHttpClient() {
return this.httpClient;
}
/**
* Build an instance of {@code WebsocketClientSpec} that reflects the current
* configuration. This can be used to check the configured parameters except
* for sub-protocols which depend on the {@link WebSocketHandler} that is used
* for a given upgrade.
*/
public WebsocketClientSpec getWebsocketClientSpec() {
return buildSpec(null);
}
private WebsocketClientSpec buildSpec(@Nullable String protocols) {
WebsocketClientSpec.Builder builder = this.specBuilderSupplier.get();
if (StringUtils.hasText(protocols)) {
builder.protocols(protocols);
}
return builder.build();
}
@Override
public Mono<Void> execute(URI url, WebSocketHandler handler) {
return execute(url, new HttpHeaders(), handler);
}
@Override
public Mono<Void> execute(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) {
String protocols = StringUtils.collectionToCommaDelimitedString(handler.getSubProtocols());
WebsocketClientSpec clientSpec = buildSpec(protocols);
return getHttpClient()
.headers(nettyHeaders -> setNettyHeaders(requestHeaders, nettyHeaders))
.websocket(clientSpec)
.uri(url.toString())
.handle((inbound, outbound) -> {
HttpHeaders responseHeaders = toHttpHeaders(inbound);
String protocol = responseHeaders.getFirst("Sec-WebSocket-Protocol");
HandshakeInfo info = new HandshakeInfo(url, responseHeaders, Mono.empty(), protocol);
Netty5DataBufferFactory factory = new Netty5DataBufferFactory(outbound.alloc());
WebSocketSession session = new ReactorNetty2WebSocketSession(
inbound, outbound, info, factory, clientSpec.maxFramePayloadLength());
if (logger.isDebugEnabled()) {
logger.debug("Started session '" + session.getId() + "' for " + url);
}
return handler.handle(session).checkpoint(url + " [ReactorNetty2WebSocketClient]");
})
.doOnRequest(n -> {
if (logger.isDebugEnabled()) {
logger.debug("Connecting to " + url);
}
})
.next();
}
private void setNettyHeaders(HttpHeaders httpHeaders, io.netty5.handler.codec.http.headers.HttpHeaders nettyHeaders) {
httpHeaders.forEach(nettyHeaders::set);
}
private HttpHeaders toHttpHeaders(WebsocketInbound inbound) {
HttpHeaders headers = new HttpHeaders();
inbound.headers().iterator().forEachRemaining(entry ->
headers.add(entry.getKey().toString(), entry.getValue().toString()));
return headers;
}
}
|
package com.nosae.game.objects;
/**
* Created by eason on 2015/10/31.
*/
public class Life2 extends GameObj {
public int width = 0;
public int height = 0;
private int column = 5;
private static int mLife = 5;
public Life2(int destX, int destY, int destWidth, int destHeight, int srcX, int srcY, int srcWidth, int srcHeight, int speed, int color, int theta) {
super(destX, destY, destWidth, destHeight, srcX, srcY, srcWidth, srcHeight, speed, color, theta);
this.width = srcWidth;
this.height = srcHeight;
}
public static int getLife() {
return mLife;
}
public static void setLife(int mLife) {
Life2.mLife = mLife;
}
public static void addLife(int life) {
Life2.mLife += life;
if (Life2.mLife > 5)
Life2.mLife = 5;
else if (Life2.mLife < 0)
Life2.mLife = 0;
}
public void updateLife() {
// png 1~0
// index = getLife();
// png 0~9
if (getLife() == 0) {
index = 9;
} else {
index = getLife() - 1;
}
setAnimationIndex(column);
}
}
|
package com.myecommerce.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.myecommerce.dto.ResponseBody;
import com.myecommerce.entity.Subcategory;
import com.myecommerce.service.SubcategoryService;
@RestController
@RequestMapping("/myecommerce/subcategory")
public class SubcategoryController {
@Autowired
@Qualifier("subcategoryService")
private SubcategoryService service;
@PutMapping("")
public ResponseEntity<ResponseBody> insert(@RequestBody @Validated Subcategory subcategory) {
HttpHeaders header = new HttpHeaders();
header.add("request", "insertSubcategory");
return ResponseEntity.ok().headers(header).body(service.insert(subcategory));
}
@DeleteMapping("/{id}")
public ResponseEntity<ResponseBody> delete(@PathVariable("id") long id) {
HttpHeaders header = new HttpHeaders();
header.add("request", "deleteSubcategory");
return ResponseEntity.ok().headers(header).body(service.delete(id));
}
@GetMapping("/{id}")
public ResponseEntity<ResponseBody> getById(@PathVariable("id") long id) {
HttpHeaders header = new HttpHeaders();
header.add("request", "getSubcategoryById");
return ResponseEntity.ok().headers(header).body(service.get(id));
}
@GetMapping("/category/{idCategory}")
public ResponseEntity<ResponseBody> getByCommerce(@PathVariable("idCategory") long idCategory) {
HttpHeaders header = new HttpHeaders();
header.add("request", "getSubcategoriesByCategory");
return ResponseEntity.ok().headers(header).body(service.getByCategory(idCategory));
}
}
|
package com.jyn.masterroad.utils.retrofit.proxy;
import com.apkfuns.logutils.LogUtils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class RetrofitProxyTest {
public static final String TAG = "Retrofit";
public void proxyTest() {
RetrofitProxyInterface retrofitProxyInterface = new RetrofitProxyInterface() {
@Override
public void testFun(String testArgs) {
LogUtils.tag(TAG).i("这是一个RetrofitInterface的匿名内部实现类1 testArgs:" + testArgs);
}
@Override
public void testFun2(String testArgument) {
LogUtils.tag(TAG).i("这是一个RetrofitInterface的匿名内部实现类2 testArgument:" + testArgument);
}
};
Class<RetrofitProxyInterface> retrofitClass = RetrofitProxyInterface.class;
RetrofitProxyInterface retrofitProxyInterfaceProxy = (RetrofitProxyInterface) Proxy.newProxyInstance(
retrofitClass.getClassLoader(),
new Class<?>[]{retrofitClass},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
LogUtils.tag(TAG).i(" ---- 动态代理开始 ---- ");
Object invoke = method.invoke(retrofitProxyInterface, args); //指明代理对象
LogUtils.tag(TAG).i(" ---- 动态代理结束 ---- ");
return invoke;
}
});
retrofitProxyInterfaceProxy.testFun("哎,就是玩 testFun");
retrofitProxyInterfaceProxy.testFun2("哎,就是玩 testFun2");
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.log.pattern;
import xyz.noark.log.LogEvent;
/**
* 样式格式化接口
*
* @author 小流氓[176543888@qq.com]
* @since 3.4.3
*/
public interface PatternFormatter {
/**
* 是否需要配置includeLocation支持当前的Formatter
*
* @return 默认是不需要
*/
boolean isIncludeLocation();
/**
* 格式化一次日志记录
*
* @param event 日志记录
* @param toAppendTo 记录到哪里去
*/
void format(final LogEvent event, final StringBuilder toAppendTo);
}
|
package de.cuuky.varo.bot.discord.commands;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import de.cuuky.varo.Main;
import de.cuuky.varo.bot.discord.DiscordBotCommand;
import de.cuuky.varo.bot.discord.register.BotRegister;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
public class ShutdownCommand extends DiscordBotCommand {
/*
* OLD CODE
*/
public ShutdownCommand() {
super("shutdown", new String[] { "disconnect" }, "Fährt den Bot herunter.");
}
@SuppressWarnings("deprecation")
@Override
public void onEnable(String[] args, MessageReceivedEvent event) {
try {
if(BotRegister.getRegister(event.getAuthor()) == null) {
event.getTextChannel().sendMessage("Du musst mit dem Bot authentifiziert sein!").queue();
return;
}
BotRegister reg = BotRegister.getRegister(event.getAuthor());
try {
if(Bukkit.getOfflinePlayer(reg.getPlayerName()) == null) {
event.getTextChannel().sendMessage("Spieler nicht gefunden!").queue();
return;
}
} catch(NullPointerException e) {
return;
}
OfflinePlayer player = Bukkit.getOfflinePlayer(reg.getPlayerName());
if(!player.isOp()) {
event.getTextChannel().sendMessage("Dazu bist du nicht berechtigt!").queue();
return;
}
event.getTextChannel().sendMessage("Bye, bye.").queue();
Bukkit.getScheduler().scheduleSyncDelayedTask(Main.getInstance(), new Runnable() {
@Override
public void run() {
getDiscordBot().disconnect();
}
}, 20);
} catch(Exception e) {
super.getDiscordBot().disconnect();
}
}
}
|
package ru.job4j.profession;
public class Engineer extends Profession {
public String task;
public void setTask(String task) {
this.task = task;
}
}
|
package DesignPatterns.AbstractFactoryPattern;
public class ConcreteProductA2 implements ProductA {
@Override
public void aaa() {
System.out.println("AFP ConcreteProductA2 aaa");
}
}
|
package Scanning;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//import java.util.Scanner;
/*
Чётные и нечётные циферки
*/
public class Ex_6 {
public static int even;
public static int odd;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String w = reader.readLine();
int wSize = w.length();
int wInt = Integer.parseInt(w);
// Scanner scanner = new Scanner(System.in);
// int w = Integer.parseInt(scanner.next());
int z = (int)Math.pow(10,(wSize-1));
for(int i = 0; i < wSize; i++){
if((wInt / z) % 2 == 0 ){
even++;
}
else{
odd++;
}
z /= 10;
}
System.out.println("Even: " + even + " Odd: " + odd);
}
}
|
package de.example.simpleREST;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import de.example.simpleREST.model.ProdOrder;
import de.example.simpleREST.model.ProdOrderRepository;
import de.example.simpleREST.model.Product;
import de.example.simpleREST.model.ProductRepository;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ProdOrderTests {
@Autowired
ProductRepository productRepository;
@Autowired
ProdOrderRepository prodOrderRepository;
Product[] testProducts = {
new Product(null, "O1", new BigDecimal("10.50"), null, false),
new Product(null, "O2", new BigDecimal("20.30"), null, false)
};
<T> List<T> toList(Iterable<T> iterable) {
ArrayList<T> l = new ArrayList<>();
iterable.forEach(l::add);
return l;
}
@Test
@Order(0)
void create() {
List<Product> products = toList(productRepository.saveAll(Arrays.asList(testProducts)));
prodOrderRepository.save(new ProdOrder(null, "test@mail.com", null, products));
prodOrderRepository.save(new ProdOrder(null, "test2@mail.com", null, Arrays.asList(products.get(0))));
}
@Test
@Order(1)
@Transactional // Needed to access products collection without LazyLoad Exception
void totalAmount() {
List<ProdOrder> orders = toList(prodOrderRepository.findAll());
assertEquals(2, orders.size());
assertEquals(
testProducts[0].getPrice().add(testProducts[1].getPrice()),
orders.get(0).getTotalAmount());
}
@Test
@Order(2)
void rangeQuery() {
List<ProdOrder> ordersAll = toList(prodOrderRepository.findAll());
assertEquals(2, ordersAll.size(), "All Orders do not match");
List<ProdOrder> orders = toList(prodOrderRepository.findInRange(
LocalDateTime.now().minusHours(1), LocalDateTime.now().plusHours(1)));
assertEquals(2, orders.size(), "Range orders do not match");
List<ProdOrder> noOrders = toList(prodOrderRepository.findInRange(
LocalDateTime.now().minusHours(2), LocalDateTime.now().minusHours(1)));
assertEquals(0, noOrders.size());
}
}
|
package com.zenika.microservices.resanet.domain;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.TableGenerator;
import javax.persistence.Version;
@MappedSuperclass
public abstract class AbstractBusinessObject {
// Identifiant technique des objets métiers
//@Id
//@GeneratedValue(strategy = GenerationType.IDENTITY)
// Pour les TP sur l'héritage
@Id
// @TableGenerator(name = "myGenerator")
// @GeneratedValue(generator = "myGenerator")
@GeneratedValue
protected Long id;
// Numéro de version pour le verrouillage optimiste
@Version
protected int version;
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public int getVersion() {
return version;
}
private void setVersion(int version) {
this.version = version;
}
}
|
package org.bk.aws.junit5;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.testcontainers.containers.localstack.LocalStackContainer;
import org.testcontainers.containers.wait.strategy.WaitStrategy;
import org.testcontainers.utility.DockerImageName;
import software.amazon.awssdk.core.SdkSystemSetting;
import static org.testcontainers.containers.localstack.LocalStackContainer.Service.SNS;
import static org.testcontainers.containers.localstack.LocalStackContainer.Service.SQS;
public final class SnsAndSqsTestExtension implements BeforeAllCallback, AfterAllCallback {
private LocalStackContainer server;
private String snsEndpoint;
private String sqsEndpoint;
@Override
public void beforeAll(ExtensionContext context) {
System.setProperty(SdkSystemSetting.AWS_ACCESS_KEY_ID.property(), "access-key");
System.setProperty(SdkSystemSetting.AWS_SECRET_ACCESS_KEY.property(), "secret-key");
try {
this.server = new LocalStackContainer(DockerImageName.parse("localstack/localstack:0.12.12")).withServices(SNS, SQS);
this.server.start();
this.snsEndpoint = this.server.getEndpointConfiguration(SQS).getServiceEndpoint();
this.sqsEndpoint = this.server.getEndpointConfiguration(SQS).getServiceEndpoint();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void afterAll(ExtensionContext context) {
if (this.server == null) {
return;
}
try {
this.server.stop();
System.clearProperty(SdkSystemSetting.AWS_ACCESS_KEY_ID.property());
System.clearProperty(SdkSystemSetting.AWS_SECRET_ACCESS_KEY.property());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String getSnsEndpoint() {
return snsEndpoint;
}
public String getSqsEndpoint() {
return sqsEndpoint;
}
}
|
package client.view.theme;
import client.controller.Handler;
import models.Theme;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DialogChangeTheme {
private JDialog dialog = new JDialog();
private Handler handler;
public DialogChangeTheme(Handler handler) {
this.handler = handler;
}
public void change(int index){
dialog.setSize(400,500);
dialog.setLayout(new GridBagLayout());
dialog.setLocationRelativeTo(null);
JLabel numberLabel = new JLabel("Номер записи: ");
JTextField numberTextField = new JTextField(10);
dialog.add(numberLabel, new GridBagConstraints(0, 0, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
dialog.add(numberTextField, new GridBagConstraints(1, 0, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
JLabel themeLabel = new JLabel("Тема: ");
JTextField themeTextField = new JTextField(10);
dialog.add(themeLabel, new GridBagConstraints(0, 1, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
dialog.add(themeTextField, new GridBagConstraints(1, 1, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
JLabel titleLabel = new JLabel("Содержание: ");
JTextField titleTextField = new JTextField(10);
dialog.add(titleLabel, new GridBagConstraints(0, 2, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
dialog.add(titleTextField, new GridBagConstraints(1, 2, 1, 1, 1, 1,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
JButton changeNotation = new JButton("Изменить запись");
dialog.add(changeNotation, new GridBagConstraints(0, 6, 2, 1, 2, 2,
GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
dialog.pack();
dialog.setVisible(true);
changeNotation.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (numberTextField.getText().trim().isEmpty() || themeLabel.getText().trim().isEmpty() ||
titleLabel.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(new JFrame(), "Одно или несколько полей не заполнены");
return;
} else {
Theme theme = new Theme(themeTextField.getText(), titleTextField.getText());
handler.changeTheme(numberTextField.getText(), theme, String.valueOf(index));
JOptionPane.showMessageDialog(dialog, "Запись успешно изменена. Для продолжения работы нажмите \"ОК\"");
dialog.dispose();
}
}
});
}
}
|
package com.gamedev.model;
import com.gamedev.model.entity.Move;
import com.gamedev.model.entity.Player;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static com.gamedev.model.entity.Disc.*;
public class ReversiGame {
private int[][] board;
private Player currentPlayer;
private final int BOARD_SIZE = 8;
public ReversiGame() {
initGame();
currentPlayer = Player.BLACK;
}
public ReversiGame(int[][] board, Player currentPlayer) {
this.board = board;
this.currentPlayer = currentPlayer;
}
public void initGame() {
board = new int[BOARD_SIZE][BOARD_SIZE];
placeStartDiscs();
}
private void placeStartDiscs() {
board[3][3] = WHITE_DISC;
board[3][4] = BLACK_DISC;
board[4][3] = BLACK_DISC;
board[4][4] = WHITE_DISC;
}
public void placeDisc(Move move) {
if (move != null) {
int playerDisc = currentPlayer == Player.BLACK ? BLACK_DISC : WHITE_DISC;
int opponentDisc = currentPlayer == Player.BLACK ? WHITE_DISC : BLACK_DISC;
board[move.getRow()][move.getCol()] = playerDisc;
int[] directionsX = {-1, -1, -1, 0, 0, 1, 1, 1};
int[] directionsY = {-1, 0, 1, -1, 1, -1, 0, 1};
for (int i = 0; i < directionsX.length; i++) {
flipDiscsInDirection(playerDisc, opponentDisc, move, directionsX[i], directionsY[i]);
}
}
checkGameState();
}
private void checkGameState() {
if (getPossibleMoves(Player.BLACK).size() + getPossibleMoves(Player.WHITE).size() == 0) {
return;
}
if (getPossibleMoves(Player.BLACK).size() > 0 && getPossibleMoves(Player.WHITE).size() == 0) {
currentPlayer = Player.BLACK;
return;
}
if (getPossibleMoves(Player.BLACK).size() == 0 && getPossibleMoves(Player.WHITE).size() > 0) {
currentPlayer = Player.WHITE;
return;
}
passTurn();
}
private void flipDiscsInDirection(int player, int opponent, Move move, int directionX, int directionY) {
int i = move.getRow() + directionX;
int j = move.getCol() + directionY;
Set<Move> toFlip = new HashSet<>();
while (inBounds(i, j)) {
if (board[i][j] == opponent) {
toFlip.add(new Move(i, j));
} else if (board[i][j] == player) {
break;
} else {
toFlip.clear();
break;
}
i = i + directionX;
j = j + directionY;
}
if (!inBounds(i, j)) {
toFlip.clear();
}
for (Move markedMove : toFlip) {
board[markedMove.getRow()][markedMove.getCol()] = player;
}
}
private boolean inBounds(int i, int j) {
return ((i >= 0) && (i < 8) && (j >= 0) && (j < 8));
}
private void passTurn() {
currentPlayer = currentPlayer == Player.BLACK
? Player.WHITE
: Player.BLACK;
}
public Set<Move> getPossibleMoves(Player player) {
Set<Move> moves = new HashSet<>();
int playerDisc = (player == Player.BLACK) ? BLACK_DISC : WHITE_DISC;
int opponentDisc = (player == Player.BLACK) ? WHITE_DISC : BLACK_DISC;
for (int row = 0; row < BOARD_SIZE; row++)
for (int col = 0; col < BOARD_SIZE; col++) {
if (board[row][col] != EMPTY_DISC) continue;
int[] directionsX = {-1, -1, -1, 0, 0, 1, 1, 1};
int[] directionsY = {-1, 0, 1, -1, 1, -1, 0, 1};
for (int i = 0; i < directionsX.length; i++) {
if ((hasOpponentDiscInDirection(row + directionsX[i], col + directionsY[i], opponentDisc))
&& hasPlayerDiscInDirection(row, col, directionsX[i], directionsY[i], playerDisc))
moves.add(new Move(row, col));
}
}
return moves;
}
private boolean hasOpponentDiscInDirection(int row, int col, int opponentDisc) {
if ((row < 0 || row >= BOARD_SIZE) || (col < 0 || col >= BOARD_SIZE)) return false;
return board[row][col] == opponentDisc;
}
private boolean hasPlayerDiscInDirection(int row, int col, int directionX, int directionY, int playerDisc) {
int x = row + directionX;
int y = col + directionY;
while (true) {
x += directionX;
y += directionY;
if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE
|| board[x][y] == EMPTY_DISC || board[x][y] == BLACK_HOLE) break;
if (board[x][y] == playerDisc) return true;
}
return false;
}
public int getFrontierDiscsNumber(Player player) {
int frontierDiscs = 0;
int playerDisc = (player == Player.BLACK) ? BLACK_DISC : WHITE_DISC;
int opponentDisc = (player == Player.BLACK) ? WHITE_DISC : BLACK_DISC;
Set<Move> moves = getPlayerDiscs(playerDisc);
int[] directionsX = {-1, -1, -1, 0, 0, 1, 1, 1};
int[] directionsY = {-1, 0, 1, -1, 1, -1, 0, 1};
for (Move move : moves) {
int row = move.getRow();
int col = move.getCol();
for (int i = 0; i < directionsX.length; i++) {
if ((!hasOpponentDiscInDirection(row + directionsX[i], col + directionsY[i], opponentDisc))
&& !hasPlayerDiscInDirection(row, col, directionsX[i], directionsY[i], playerDisc))
frontierDiscs++;
}
}
return frontierDiscs;
}
public int getStableDiscsNumber(Player player) {
int playerDisc = (player == Player.BLACK) ? BLACK_DISC : WHITE_DISC;
int playerStableDiscs = 0;
int[] directionsX = {1, 1, -1, -1};
int[] directionsY = {1, -1, -1, 1};
int[][] corners = {{0, 0}, {0, 7}, {7, 7}, {7, 0}};
for (int i = 0; i < directionsX.length; i++) {
playerStableDiscs += stableDiscsFromCorner(corners[i], directionsX[i], directionsY[i], playerDisc);
}
return playerStableDiscs;
}
private int stableDiscsFromCorner(int[] corner, int directionsX, int directionsY, int playerDisc) {
int stableDiscs = 0;
for (int i = corner[0]; i < 8 && i > 0; i += directionsX) {
if (board[i][corner[1]] == playerDisc) {
for (int j = corner[1]; j < 8 && j > 0; j += directionsY) {
if (board[i][j] == playerDisc) {
stableDiscs++;
} else {
break;
}
}
} else {
break;
}
}
return stableDiscs;
}
private Set<Move> getPlayerDiscs(int playerDisc) {
Set<Move> moves = new HashSet<>();
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == playerDisc) {
moves.add(new Move(i, j));
}
}
}
return moves;
}
public void setBlackHole(Move blackHole) {
board[blackHole.getRow()][blackHole.getCol()] = BLACK_HOLE;
}
public boolean gameNotFinished() {
return getPossibleMoves(Player.BLACK).size() + getPossibleMoves(Player.WHITE).size() > 0;
}
public int[][] getGameBoardCopy() {
return Arrays.stream(board).map(int[]::clone).toArray(int[][]::new);
}
public Player getCurrentPlayer() {
return currentPlayer;
}
}
|
package slimeknights.tconstruct.library.tinkering;
import net.minecraft.item.ItemStack;
import java.util.List;
public interface IToolStationDisplay {
/**
* The "title" displayed in the GUI
* @deprecated Use getLocalizedName for consistency
*/
@Deprecated
String getLocalizedToolName();
/**
* The "title" displayed in the GUI
*/
default String getLocalizedName() {
return getLocalizedToolName();
}
/**
* Returns an List of Strings, where each String represents an information about the tool. Used to display
* Information about the item in the GUI
*/
List<String> getInformation(ItemStack stack);
}
|
package generic.wildcard;
public class CarWildcardSample {
public static void main(String[] ar) {
CarWildcardSample ex = new CarWildcardSample();
ex.callBoundedWildcardMethod();
ex.callBusBoundedWildcardMethod();
WildCardGeneric<Long> w = new WildCardGeneric("long");
Bus bus = new Bus("Toyota bus");
String result = ex.genericMethod(w, "WildCardGeneric", bus);
System.out.println(result);
}
public void callBoundedWildcardMethod() {
WildCardGeneric<Car> wildcard = new WildCardGeneric<Car>();
wildcard.setWildCard(new Car("Mustang"));
boundedWildcardMethod(wildcard);
// Car name = Mustang
}
/**
* Car class 와 Car class 를 상속받은 클래스가 param으로 올 수 있음
* @param c : Car or Car class's child class
*/
public void boundedWildcardMethod(WildCardGeneric<? extends Car> c) {
Car value = c.getWildCard();
System.out.println(value);
}
public void callBusBoundedWildcardMethod() {
WildCardGeneric<Bus> wildcard = new WildCardGeneric<Bus>();
wildcard.setWildCard(new Bus("7777"));
boundedWildcardMethod(wildcard);
// Bus name = 7777
}
public <S, T extends Car> S genericMethod(WildCardGeneric<?> c, S addValue1, T addValue2) {
System.out.println("##############genericMethod##############");
System.out.println(c.getWildCard());
System.out.println(String.valueOf(addValue1));
System.out.println(String.valueOf(addValue2));
System.out.println("##############genericMethod##############");
if (addValue1 instanceof String) { return (S) (addValue1 + " called"); } else { return addValue1; }
}
}
|
package be.odisee.pajotter.controller;
import be.odisee.pajotter.domain.*;
import be.odisee.pajotter.service.*;
import be.odisee.pajotter.utilities.RolNotFoundException;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/Pajotter")
public class PajotterController {
@Autowired
protected PajottersSessieService pajottersSessieService = null;
@Autowired
protected UserContextService userContextService = null;
//---------------------------------------------Antwoord-----------------------------------------------------------------
//lijst van alle antwoord
@RequestMapping(value={"/antwoordLijst.html"}, method = RequestMethod.GET)
public String indexAntwoord(ModelMap model){
Partij partij = userContextService.getAuthenticatedPersoon();
List<Antwoord> deLijst = pajottersSessieService.geefAlleAntwoorden(partij.getId(), "partij_id");
model.addAttribute("antwoord", deLijst);
return "/Pajotter/antwoordLijst";
}
//details van de producite
@RequestMapping(value={"/antwoord.html"}, method = RequestMethod.GET)
public String antwoordDetail(@RequestParam("id") Integer id, ModelMap model) {
Antwoord antwoord = pajottersSessieService.zoekAntwoordMetId(id);
model.addAttribute("antwoord", antwoord);
return "/Pajotter/antwoord";
}
//om een antwoord toe te voegen
@RequestMapping(value={"/nieuweAntwoord.html"}, method = RequestMethod.GET)
public String antwoordFormulier(ModelMap model) {
Antwoord antwoord = new Antwoord();
model.addAttribute("deantwoord", antwoord);
return "/Pajotter/nieuweAntwoord";
}
//om de antwoord te verwijderen
@RequestMapping(value={"/verwijderAntwoord.html"}, method = RequestMethod.GET)
public String antwoordDelete(@RequestParam("id") Integer id, ModelMap model) {
pajottersSessieService.verwijderAntwoord(id);
Partij partij = userContextService.getAuthenticatedPersoon();
List<Antwoord> deLijst = pajottersSessieService.geefAlleAntwoorden(partij.getId(), "partij_id");
model.addAttribute("antwoord", deLijst);
return "/Pajotter/antwoordLijst";
}
//om de antwoord up te daten
@RequestMapping(value={"/updateAntwoord.html"}, method = RequestMethod.POST)
public String antwoordUpdate(@ModelAttribute("deantwoord") @Valid Antwoord antwoord, BindingResult result, ModelMap model){
pajottersSessieService.updateAntwoord(antwoord);
model.addAttribute("antwoord", antwoord);
return "/Pajotter/antwoord";
}
//om naar de update pagina te gaan en de antwoord info mee te geven
@RequestMapping(value={"/updateAntwoord.html"}, method = RequestMethod.GET)
public String antwoordEditpagina(@RequestParam("id") Integer id, ModelMap model) {
Antwoord antwoord = pajottersSessieService.zoekAntwoordMetId(id);
model.addAttribute("deantwoord", antwoord);
return "/Pajotter/editAntwoord";
}
//nieuwe antwoord te maken
@RequestMapping(value={"/nieuweAntwoord.html"}, method = RequestMethod.POST)
public String producteiToevoegen(@ModelAttribute("deantwoord") @Valid Antwoord antwoord, @RequestParam("vraagid") Integer vraagid, BindingResult result, ModelMap model){
if (result.hasErrors()) return "/Pajotter/nieuweAntwoord";
//Partij partijDatVerzend = pajottersSessieService.zoekPartijMetId(PartijId);
Bericht oorsprongBericht = pajottersSessieService.zoekVraagMetId(vraagid);
Partij partijDatVerzend = userContextService.getAuthenticatedPersoon();
Antwoord toegevoegdAntwoord = pajottersSessieService.VoegAntwoordToe("actief",partijDatVerzend, oorsprongBericht,antwoord.getTekst());
System.out.println("DEBUG AntwoordGegevens Tekstst: " + antwoord.getTekst() );
return "redirect:/Pajotter/antwoord.html?id=" + toegevoegdAntwoord.getId();
}
//---------------------------------------------Vraag-----------------------------------------------------------------
//lijst van alle bestelling
@RequestMapping(value={"/index", "/vraagLijst.html"}, method = RequestMethod.GET)
public String indexVraag(ModelMap model){
Partij partij = userContextService.getAuthenticatedPersoon();
List<Vraag> deLijst = pajottersSessieService.geefAlleVraagen();
model.addAttribute("vraag", deLijst);
return "/Pajotter/vraagLijst";
}
//details van de producite
@RequestMapping(value={"/vraag.html"}, method = RequestMethod.GET)
public String vraagDetail(@RequestParam("id") Integer id, ModelMap model) {
Vraag vraag = pajottersSessieService.zoekVraagMetId(id);
Antwoord antwoord = pajottersSessieService.zoekAntwoordMetId(vraag.getId());
model.addAttribute("antwoord", antwoord);
model.addAttribute("vraag", vraag);
return "/Pajotter/vraag";
}
//om een vraag toe te voegen
@RequestMapping(value={"/nieuweVraag.html"}, method = RequestMethod.GET)
public String vraagFormulier(ModelMap model) {
Vraag vraag = new Vraag();
model.addAttribute("devraag", vraag);
return "/Pajotter/nieuweVraag";
}
//om de vraag te verwijderen
@RequestMapping(value={"/verwijderVraag.html"}, method = RequestMethod.GET)
public String vraagDelete(@RequestParam("id") Integer id, ModelMap model) {
pajottersSessieService.verwijderVraag(id);
Partij partij = userContextService.getAuthenticatedPersoon();
List<Vraag> deLijst = pajottersSessieService.geefAlleVraagen(partij.getId(), "partij_id");
model.addAttribute("vraag", deLijst);
return "/Pajotter/vraagLijst";
}
//om de vraag up te daten
@RequestMapping(value={"/beantwoordVraag.html"}, method = RequestMethod.POST)
public String vraagUpdate(@ModelAttribute("devraag") @Valid Vraag vraag, @RequestParam("antwoord") String antwoord, BindingResult result, ModelMap model){
//pajottersSessieService.updateVraag(vraag);
Bericht oorsprongBericht = pajottersSessieService.zoekVraagMetId(vraag.getId());
Partij partijDatVerzend = userContextService.getAuthenticatedPersoon();
System.out.println("Debug" + vraag.getId());
Antwoord toegevoegdAntwoord = pajottersSessieService.VoegAntwoordToe("beantwoord", partijDatVerzend, oorsprongBericht, antwoord);
model.addAttribute("vraag", vraag);
model.addAttribute("antwoord", toegevoegdAntwoord);
return "/Pajotter/vraag";
}
//om naar de update pagina te gaan en de vraag info mee te geven
@RequestMapping(value={"/beantwoordVraag.html"}, method = RequestMethod.GET)
public String vraagEditpagina(@RequestParam("id") Integer id, ModelMap model) {
Vraag vraag = pajottersSessieService.zoekVraagMetId(id);
Antwoord antwoord = pajottersSessieService.zoekAntwoordMetId(vraag.getId());
model.addAttribute("antwoord", antwoord);
model.addAttribute("devraag", vraag);
return "/Pajotter/beantwoordVraag";
}
//nieuwe vraag te maken
@RequestMapping(value={"/nieuweVraag.html"}, method = RequestMethod.POST)
public String producteiToevoegen(@ModelAttribute("devraag") @Valid Vraag vraag, BindingResult result, ModelMap model){
if (result.hasErrors()) return "/Pajotter/nieuweVraag";
//Partij partijDatVerzend = pajottersSessieService.zoekPartijMetId(PartijId);
Partij partijDatVerzend = userContextService.getAuthenticatedPersoon();
Vraag toegevoegdVraag = pajottersSessieService.VoegVraagToe("actief",partijDatVerzend, vraag.getTekst());
System.out.println("DEBUG VraagGegevens Tekstst: " + vraag.getTekst() );
return "redirect:/Pajotter/vraag.html?id=" + toegevoegdVraag.getId();
}
} |
package io.github.satr.aws.lambda.bookstore.entity.formatter;
import io.github.satr.aws.lambda.bookstore.entity.Book;
public class LexMessageFormatter extends MessageFormatter {
@Override
public String getBookFullDescription(Book book, String newLineDelimiter) {
StringBuilder builder = new StringBuilder();
builder.append(String.format(" Title: \"%s\"%s", book.getTitle(), newLineDelimiter));
builder.append(String.format(" Author: %s%s", book.getAuthor(), newLineDelimiter));
builder.append(String.format(" Issued: %s%s", book.getIssueYear(), newLineDelimiter));
builder.append(String.format(" ISBN: %s%s", book.getIsbn(), newLineDelimiter));
builder.append(String.format(" Price: %.2f%s", book.getPrice(), newLineDelimiter));
return builder.toString();
}
@Override
protected void addBookDescriptionToList(StringBuilder messageBuilder, Book book, boolean showBookNumber, int bookNumber, boolean withPrices) {
if (showBookNumber)
messageBuilder.append(String.format("%d. ", bookNumber));
messageBuilder.append(String.format("\"%s\" by %s", book.getTitle(), book.getAuthor()));
if(withPrices)
messageBuilder.append(String.format("; Price: %.2f", book.getPrice()));
messageBuilder.append("\n");
}
@Override
public String getPriceText(double price) {
return String.format("%.2f", price);
}
@Override
public String getShortBreak() {
return "";
}
}
|
package dev.mher.taskhunter.models;
import dev.mher.taskhunter.utils.DataSourceUtils;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* User: MheR
* Date: 12/4/19.
* Time: 9:54 PM.
* Project: taskhunter.
* Package: dev.mher.taskhunter.models.
*/
@Component
@Getter
@Setter
public class TaskModel {
private static final Logger logger = LoggerFactory.getLogger(TaskModel.class);
private Integer taskId;
private Integer projectId;
private Integer parentTaskId;
private String name;
private String text;
private Timestamp createdAt;
private Timestamp updatedAt;
private DataSource dataSource;
public TaskModel() {
}
@Autowired
public TaskModel(DataSource dataSource) {
this.dataSource = dataSource;
}
public TaskModel save() {
String queryString = "INSERT INTO tasks (project_id, parent_task_id, name, text)\n" +
"VALUES (?, ?, ?, ?)\n" +
"RETURNING task_id AS \"taskId\";";
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
con = dataSource.getConnection();
pst = con.prepareStatement(queryString);
pst.setInt(1, this.getProjectId());
pst.setObject(2, this.getParentTaskId());
pst.setString(3, this.getName());
pst.setString(4, this.getText());
rs = pst.executeQuery();
if (rs != null && rs.next()) {
this.setTaskId(rs.getInt("taskId"));
}
} catch (SQLException e) {
logger.info(e.getMessage());
logger.error(e.getMessage(), e);
} finally {
DataSourceUtils.closeConnection(con, pst, rs);
}
return this;
}
public List<TaskModel> list(Integer projectId, Integer limit, Integer offset) {
String queryString = "SELECT task_id AS \"taskId\",\n" +
" parent_task_id AS \"parentTaskId\",\n" +
" project_id AS \"projectId\",\n" +
" name,\n" +
" text,\n" +
" created_at AS \"createdAt\",\n" +
" updated_at AS \"updatedAt\"\n" +
"FROM tasks\n" +
"WHERE (?::INT IS NULL OR project_id=?) ORDER BY created_at DESC\n " +
"LIMIT ?\n" +
"OFFSET ?;";
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
List<TaskModel> tasks = new ArrayList<>();
try {
con = dataSource.getConnection();
pst = con.prepareStatement(queryString);
pst.setObject(1, projectId);
pst.setObject(2, projectId);
pst.setInt(3, limit);
pst.setInt(4, offset);
rs = pst.executeQuery();
if (rs != null) {
while (rs.next()) {
TaskModel task = new TaskModel();
task.setTaskId(rs.getInt("taskId"));
task.setProjectId(rs.getInt("projectId"));
task.setParentTaskId(rs.getInt("parentTaskId"));
task.setName(rs.getString("name"));
task.setText(rs.getString("text"));
task.setCreatedAt(rs.getTimestamp("createdAt"));
task.setUpdatedAt(rs.getTimestamp("updatedAt"));
tasks.add(task);
}
return tasks;
}
} catch (SQLException e) {
logger.info(e.getMessage());
logger.error(e.getMessage(), e);
} finally {
DataSourceUtils.closeConnection(con, pst, rs);
}
return tasks;
}
public TaskModel retrieve(Integer taskId) {
String queryString = "SELECT task_id AS \"taskId\",\n" +
" parent_task_id AS \"parentTaskId\",\n" +
" project_id AS \"projectId\",\n" +
" name,\n" +
" text,\n" +
" created_at AS \"createdAt\",\n" +
" updated_at AS \"updatedAt\"\n" +
"FROM tasks\n" +
"WHERE task_id=?;";
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
con = dataSource.getConnection();
pst = con.prepareStatement(queryString);
pst.setInt(1, taskId);
rs = pst.executeQuery();
if (rs != null && rs.next()) {
TaskModel task = new TaskModel();
task.setTaskId(rs.getInt("taskId"));
task.setProjectId(rs.getInt("projectId"));
task.setParentTaskId(rs.getInt("parentTaskId"));
task.setName(rs.getString("name"));
task.setText(rs.getString("text"));
task.setCreatedAt(rs.getTimestamp("createdAt"));
task.setUpdatedAt(rs.getTimestamp("updatedAt"));
return task;
}
} catch (SQLException e) {
logger.info(e.getMessage());
logger.error(e.getMessage(), e);
} finally {
DataSourceUtils.closeConnection(con, pst, rs);
}
return null;
}
public TaskModel update() {
String queryString = "UPDATE tasks\n" +
"SET project_id=?, parent_task_id=?, name=?, text=?, updated_at=?\n" +
"WHERE task_id=?;";
Connection con = null;
PreparedStatement pst = null;
boolean isUpdated = false;
try {
con = dataSource.getConnection();
pst = con.prepareStatement(queryString);
pst.setInt(1, this.getProjectId());
pst.setObject(2, this.getParentTaskId());
pst.setString(3, this.getName());
pst.setString(4, this.getText());
pst.setTimestamp(5, this.getUpdatedAt());
pst.setInt(6, this.getTaskId());
isUpdated = pst.executeUpdate() != 0;
if (isUpdated) {
return this;
}
} catch (SQLException e) {
logger.info(e.getMessage());
logger.error(e.getMessage(), e);
} finally {
DataSourceUtils.closeConnection(con, pst, null);
}
return null;
}
public boolean delete(TaskModel model) throws SQLException {
Connection conn = null;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
model.deleteSubTasks(conn);
model.deleteTaskById(conn);
conn.commit();
} catch (SQLException e) {
logger.error(e.getMessage());
logger.info(e.getMessage(), e);
if (conn != null) {
conn.rollback();
}
} finally {
DataSourceUtils.closeConnection(conn, null, null);
}
return true;
}
private boolean deleteSubTasks(Connection conn) throws SQLException {
boolean isInTransaction = conn != null;
if (!isInTransaction) {
conn = dataSource.getConnection();
}
String queryString = "DELETE FROM tasks WHERE parent_task_id=?;";
PreparedStatement pst = null;
boolean isDeleted = false;
try {
pst = conn.prepareStatement(queryString);
pst.setInt(1, this.getTaskId());
isDeleted = pst.execute();
if (isInTransaction) {
DataSourceUtils.closeConnection(null, pst, null);
}
} catch (SQLException e) {
logger.info(e.getMessage());
logger.error(e.getMessage(), e);
} finally {
if (!isInTransaction) {
DataSourceUtils.closeConnection(conn, pst, null);
}
}
return isDeleted;
}
private boolean deleteTaskById(Connection conn) throws SQLException {
boolean isInTransaction = conn != null;
if (!isInTransaction) {
conn = dataSource.getConnection();
}
String queryString = "DELETE FROM tasks WHERE task_id=?;";
PreparedStatement pst = null;
boolean isDeleted = false;
try {
pst = conn.prepareStatement(queryString);
pst.setInt(1, this.getTaskId());
isDeleted = pst.execute();
if (isInTransaction) {
DataSourceUtils.closeConnection(null, pst, null);
}
} catch (SQLException e) {
logger.info(e.getMessage());
logger.error(e.getMessage(), e);
} finally {
if (!isInTransaction) {
DataSourceUtils.closeConnection(conn, pst, null);
}
}
return isDeleted;
}
public List<TaskModel> listSubTasks(int taskId, int limit, int offset) {
String queryString = "SELECT task_id AS \"taskId\",\n" +
" parent_task_id AS \"parentTaskId\",\n" +
" project_id AS \"projectId\",\n" +
" name,\n" +
" text,\n" +
" created_at AS \"createdAt\",\n" +
" updated_at AS \"updatedAt\"\n" +
"FROM tasks\n" +
"WHERE parent_task_id=? ORDER BY created_at DESC \n" +
"LIMIT ?\n" +
"OFFSET ?;";
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
List<TaskModel> tasks = new ArrayList<>();
try {
con = dataSource.getConnection();
pst = con.prepareStatement(queryString);
pst.setInt(1, taskId);
pst.setInt(2, limit);
pst.setInt(3, offset);
rs = pst.executeQuery();
if (rs != null) {
while (rs.next()) {
TaskModel task = new TaskModel();
task.setTaskId(rs.getInt("taskId"));
task.setProjectId(rs.getInt("projectId"));
task.setParentTaskId(rs.getInt("parentTaskId"));
task.setName(rs.getString("name"));
task.setText(rs.getString("text"));
task.setCreatedAt(rs.getTimestamp("createdAt"));
task.setUpdatedAt(rs.getTimestamp("updatedAt"));
tasks.add(task);
}
return tasks;
}
} catch (SQLException e) {
logger.info(e.getMessage());
logger.error(e.getMessage(), e);
} finally {
DataSourceUtils.closeConnection(con, pst, rs);
}
return tasks;
}
}
|
/*implementation of stop(),sleep(),yield()*/
//public void stop(): is used to stop the thread(depricated).
//public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
//public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
class first extends Thread{
public void run(){
for(int i=1;i<5;i++){
System.out.println("thread first i="+i);
if(i==2) yield();
}
System.out.println("end of first");
}
}
class second extends Thread{
public void run(){
for(int i=1;i<5;i++){
System.out.println("thread second i="+i);
if(i==3) stop();
}
System.out.println("end of second");
}
}
class third extends Thread{
public void run(){
for(int i=1;i<5;i++){
System.out.println("thread third i="+i);
if(i==2) {
try{
sleep(1000);
}
catch(InterruptedException e){ //sleep() method throws InterruptedException.
}
}
}
}
}
public class stopandsleepandyieldmethodexample {
public static void main(String[] args) {
first obj1=new first();
second obj2=new second();
third obj3=new third();
obj1.start();
obj2.start();
obj3.start();
}
}
|
package com.tide.demo11;
public interface MyInterfaceB {
public abstract void methodB();
public abstract void method();
public default void methodDefaultAbs(){
System.out.println("洗澡");
}
}
|
package org.desertworkz.misc;
import java.util.HashMap;
public class Utils {
/**
* @param query the http uri query to be parsed
* @return Map object with key/value pairs according to query
*/
static public HashMap<String, String> parseQuery(String query){
// https://stackoverflow.com/a/17472462
// Example query: 'name=joe&age=10'
HashMap<String, String> result = new HashMap<>();
for (String param : query.split("&")) {
String[] entry = param.split("=");
if (entry.length > 1) {
result.put(entry[0], entry[1]);
}else{
result.put(entry[0], "");
}
}
return result;
}
}
|
public class ShortTermLease extends Lease
{
public int DailyCost;
public int howmanyday;
public Car car;
public ShortTermLease(){
}
public ShortTermLease(int modelyear,String brandandmodel,int Leasestart,int Leaseends,int Costinput) {
super(modelyear,brandandmodel,Leasestart,Leaseends,Costinput);
DailyCost=Costinput;
howmanyday=(Leaseends-Leasestart)+1;
}
public String show(String text)
{
text=newcar.carBrandModel+", is leased for "+(this.Leaseend-this.Leasestart+1)+" days.Daily cost is "+this.DailyCost+"$\n";
return text;
}
public int calculateInsurance()
{
//howmanyday*
return ((DailyCost)*15)/100;
}
}
|
package leader.view.component;
import leader.view.ViewUtil;
import javax.swing.*;
public class HeadingLabel extends JLabel {
public HeadingLabel(){
super();
setFont(ViewUtil.HEADING_FONT);
}
public HeadingLabel(String text){
this();
setText(text);
}
}
|
/**
* Created with IntelliJ IDEA.
* User: dexctor
* Date: 12-11-20
* Time: 上午10:59
* To change this template use File | Settings | File Templates.
*/
public class p1_2_3 {
public static void main(String[] args)
{
int N = StdIn.readInt();
double max = StdIn.readDouble();
double min = StdIn.readDouble();
Interval2D[] intervals = new Interval2D[N];
for(int i = 0; i < N; ++i)
{
double xmin = StdRandom.uniform(min,max);
double ymin = StdRandom.uniform(min,max);
double xmax = StdRandom.uniform(min,max);
double ymax = StdRandom.uniform(min,max);
if(xmin > xmax)
{
double tmp = xmin;
xmin = xmax;
xmax = tmp;
}
if(ymin > ymax)
{
double tmp = ymax;
ymax = ymin;
ymin = tmp;
}
Interval2D inter = new Interval2D(new Interval1D(xmin, xmax), new Interval1D(ymin, ymax));
intervals[i] = inter;
}
for(int i = 0; i < N; ++i)
{
for(int j = 0; j < N; ++j)
{
StdDraw.setXscale(min, max);
StdDraw.setYscale(min, max);
StdDraw.setPenRadius(0.001);
intervals[i].draw();
}
}
}
}
|
package com.uapp.useekr.adapters;
import android.support.design.widget.TextInputEditText;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.uapp.useekr.R;
import com.uapp.useekr.models.Task;
import java.util.List;
/**
* Created by root on 12/2/17.
*/
public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.ViewHolder> {
private List<Task> dataSet;
public TaskAdapter(List<Task> dataSet) {
this.dataSet = dataSet;
}
public List<Task> getDataSet() {
return dataSet;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowLayout = LayoutInflater.from(parent.getContext())
.inflate(R.layout.task_row, parent, false);
return new ViewHolder(rowLayout, new TaskTitleTextWatcher());
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Task task = dataSet.get(position);
holder.txtNumber.setText(String.valueOf(position + 1));
holder.editTitle.setText(task.getTitle());
holder.textWatcher.updatePosition(position);
}
@Override
public int getItemCount() {
return dataSet.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView txtNumber;
TextInputEditText editTitle;
TaskTitleTextWatcher textWatcher;
public ViewHolder(View itemView, TaskTitleTextWatcher textWatcher) {
super(itemView);
txtNumber = itemView.findViewById(R.id.edit_transaction_create_task_number);
editTitle = itemView.findViewById(R.id.edit_transaction_create_task_title);
editTitle.addTextChangedListener(textWatcher);
this.textWatcher = textWatcher;
}
}
class TaskTitleTextWatcher implements TextWatcher {
private int position;
void updatePosition(int position) {
this.position = position;
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
dataSet.get(position).setTitle(charSequence.toString());
}
@Override
public void afterTextChanged(Editable editable) {
}
}
}
|
package GUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
@SuppressWarnings("serial")
public class ATMScreen extends java.awt.Container {
public ATMScreen() {
//super();
super.setLayout(null);
}
/* add a screen element*/
public void add(ScreenElement ScreenEl) {
ScreenEl.setContainer(this);
}
/* Clear everything on the screen */
public void Clear() {
removeAll();
}
/* Paint the HR bank logo in the buttom right of the screen */
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
g.fillRoundRect(347,230,35,35,10,10);
g.fillRect(377, 260, 5, 5);
g.setColor(Color.WHITE);
g.setFont(new Font("SansSerif", Font.BOLD, 20));
g.drawString("HR", 350, 250);
g.setFont(new Font("SansSerif", Font.PLAIN, 12));
g.drawString("Bank", 351, 260);
}
}
|
package ch8;
public class ExceptionEx7 {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
try {
System.out.println(3);
System.out.println(0/0); //ArithmeticException 발생 -> 해당 인스턴스가 만들어짐
System.out.println(4); //실행 x
} catch (ArithmeticException ae) {
if(ae instanceof ArithmeticException) //ok
System.out.println("true"); //실행
System.out.println("ArithmeticException");
} catch(Exception e) {
System.out.println("Exception");
}
System.out.println(6);
}
}
|
/*
* Created on 20/08/2008
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.citibank.ods.entity.pl;
import java.util.Date;
import com.citibank.ods.entity.pl.valueobject.TplProdAssetEntityVO;
/**
* @author rcoelho
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class TplProdAssetEntity extends BaseTplProdAssetEntity {
/**
* Construtor padrão - sem argumentos
*/
public TplProdAssetEntity() {
m_data = new TplProdAssetEntityVO();
}
/**
* Construtor - Carrega os atributos com os atributos do movimento
*/
public TplProdAssetEntity(TplProdAssetMovEntity tplProdAssetMovEntity_,Date lastAuthDate_,
String lastAuthUserId_,String recStatCode_) {
m_data = new TplProdAssetEntityVO();
m_data.setProdAssetCode(tplProdAssetMovEntity_.getData().getProdAssetCode());
m_data.setProdAssetText(tplProdAssetMovEntity_.getData().getProdAssetText());
m_data.setAssetClassCustRptOrderNbr(tplProdAssetMovEntity_.getData().getAssetClassCustRptOrderNbr());
m_data.setLastUpdDate(tplProdAssetMovEntity_.getData().getLastUpdDate());
m_data.setLastUpdUserId(tplProdAssetMovEntity_.getData().getLastUpdUserId());
((TplProdAssetEntityVO) m_data).setLastAuthDate(lastAuthDate_);
((TplProdAssetEntityVO) m_data).setLastAuthUserId(lastAuthUserId_);
((TplProdAssetEntityVO) m_data).setRecStatCode(recStatCode_);
}
}
|
package parties;
/**
* Created by David on 10/04/2017.
*/
public enum TypeFantome {
ROUGE, BLEU;
}
|
package introexception;
public class SsnValidator {
public boolean validate(String socialSecurityNumber) {
if (socialSecurityNumber.length() < 9) {
return false;
}
try {
int sumValue = 0;
for (int i = 0; i < socialSecurityNumber.length() - 2; i++) {
int value = Integer.parseInt(Character.toString((socialSecurityNumber.charAt(i))));
sumValue += (i % 2 == 0 ? value * 7 : value * 3);
}
int validatorValue = Integer.parseInt(Character.toString((socialSecurityNumber.charAt(socialSecurityNumber.length() - 1))));
return validatorValue == sumValue % 10;
} catch (Exception ex) {
return false;
}
}
}
|
import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
String number = in.nextLine();
int digits[] = new int[number.length()];
for (int i = 0; i < number.length(); i++) {
digits[i] = number.charAt(i) - '0';
}
int answer = 1;
if (digits.length > 2) {
int nines = digits.length - 2;
while (nines > 0) {
answer *= 9;
nines--;
}
int currentMax = digits[0] * digits[1];
int beforeMax = 1;
if (digits[1] != 9) {
beforeMax *= (9 * Math.max(digits[0] - 1, 1));
}
answer *= Math.max(currentMax, beforeMax);
} else if (digits.length == 2) {
int currentMax = digits[0] * digits[1];
int beforeMax = 1;
if (digits[1] != 9) {
beforeMax *= (9 * Math.max(digits[0] - 1, 1));
}
answer = Math.max(currentMax, beforeMax);
} else {
answer = digits[0];
}
// for (int i = digits.length - 1; i > 0; i--) {
// if (digits[i] == 0 || digits[i] == -1) {
// digits[i] = 9;
// digits[i - 1]--;
// } else if (i > 1 && digits[i] < 9) {
// digits[i] = 9;
// digits[i - 1]--;
// }
// }
// for (int digit : digits) {
// if (digit == 0) continue;
// answer *= digit;
// out.print(digit + " ");
// }
// out.println();
out.println(answer);
in.close();
out.close();
}
} |
/*
* 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 cocktail.ui;
import cocktail.cbr.CocktailCase;
import java.awt.BorderLayout;
import java.awt.Container;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import jcolibri.cbrcore.CBRCase;
import jcolibri.method.retrieve.RetrievalResult;
/**
*
* @author visaac
*/
public class OutcomePanel extends javax.swing.JPanel {
private List<CaseRevisionPanel> casePanes = new ArrayList<>();
/**
* Creates new form QueryPanel
*/
public OutcomePanel() {
initComponents();
}
public void populateCases(List<CocktailCase> cases) {
jTabbedPane1.removeAll();
casePanes.clear();
for (int i = 0 ; i < cases.size() ; i++ ) {
CaseRevisionPanel crp = new CaseRevisionPanel(cases.get(i));
casePanes.add(crp);
jTabbedPane1.addTab(String.valueOf(i), crp);
}
}
public List<CBRCase> getCasesToRetain() {
List<CBRCase> casesToRetain = new ArrayList<>();
for (CaseRevisionPanel crp : casePanes) {
CBRCase caseForRetension = crp.getCaseForRetension();
if (caseForRetension != null) {
casesToRetain.add(caseForRetension);
}
}
return casesToRetain;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel8 = new javax.swing.JLabel();
jTabbedPane1 = new javax.swing.JTabbedPane();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel8.setText("<html>Please click on the settings options to customize your adaptation parameters and click on the refresh button below.</html>");
add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 400, 490, -1));
jTabbedPane1.setTabPlacement(javax.swing.JTabbedPane.BOTTOM);
add(jTabbedPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 30, 490, 350));
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel8;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration//GEN-END:variables
void reset() {
jTabbedPane1.removeAll();
}
}
|
package pl.pawel.weekop.controller;
import pl.pawel.weekop.model.User;
import pl.pawel.weekop.service.UserService;
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 java.io.IOException;
import java.util.Comparator;
import java.util.List;
@WebServlet("/userAdmin")
public class UserAdminServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
saveUserInRequst(request);
request.getRequestDispatcher("WEB-INF/userAdmin.jsp").forward(request,response);
}
private void saveUserInRequst(HttpServletRequest request) {
UserService userService = new UserService();
List<User> allUsers = userService.getAllUsers((u1, u2) -> u1.compareTo(u2));
/* List<User> allUsers = userService.getAllUsers(new Comparator<User>()
{
@Override
public int compare(User o1, User o2) {
return o1.compareTo(o2);
}
});*/
request.setAttribute("users", allUsers);
System.out.println(request.getAttribute("users"));
}
}
|
/**
*
*/
package com.isg.iloan.controller.functions.dataEntry;
import java.util.ArrayList;
import java.util.List;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Div;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Row;
import org.zkoss.zul.Tabbox;
import org.zkoss.zul.Tabs;
import org.zkoss.zul.Textbox;
import com.isg.iloan.commons.Labels;
import com.isg.iloan.validation.CheckboxValidator;
/**
* @author sheena.catacutan
*
*/
public class MyDeliveryPaymentInstructionsViewCtrl extends
GenericForwardComposer {
private Div ada_div;
private Checkbox ada;
private Checkbox office;
private Checkbox home;
private Textbox deliveryPlace;
private Textbox paymentMode;
private Checkbox cashcheck;
private Checkbox minAmountDue;
private Checkbox totalAmountDue;
private Row preferredPaymentRow;
private Row deliveryLocRow;
/**
*
*
*/
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
home.setChecked(true);
cashcheck.setChecked(true);
ada_div.setVisible(false);
minAmountDue.setChecked(true);
List<Component>toValidate = new ArrayList<Component>();
toValidate.add(deliveryLocRow);
toValidate.add(preferredPaymentRow);
addCheckboxEvent(comp, comp, toValidate);
bindValidationOnClick(deliveryLocRow);
}
@SuppressWarnings("unchecked")
private void bindValidationOnClick(Component comp){
Component parent = comp.getParent();
if(parent instanceof Tabbox){
for(Component c: parent.getChildren()){
if(c instanceof Tabs){
for(Component t :c.getChildren()){
if("deliveryInstruction".equals(t.getId())){
t.addEventListener(Events.ON_CLICK, new EventListener(){
public void onEvent(Event event){
List<Component>comps = new ArrayList<Component>();
comps.add(deliveryLocRow);
comps.add(preferredPaymentRow);
validateCheckboxFields(comps);
}
});
break;
}
}
}
}
return;
}
bindValidationOnClick(parent.getParent());
}
@SuppressWarnings("unchecked")
public static void addCheckboxEvent(final Component comp,
final Component parent, final List<Component> comps) {
if (comp instanceof Checkbox) {
comp.addEventListener(Events.ON_CLICK, new EventListener(){
public void onEvent(Event event){
validateCheckboxFields(comps);
}
});
}
List<Component> list = comp.getChildren();
for (Component child : list) {
addCheckboxEvent(child, parent, comps);
}
}
public static void validateCheckboxFields(List<Component> comps) {
boolean isValidated = true;
for (Component comp : comps) {
isValidated = CheckboxValidator.validateCheckboxes(CheckboxValidator.getCheckboxFields(comp,
new ArrayList<Checkbox>()));
if (!isValidated)break;
}
if (!isValidated) {
Clients.evalJavaScript("validatedState('#dpi',false)");
} else {
Clients.evalJavaScript("validatedState('#dpi',true)");
}
}
public void onCheck$office(){
home.setChecked(!office.isChecked());
deliveryPlace.setValue(office.isChecked()?office.getLabel():home.getLabel());
}
public void onCheck$home(){
office.setChecked(!home.isChecked());
deliveryPlace.setValue(home.isChecked()?home.getLabel():office.getLabel());
}
public void onCheck$ada(){
cashcheck.setChecked(!ada.isChecked());
paymentMode.setValue(ada.isChecked()?Labels.INS_ADA:Labels.INS_CASH_CHECK);
ada_div.setVisible(ada.isChecked());
// if(ada.isChecked()){
// Clients.evalJavaScript("smoothSlideDown('.ada_container')");
// }else{
// Clients.evalJavaScript("smoothSlideUp('.ada_container')");
// }
}
public void onCheck$cashcheck(){
ada.setChecked(!cashcheck.isChecked());
paymentMode.setValue(cashcheck.isChecked()?Labels.INS_CASH_CHECK:Labels.INS_ADA);
ada_div.setVisible(!cashcheck.isChecked());
// if(!cashcheck.isChecked()){
// Clients.evalJavaScript("smoothSlideDown('.ada_container')");
// }else{
// Clients.evalJavaScript("smoothSlideUp('.ada_container')");
// }
}
public void onCheck$minAmountDue(){
totalAmountDue.setChecked(!minAmountDue.isChecked());
}
public void onCheck$totalAmountDue(){
minAmountDue.setChecked(!totalAmountDue.isChecked());
}
}
|
package beakjoon6;
import java.util.Scanner;
public class Hw_2577 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a,b,c;
int[] count= new int[10];
do {
a=s.nextInt();
b=s.nextInt();
c=s.nextInt();
}while(!(a>=100&&a<1000&&b>=100&&b<1000&&c>=100&&c<1000));
String sum=(a*b*c)+"";
for(int i=0; i<sum.length(); i++) {
int n=Integer.parseInt(sum.substring(i, i+1));
count[n]++;
}
for(int i=0; i<count.length; i++) {
System.out.println(count[i]);
}
}
}
|
/* Copyright 2015 Esri
*
* 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.arcgis.android.samples.localdata.localrasterdata;
import android.view.View;
import android.widget.EditText;
/*
* Defines some commonly used constants and methods to handle EditText.
*/
public class EditTextUtils {
public final static double DEFAULT_DOUBLE_VALUE = Double.NEGATIVE_INFINITY;
public final static int DEFAULT_INT_VALUE = Integer.MIN_VALUE;
private EditTextUtils() {
throw new AssertionError();
}
public static double getEditTextValue(EditText text) {
double ret = DEFAULT_DOUBLE_VALUE;
String textString = text.getText().toString();
if (textString != null && textString.length() > 0) {
ret = Double.parseDouble(textString);
}
return ret;
}
public static void setEditTextValue(View view, int id, double value) {
if (value != EditTextUtils.DEFAULT_DOUBLE_VALUE) {
EditText editText = (EditText) view.findViewById(id);
if (editText != null) {
editText.setText(Double.toString(value));
}
}
}
}
|
/**
*
*/
package eu.fbk.dycapo.factories.json;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import eu.fbk.dycapo.exceptions.DycapoException;
import eu.fbk.dycapo.models.Participation;
import eu.fbk.dycapo.models.Person;
/**
* @author riccardo
*
*/
public abstract class ParticipationFetcher {
private static final String TAG = "ParticipationFetcher";
public static final Participation fetchParticipation(JSONObject jsonObject)
throws DycapoException {
Participation participation = new Participation();
if (jsonObject instanceof JSONObject)
Log.d(TAG, jsonObject.toString());
try {
Log.d(TAG, "participation : " + participation.toString());
if (jsonObject.has(DycapoObjectsFetcher.HREF)) {
participation.setHref(jsonObject
.getString(DycapoObjectsFetcher.HREF));
Log.d(TAG, participation.getHref());
}
if (jsonObject.has(Participation.STATUS)) {
participation.setStatus(jsonObject
.getString(Participation.STATUS));
Log.d(TAG, participation.getStatus());
}
if (jsonObject.has(Participation.AUTHOR)) {
participation.setAuthor(PersonFetcher.fetchPerson(jsonObject
.getJSONObject(Participation.AUTHOR)));
if (participation.getAuthor() instanceof Person)
Log.d(TAG, "Author fetched");
// Log.d(TAG, participation.getAuthor().toString());
}
// Log.d(TAG, "participation : " + participation.toString());
return participation;
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
return participation;
}
public static final List<Participation> fetchTripParticipations(
JSONArray json) throws DycapoException {
List<Participation> tparticipations = new ArrayList<Participation>();
try {
int size = json.length();
Log.d(TAG + ".fetchTripParticipations", "participations size : "
+ String.valueOf(size));
for (int i = 0; i < size; i++) {
Participation p = fetchParticipation(json.getJSONObject(i));
Log.d(TAG, "fetching : " + i + "-th participation");
tparticipations.add(p);
Log.d(TAG + ".fetchTripParticipations", "done!");
}
if (tparticipations.isEmpty())
Log.d(TAG + ".fetchTripParticipations", "empty list");
else
Log.d(TAG + ".fetchTripParticipations",
String.valueOf(tparticipations.size()));
return tparticipations;
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
return tparticipations;
}
}
|
import java.io.*;
class railfence
{
public static String encrypt(String plainText,int key)
{
int r = key;
int len = plainText.length();
int c;
if(len%2 == 0)
{
c = (len/key);
}
else
{
c = (len/key) + 1;
}
char mat[][] = new char[r][c];
int k = 0;
String cipherText = "";
for(int i = 0;i < c;i++)
{
for(int j = 0;j < r;j++)
{
if(k!=len)
mat[j][i] = plainText.charAt(k++);
else
mat[j][i] = ' ';
}
}
for(int i = 0;i < r;i++)
{
for(int j = 0;j < c;j++)
{
cipherText += mat[i][j];
}
}
return cipherText;
}
public static String decrypt(String cipherText,int depth)
{
int r=depth,len=cipherText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String plainText="";
for(int i = 0;i < r;i++)
{
for(int j = 0;j < c;j++)
{
mat[i][j] = cipherText.charAt(k++);
}
}
for(int i=0;i < c;i++)
{
for(int j=0;j < r;j++)
{
plainText+=mat[j][i];
}
}
return plainText;
}
public static void main(String args[]) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String text,text2;
int key = 2;
System.out.println("Enter string to encrpyt: ");
text = br.readLine();
System.out.println("\nText : " + text);
System.out.println("Key: " + key);
System.out.println("Cipher: " + encrypt(text, key));
System.out.println("Original string: " + decrypt(encrypt(text, key), key));
}
}
|
package projecteuler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DigitCancelingFractions {
public static void main(String args[]) throws IOException {
List<Integer> numerators = new ArrayList<Integer>();
List<Integer> denominators = new ArrayList<Integer>();
for (int i = 10; i <= 99; i++) {
for (int j = 10; j <= 99; j++) {
if (i / j < 1) {
numerators.add(i);
denominators.add(j);
}
}
}
System.out.println(numerators.size());
System.out.println(denominators.size());
System.out.println(numerators);
System.out.println(denominators);
double ans = calculatePandigitals(numerators, denominators);
System.out.println("Pandigital product is "+ans);
}
public static double calculatePandigitals(List<Integer> numerators,
List<Integer> denominators) {
int size = numerators.size();
double denominatorproduct = 1;
for (int i = 0; i < size; i++) {
int numfirst = numerators.get(i)/10;
int numsecond = numerators.get(i)%10;
int denfirst = denominators.get(i)/10;
int densecond = denominators.get(i)%10;
if(numsecond == denfirst && numfirst < densecond && numsecond > numfirst && denfirst > densecond ) {
denominatorproduct = denominatorproduct*densecond;
System.out.println("n1 " +numfirst);
System.out.println("n2 "+numsecond);
System.out.println("d1 "+denfirst);
System.out.println("d2 "+densecond);
}
}
return denominatorproduct;
}
}
|
package pl.ziemniakoss.orangeunit;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class MeetingPlannerTest {
private final MeetingPlanner meetingPlanner = new MeetingPlanner();
@ParameterizedTest
@ArgumentsSource(MeetingPlannerTestArgumentsProvider.class)
public void findPossibleMeetings(Calendar cal1, Calendar cal2, Duration duration, List<TimeInterval> expected) {
Collection<TimeInterval> result = meetingPlanner.findPossibleMeetings(cal1, cal2, duration);
assertEquals(expected, result);
}
} |
package model.DAO;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.DBConnection.DBConnection;
import model.object.Language;
import model.object.Publisher;
public class LaguageDAO {
public static List<Language> getListLanguage() {
String query = "select * from Language ";
try {
PreparedStatement preparedStatement = DBConnection.connect(query);
List<Language> list = new ArrayList<Language>();
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Language language = new Language();
language.setId(resultSet.getInt("id"));
language.setLanguage(resultSet.getString("language"));
list.add(language);
}
return list;
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static Boolean insertLanguage(Language language) {
String query = "insert into Language(language) values(?)";
try {
PreparedStatement preparedStatement = DBConnection.connect(query);
preparedStatement.setString(1, language.getLanguage());
return 1 == preparedStatement.executeUpdate();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
return false;
}
}
}
|
package com.zl.util;
/**
* @program: FruitSales
* @description: 与前台通信类
* @author: ZhuLlin
* @create: 2019-01-07 23:10
**/
public class MessageBean {
// 是否成功
private boolean success;
// 返回消息
private Object msg;
// 其他对象
private Object data;
public MessageBean(Object data) {
this.data = data;
}
public MessageBean(boolean success) {
this.success = success;
}
public MessageBean(boolean success, Object msg) {
this.success = success;
this.msg = msg;
}
public MessageBean(boolean success, Object msg, Object data) {
this.success = success;
this.msg = msg;
this.data = data;
}
public Object getdata() {
return data;
}
public void setdata(Object data) {
this.data = data;
}
public void setSuccess(boolean success) {
this.success = success;
}
public boolean getSuccess() {
return success;
}
public Object getMsg() {
return msg;
}
public void setMsg(Object msg) {
this.msg = msg;
}
}
|
package business.control;
import java.util.TreeSet;
import infra.IPersistence;
import util.InfraException;
public class DBConnectionController<E> {
private IPersistence<E> iPersistence;
public DBConnectionController(IPersistence<E> iPersistence) {
this.iPersistence = iPersistence;
}
public TreeSet<E> loadFromDatabase(String filename) {
try {
return iPersistence.loadUsers(filename);
} catch (InfraException e) {
System.out.print(e.getMessage());
// e.printStackTrace();
}
return null;
}
public void saveInDatabase(TreeSet<E> users, String filename) {
try {
iPersistence.saveUsers(users, filename);
} catch (InfraException e) {
System.out.print(e.getMessage());
// e1.printStackTrace();
}
}
}
|
package org.hpin.webservice.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hpin.common.core.orm.BaseService;
import org.hpin.common.util.DateUtils;
import org.hpin.webservice.bean.ReportCustomerInfo;
import org.hpin.webservice.dao.ReportCustomerInfoDao;
import org.hpin.webservice.util.Dom4jDealUtil;
import org.hpin.webservice.util.ReturnStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service(value="org.hpin.webservice.service.ReportCustomerInfoService")
@Transactional
public class ReportCustomerInfoService extends BaseService {
private static Logger log = Logger.getLogger("pushCustomerGenerCode"); //日志;
@Autowired
private ReportCustomerInfoDao reportCustomerInfoDao;
@SuppressWarnings("unchecked")
public String saveReportCustomerInfo(String xml) {
log.info("客户端接收数据-格式XML: " + xml);
String result = "";
String flag = "1"; //0:失败 1:成功
String message = "";
//空判断
try {
if(StringUtils.isNotEmpty(xml)) {
Map<String, String> mapValidateInfo = new HashMap<String, String>();
Map<String, String> mapCustomerList = new HashMap<String, String>();
mapValidateInfo.put("level", "2");
mapValidateInfo.put("params", "validateInfo");
mapCustomerList.put("level", "3");
mapCustomerList.put("params", "customerList");
List<Map<String, String>> params = new ArrayList<Map<String, String>>();
params.add(mapValidateInfo);
params.add(mapCustomerList);
Map<String, Object> objMap = Dom4jDealUtil.readStringXml2Out(xml, params);
ReportCustomerInfo reCusInfo = null;
if(objMap != null && !objMap.isEmpty()) {
mapValidateInfo = (Map<String, String>) objMap.get("validateInfo");
String accountName = mapValidateInfo.get("accountName");
String password = mapValidateInfo.get("password");
List<Map<String, String>> reCusInfos = (List<Map<String, String>>) objMap.get("customerList");
Map<String, String> map = null;
Map<String, String> judge = null;
/*
* 重复验证;
*/
for(int i=0; i< reCusInfos.size(); i++) {
map = reCusInfos.get(i);
//重复验证,当出现重复的时候跳过保存;
String reportId = (String)map.get("reportId");
String reportNum = (String)map.get("reportNum");
boolean isExist = this.reportCustomerInfoDao.findIsExcitByCondtions(reportId, reportNum);
if(isExist) {
flag = "0";
message = "该批次数据中部分数据在远盟数据库已存在!";
result = ReturnStringUtils.reportCustomerInfoResult(flag, message);
log.info("服务端返回数据-格式XML: " + result);
return result;
}
//在判断是否在该批次中重复;
for(int j=i+1; j<reCusInfos.size(); j++) {
judge = reCusInfos.get(j);
//重复验证,当出现重复的时候跳过保存;
String reportId2 = (String)judge.get("reportId");
String reportNum2 = (String)judge.get("reportNum");
if(reportId.equals(reportId2) && reportNum.equals(reportNum2)) {
flag = "0";
message = "该批次数据中存在重复的数据!";
result = ReturnStringUtils.reportCustomerInfoResult(flag, message);
log.info("服务端返回数据-格式XML: " + result);
return result;
}
}
}
/*
* 验证后数据保存;
*/
Map<String, String> mapData = null;
for (int i=0; i< reCusInfos.size(); i++) {
mapData = reCusInfos.get(i);
//重复验证,当出现重复的时候跳过保存;
String code = (String)mapData.get("code");
String name = (String)mapData.get("name");
String combo = (String)mapData.get("setmealName");
String reportLaunchDate = (String)mapData.get("reportDate");
//判断数据库是否重复;
reCusInfo = new ReportCustomerInfo();
reCusInfo.setBatch((String)mapData.get("batchNo"));
reCusInfo.setCode(code);
reCusInfo.setCombo(combo);
reCusInfo.setCreateTime(new Date());
reCusInfo.setCreateUserId("-1");
reCusInfo.setIsDeleted(0);
reCusInfo.setName(name);
reCusInfo.setPhone((String)mapData.get("phone"));
String receivedDate = (String)mapData.get("receiveDate");
Date receDate = null;
if(StringUtils.isNotEmpty(receivedDate)) {
receDate = DateUtils.convertDate(receivedDate, "yyyy-MM-dd");
}
reCusInfo.setReceivedDate(receDate);
reCusInfo.setReportAccountName(accountName);
reCusInfo.setReportAccountPass(password);
Date relancDate = null;
if(StringUtils.isNotEmpty(reportLaunchDate)) {
relancDate = DateUtils.convertDate(reportLaunchDate, "yyyy-MM-dd");
}
reCusInfo.setReportLaunchDate(relancDate);
reCusInfo.setSex((String)mapData.get("sex"));
/*
* * update henry.xu 2017-03-14
* 添加: reportId 报告ID; reportNum 报告编号; isSuccess 是否成功上传; 默认为-1, 成功为1, 失败为0
*/
reCusInfo.setReportId((String)mapData.get("reportId"));
reCusInfo.setReportNum((String)mapData.get("reportNum"));
reCusInfo.setIsSuccess(-1);
this.reportCustomerInfoDao.save(reCusInfo);
}
} else {
flag = "0";
message = "传入XML格式不符合约定!";
log.info("客户端传入数据处理格式不正确.");
}
} else {
flag = "0";
message = "传入的XML为空!";
log.info("客户端传入数据为空字符串.");
}
}catch(Exception e) {
flag = "0";
message = "传入XML格式不符合约定!";
log.error("数据处理", e);
}
result = ReturnStringUtils.reportCustomerInfoResult(flag, message);
log.info("服务端返回数据-格式XML: " + result);
return result;
}
}
|
package com.gsccs.sme.plat.corp.service;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gsccs.sme.plat.auth.dao.DictItemTMapper;
import com.gsccs.sme.plat.auth.model.DictItemT;
import com.gsccs.sme.plat.auth.service.AreaService;
import com.gsccs.sme.plat.svg.dao.CorpTMapper;
import com.gsccs.sme.plat.svg.dao.RegTypeTMapper;
import com.gsccs.sme.plat.svg.model.CorpT;
import com.gsccs.sme.plat.svg.model.CorpTExample;
import com.gsccs.sme.plat.svg.model.IndustryT;
import com.gsccs.sme.plat.svg.model.RegTypeT;
import com.gsccs.sme.plat.svg.model.RegTypeTExample;
import com.gsccs.sme.plat.svg.service.IndustryService;
@Service
public class CorpServiceImpl implements CorpService {
@Autowired
private CorpTMapper corpTMapper;
@Autowired
private DictItemTMapper dictItemTMapper;
@Autowired
private RegTypeTMapper regTypeTMapper;
@Autowired
private IndustryService industryService;
@Autowired
private AreaService areaService;
@Override
public Long addCorp(CorpT corpT) {
if (null != corpT) {
corpTMapper.insert(corpT);
return corpT.getId();
}
return null;
}
@Override
public CorpT getCorp(Long id) {
CorpT corp = corpTMapper.selectByPrimaryKey(id);
// 企业注册类型
if (StringUtils.isNotEmpty(corp.getRegtype())) {
DictItemT dictItemT = dictItemTMapper.selectByPrimaryKey(corp
.getRegtype());
if (null != dictItemT) {
corp.setRegtypestr(dictItemT.getTitle());
}
}
// 单位性质
if (StringUtils.isNotEmpty(corp.getNature())) {
DictItemT dictItemT = dictItemTMapper.selectByPrimaryKey(corp
.getNature());
if (null != dictItemT) {
corp.setNaturestr(dictItemT.getTitle());
}
}
return corp;
}
@Override
public List<CorpT> find(CorpT corpT, String order, int currPage,
int pageSize) {
CorpTExample example = new CorpTExample();
CorpTExample.Criteria criteria = example.createCriteria();
proSearchParam(corpT, criteria);
example.setCurrPage(currPage);
example.setPageSize(pageSize);
if (StringUtils.isNotEmpty(order)) {
example.setOrderByClause(order);
}else{
example.setOrderByClause("istop");
}
List<CorpT> corpTs = corpTMapper.selectPageByExample(example);
if (null != corpTs && corpTs.size()>0){
for (CorpT corp : corpTs) {
// 行业
if (null != corp.getHycode()) {
IndustryT industryT = industryService.findById(corp.getHycode());
if (null != industryT) {
corp.setHytypestr(industryT.getTitle());
}
}
// 企业注册类型
if (StringUtils.isNotEmpty(corp.getRegtype())) {
DictItemT dictItemT = dictItemTMapper.selectByPrimaryKey(corp
.getRegtype());
if (null != dictItemT) {
corp.setRegtypestr(dictItemT.getTitle());
}
}
// 单位性质
if (StringUtils.isNotEmpty(corp.getNature())) {
DictItemT dictItemT = dictItemTMapper.selectByPrimaryKey(corp
.getNature());
if (null != dictItemT) {
corp.setNaturestr(dictItemT.getTitle());
}
}
String areastr = "";
if (null != corp.getAcode()) {
areastr += areaService.getAreaStr(corp.getAcode());
} else if (null != corp.getCcode()) {
areastr += areaService.getAreaStr(corp.getCcode());
} else if (null != corp.getPcode()) {
areastr += areaService.getAreaStr(corp.getPcode());
}
String address = corp.getAddress() == null ? "" : corp
.getAddress();
areastr += address;
corp.setAreastr(areastr);
}
}
return corpTs;
}
@Override
public Integer count(CorpT corpT) {
CorpTExample example = new CorpTExample();
CorpTExample.Criteria criteria = example.createCriteria();
proSearchParam(corpT, criteria);
return corpTMapper.countByExample(example);
}
public void proSearchParam(CorpT corpT, CorpTExample.Criteria criteria) {
if (null != corpT) {
if (StringUtils.isNotEmpty(corpT.getTitle())) {
criteria.andTitleLike("%" + corpT.getTitle() + "%");
}
if (null != corpT.getOrgcode()) {
criteria.andOrgCodeEqualTo(corpT.getOrgcode());
}
if (null != corpT.getRegtype()) {
criteria.andRegtypeEqualTo(corpT.getRegtype());
}
if (null != corpT.getParkid()) {
criteria.andParkidEqualTo(corpT.getParkid());
}
if (null != corpT.getHycode()) {
criteria.andHycodeEqualTo(corpT.getHycode().toString());
}
if (null != corpT.getStatus()) {
criteria.andStatusEqualTo(corpT.getStatus());
}
}
}
public List<RegTypeT> findALL() {
RegTypeTExample example = new RegTypeTExample();
return regTypeTMapper.selectByExample(example);
}
@Override
public JSONArray findCorpTypeTree() {
List<RegTypeT> roots = findALL();
if (null != roots) {
JSONArray rootArray = (JSONArray) JSON.toJSON(roots);
return treeList(rootArray, 0l);
}
return null;
}
public JSONArray treeList(JSONArray nodeList, Long parentId) {
JSONArray nodearray = new JSONArray();
for (Object object : nodeList) {
JSONObject json = (JSONObject) JSON.toJSON(object);
long id = json.getLong("id");
long pid = json.getLong("parid");
json.put("text", json.get("title"));
if (parentId == pid) {
JSONArray subitems = treeList(nodeList, id);
json.put("children", subitems);
nodearray.add(json);
}
}
return nodearray;
}
@Override
public List<CorpT> find(CorpT corpT) {
CorpTExample example = new CorpTExample();
CorpTExample.Criteria criteria = example.createCriteria();
proSearchParam(corpT, criteria);
return corpTMapper.selectByExample(example);
}
@Override
public void updateCorp(CorpT corpT) {
if (null != corpT){
corpTMapper.updateByPrimaryKeyWithBLOBs(corpT);
}
}
}
|
package com.github.fly_spring.demo11.taskscheduler;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
System.out.println("Main Thread==========");
}
/*
每隔5秒执行一次:17:34:34
Main Thread==========
每隔5秒执行一次:17:34:39
每隔5秒执行一次:17:34:44
每隔5秒执行一次:17:34:49
每隔5秒执行一次:17:34:54
每隔5秒执行一次:17:34:59
在指定时间 17:35:00 执行!
每隔5秒执行一次:17:35:04
*/
}
|
package com.metoo.manage.seller.action;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.metoo.core.annotation.SecurityMapping;
import com.metoo.core.domain.virtual.SysMap;
import com.metoo.core.mv.JModelAndView;
import com.metoo.core.query.support.IPageList;
import com.metoo.core.security.support.SecurityUserHolder;
import com.metoo.core.tools.CommUtil;
import com.metoo.foundation.domain.Goods;
import com.metoo.foundation.domain.Store;
import com.metoo.foundation.domain.User;
import com.metoo.foundation.domain.query.GoodsQueryObject;
import com.metoo.foundation.service.IGoodsService;
import com.metoo.foundation.service.ISysConfigService;
import com.metoo.foundation.service.IUserConfigService;
import com.metoo.foundation.service.IUserService;
@Controller
public class ZtcSellerAction {
@Autowired
private ISysConfigService configService;
@Autowired
private IUserConfigService userConfigService;
@Autowired
private IGoodsService goodsService;
@Autowired
private IUserService userService;
@SecurityMapping(title = "直通车申请", value = "/seller/ztc_apply.htm*", rtype = "seller", rname = "竞价直通车", rcode = "ztc_seller", rgroup = "促销推广")
@RequestMapping("/seller/ztc_apply.htm")
public ModelAndView ztc_apply(HttpServletRequest request,
HttpServletResponse response) {
ModelAndView mv = new JModelAndView(
"user/default/sellercenter/ztc_apply.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
if (!this.configService.getSysConfig().isZtc_status()) {
mv = new JModelAndView(
"user/default/sellercenter/seller_error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request,
response);
mv.addObject("op_title", "系统未开启直通车");
mv.addObject("url", CommUtil.getURL(request) + "/seller/index.htm");
}
User user = this.userService.getObjById(SecurityUserHolder
.getCurrentUser().getId());
mv.addObject("user", user);
return mv;
}
@SecurityMapping(title = "直通车加载商品", value = "/seller/ztc_goods.htm*", rtype = "seller", rname = "竞价直通车", rcode = "ztc_seller", rgroup = "促销推广")
@RequestMapping("/seller/ztc_goods.htm")
public ModelAndView ztc_goods(HttpServletRequest request,
HttpServletResponse response, String goods_name, String currentPage) {
ModelAndView mv = new JModelAndView(
"user/default/sellercenter/ztc_goods.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
User user = this.userService.getObjById(SecurityUserHolder
.getCurrentUser().getId());
user = user.getParent() == null ? user : user.getParent();
Store store = user.getStore();
GoodsQueryObject qo = new GoodsQueryObject();
qo.setCurrentPage(CommUtil.null2Int(currentPage));
if (!CommUtil.null2String(goods_name).equals("")) {
qo.addQuery("obj.goods_name", new SysMap("goods_name", "%"
+ CommUtil.null2String(goods_name) + "%"), "like");
}
qo.addQuery("obj.goods_store.id",
new SysMap("store_id", store.getId()), "=");
qo.addQuery("obj.goods_status", new SysMap("goods_status", 0), "=");
qo.addQuery("obj.ztc_status", new SysMap("ztc_status", 0), "<=");
qo.addQuery("obj.ztc_status", new SysMap("ztc_status2", -1), ">=");
qo.setPageSize(15);
IPageList pList = this.goodsService.list(qo);
CommUtil.saveIPageList2ModelAndView(CommUtil.getURL(request)
+ "/seller/ztc_goods.htm", "", "&goods_name=" + goods_name,
pList, mv);
return mv;
}
@SecurityMapping(title = "直通车申请保存", value = "/seller/ztc_apply_save.htm*", rtype = "seller", rname = "竞价直通车", rcode = "ztc_seller", rgroup = "促销推广")
@RequestMapping("/seller/ztc_apply_save.htm")
public String ztc_apply_save(HttpServletRequest request,
HttpServletResponse response, String goods_id, String ztc_price,
String ztc_begin_time, String ztc_gold, String ztc_session) {
String url = "redirect:/seller/ztc_apply.htm";
if (!this.configService.getSysConfig().isZtc_status()) {
request.getSession(false).setAttribute("url",
CommUtil.getURL(request) + "/seller/ztc_apply.htm");
request.getSession(false).setAttribute("op_title", "系统未开启直通车");
url = "redirect:/seller/error.htm";
} else {
Goods goods = this.goodsService.getObjById(CommUtil
.null2Long(goods_id));
goods.setZtc_status(1);
goods.setZtc_pay_status(1);
goods.setZtc_begin_time(CommUtil.formatDate(ztc_begin_time));
goods.setZtc_gold(CommUtil.null2Int(ztc_gold));
goods.setZtc_price(CommUtil.null2Int(ztc_price));
goods.setZtc_apply_time(new Date());
this.goodsService.update(goods);
request.getSession(false).setAttribute("url",
CommUtil.getURL(request) + "/seller/ztc_list.htm");
request.getSession(false).setAttribute("op_title", "直通车申请成功,等待审核");
url = "redirect:/seller/success.htm";
}
return url;
}
@SecurityMapping(title = "直通车申请列表", value = "/seller/ztc_apply_list.htm*", rtype = "seller", rname = "竞价直通车", rcode = "ztc_seller", rgroup = "促销推广")
@RequestMapping("/seller/ztc_apply_list.htm")
public ModelAndView ztc_apply_list(HttpServletRequest request,
HttpServletResponse response, String currentPage, String goods_name) {
ModelAndView mv = new JModelAndView(
"user/default/sellercenter/ztc_apply_list.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
if (!this.configService.getSysConfig().isZtc_status()) {
mv = new JModelAndView(
"user/default/sellercenter/seller_error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request,
response);
mv.addObject("op_title", "系统未开启直通车");
mv.addObject("url", CommUtil.getURL(request) + "/seller/index.htm");
} else {
GoodsQueryObject qo = new GoodsQueryObject(currentPage, mv,
"ztc_begin_time", "desc");
qo.addQuery("obj.goods_store.user.id", new SysMap("user_id",
SecurityUserHolder.getCurrentUser().getId()), "=");
qo.addQuery("obj.ztc_status", new SysMap("ztc_status", 1), "=");
if (!CommUtil.null2String(goods_name).equals("")) {
qo.addQuery("obj.goods_name", new SysMap("goods_name", "%"
+ goods_name.trim() + "%"), "like");
}
IPageList pList = this.goodsService.list(qo);
CommUtil.saveIPageList2ModelAndView("", "", "", pList, mv);
mv.addObject("goods_name", goods_name);
}
return mv;
}
@SecurityMapping(title = "直通车商品列表", value = "/seller/ztc_list.htm*", rtype = "seller", rname = "竞价直通车", rcode = "ztc_seller", rgroup = "促销推广")
@RequestMapping("/seller/ztc_list.htm")
public ModelAndView ztc_list(HttpServletRequest request,
HttpServletResponse response, String currentPage, String goods_name) {
ModelAndView mv = new JModelAndView(
"user/default/sellercenter/ztc_list.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
if (!this.configService.getSysConfig().isZtc_status()) {
mv = new JModelAndView(
"user/default/sellercenter/seller_error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request,
response);
mv.addObject("op_title", "系统未开启直通车");
mv.addObject("url", CommUtil.getURL(request) + "/seller/index.htm");
} else {
GoodsQueryObject qo = new GoodsQueryObject(currentPage, mv,
"ztc_apply_time", "desc");
qo.addQuery("obj.goods_store.user.id", new SysMap("user_id",
SecurityUserHolder.getCurrentUser().getId()), "=");
qo.addQuery("obj.ztc_status", new SysMap("ztc_status", 2), ">=");
if (!CommUtil.null2String(goods_name).equals("")) {
qo.addQuery("obj.goods_name", new SysMap("goods_name", "%"
+ goods_name.trim() + "%"), "like");
}
IPageList pList = this.goodsService.list(qo);
CommUtil.saveIPageList2ModelAndView("", "", "", pList, mv);
}
return mv;
}
@SecurityMapping(title = "直通车申请查看", value = "/seller/ztc_apply_view.htm*", rtype = "seller", rname = "竞价直通车", rcode = "ztc_seller", rgroup = "促销推广")
@RequestMapping("/seller/ztc_apply_view.htm")
public ModelAndView ztc_apply_view(HttpServletRequest request,
HttpServletResponse response, String id) {
ModelAndView mv = new JModelAndView(
"user/default/sellercenter/ztc_apply_view.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
if (!this.configService.getSysConfig().isZtc_status()) {
mv = new JModelAndView(
"user/default/sellercenter/seller_error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request,
response);
mv.addObject("op_title", "系统未开启直通车");
mv.addObject("url", CommUtil.getURL(request) + "/seller/index.htm");
} else {
Goods obj = this.goodsService.getObjById(CommUtil.null2Long(id));
if (obj.getGoods_store().getUser().getId()
.equals(SecurityUserHolder.getCurrentUser().getId())) {
mv.addObject("obj", obj);
} else {
mv = new JModelAndView(
"user/default/sellercenter/seller_error.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request,
response);
mv.addObject("op_title", "参数错误,不存在该直通车信息");
mv.addObject("url", CommUtil.getURL(request)
+ "/seller/ztc_list.htm");
}
}
return mv;
}
}
|
package br.com.mixfiscal.prodspedxnfe.services.ex;
public class DadosNFeNaoCarregadosException extends Exception {
public DadosNFeNaoCarregadosException() {
super();
}
public DadosNFeNaoCarregadosException(String message) {
super(message);
}
public DadosNFeNaoCarregadosException(Throwable cause) {
super(cause);
}
public DadosNFeNaoCarregadosException(String message, Throwable cause) {
super(message, cause);
}
}
|
package com.hamatus.web.rest.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by stefan.chapuis on 06.11.2015.
*/
public class ImageUtil {
private static final Logger log = LoggerFactory.getLogger(ImageUtil.class);
public static byte[] resizeAndCropImage(byte[] sourceImage, String imageFormatName, Integer width, Integer height) throws IOException {
InputStream inputStream = new ByteArrayInputStream(sourceImage);
//read image
BufferedImage bufferedImage = ImageIO.read(inputStream);
//trim image (remove not used area of paperjs)
bufferedImage = trimImage(bufferedImage);
//resize image
bufferedImage = resizeImage(bufferedImage, width, height);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, imageFormatName, byteArrayOutputStream);
byteArrayOutputStream.flush();
byte[] imageData = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
return imageData;
}
public static byte[] cropImage(byte[] sourceImage, String imageFormatName) throws IOException {
InputStream inputStream = new ByteArrayInputStream(sourceImage);
//read image
BufferedImage bufferedImage = ImageIO.read(inputStream);
//trim image (remove not used area of paperjs)
bufferedImage = trimImage(bufferedImage);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, imageFormatName, byteArrayOutputStream);
byteArrayOutputStream.flush();
byte[] imageData = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
return imageData;
}
private static BufferedImage trimImage(BufferedImage img) {
final byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
int width = img.getWidth();
int height = img.getHeight();
int x0, y0, x1, y1; // the new corners of the trimmed image
int i, j; // i - horizontal iterator; j - vertical iterator
leftLoop:
for (i = 0; i < width; i++) {
for (j = 0; j < height; j++) {
if (pixels[(j * width + i) * 4] != 0) { // alpha is the very first byte and then every fourth one
break leftLoop;
}
}
}
x0 = i;
topLoop:
for (j = 0; j < height; j++) {
for (i = 0; i < width; i++) {
if (pixels[(j * width + i) * 4] != 0) {
break topLoop;
}
}
}
y0 = j;
rightLoop:
for (i = width - 1; i >= 0; i--) {
for (j = 0; j < height; j++) {
if (pixels[(j * width + i) * 4] != 0) {
break rightLoop;
}
}
}
x1 = i + 1;
bottomLoop:
for (j = height - 1; j >= 0; j--) {
for (i = 0; i < width; i++) {
if (pixels[(j * width + i) * 4] != 0) {
break bottomLoop;
}
}
}
y1 = j + 1;
return img.getSubimage(x0, y0, x1 - x0, y1 - y0);
}
private static BufferedImage resizeImage(BufferedImage originalImage, Integer width, Integer height) {
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
//*Special* if the width or height is 0 use image src dimensions
if (width == 0) {
width = originalImage.getWidth();
}
if (height == 0) {
height = originalImage.getHeight();
}
log.debug("source image {} / {}", originalImage.getHeight(), originalImage.getWidth());
log.debug("dest dim {} / {}", height, width);
int fHeight = height;
int fWidth = width;
//Work out the resized width/height
if (originalImage.getHeight() > height || originalImage.getWidth() > width) {
fHeight = height;
int wid = width;
float sum = (float) originalImage.getWidth() / (float) originalImage.getHeight();
fWidth = Math.round(fHeight * sum);
if (fWidth > wid) {
//rezise again for the width this time
fHeight = Math.round(wid / sum);
fWidth = wid;
}
log.debug("make it smaller");
log.debug("resize values {} / {} ",fWidth, fHeight);
BufferedImage resizedImage = new BufferedImage(fWidth, fHeight, type);
Graphics2D g = resizedImage.createGraphics();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(originalImage, 0, 0, fWidth, fHeight, null);
g.dispose();
return resizedImage;
}
else{
log.debug("make it not smaller");
}
return originalImage;
}
}
|
package com.gymteam.tom.gymteam.model;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by tomshabtay on 18/08/2017.
*/
public class Gym {
private String name;
private String address;
public HashMap<String,User> usersInGym;
public ArrayList<WorkoutInvite> workoutInvites;
public HashMap<String, User> getUsersInGym() {
return usersInGym;
}
public void setUsersInGym(HashMap<String, User> usersInGym) {
this.usersInGym = usersInGym;
}
public Gym(String name){
this.name = name;
this.address = "";
usersInGym = new HashMap<>();
workoutInvites = new ArrayList<>();
}
public Gym(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public ArrayList<WorkoutInvite> getWorkoutInvites() {
return workoutInvites;
}
public void setWorkoutInvites(ArrayList<WorkoutInvite> workoutInvites) {
this.workoutInvites = workoutInvites;
}
}
|
import java.util.Arrays;
public class ComparableRectangle implements Comparable<ComparableRectangle>{
private double lenght;
private double width;
// Argument constructor
public ComparableRectangle(double lenght, double width){
this.lenght=lenght;
this.width=width;
}
public double getArea(){
return lenght*width;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ComparableRectangle myRec = new ComparableRectangle(4,5);
// myRec is bigger than the anonymous rectangle
System.out.println(myRec.compareTo(new ComparableRectangle(3,3)));
// Creating an array and the sort method will use compareTo to sort them
ComparableRectangle rectangles[] = {new ComparableRectangle(2,4),new ComparableRectangle(1,1)
,new ComparableRectangle(3,2),new ComparableRectangle(1,7),new ComparableRectangle(6,6)};
//sort uses compareTo method to sort the array
Arrays.sort(rectangles);
for(ComparableRectangle e : rectangles){
System.out.println(e.toString());
}
}
// this method is defined in the Comparable interface
@Override
public int compareTo(ComparableRectangle o) {
if(getArea()>o.getArea())
return 1;
else if(getArea()<o.getArea())
return -1;
else
return 0;
}
@Override
public String toString(){
return "Rectangle with area of "+getArea();
}
}
|
package com.rengu.operationsoanagementsuite.Configuration;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationConfiguration {
// Device 通信端口
public static final int deviceUDPPort = 3087;
public static final int deviceTCPPort = 3088;
private String defultUsername = "admin";
private String defultPassword = "admin";
private String componentLibraryName = "lib";
private String jsonFileName = "export.json";
private String compressFileName = "ExportComponent.zip";
private int hearbeatSendPort = 3086;
private int hearbeatReceivePort = 6004;
private int tcpReceivePort = 6005;
private int deviceLogoutDelay = 3;
// 组件部署参数
private int socketTimeout = 1000;
private int maxWaitTimes = 10;
private int maxRetryTimes = 5;
// 不可修改项-自动从运行环境获取
private String componentLibraryPath = "";
public String getDefultUsername() {
return defultUsername;
}
public String getDefultPassword() {
return defultPassword;
}
public String getComponentLibraryName() {
return componentLibraryName;
}
public String getJsonFileName() {
return jsonFileName;
}
public String getCompressFileName() {
return compressFileName;
}
public int getHearbeatSendPort() {
return hearbeatSendPort;
}
public int getHearbeatReceivePort() {
return hearbeatReceivePort;
}
public int getTcpReceivePort() {
return tcpReceivePort;
}
public int getDeviceLogoutDelay() {
return deviceLogoutDelay;
}
public int getSocketTimeout() {
return socketTimeout;
}
public int getMaxWaitTimes() {
return maxWaitTimes;
}
public int getMaxRetryTimes() {
return maxRetryTimes;
}
public String getComponentLibraryPath() {
return componentLibraryPath;
}
public void setComponentLibraryPath(String componentLibraryPath) {
this.componentLibraryPath = componentLibraryPath;
}
} |
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Net-Világ Szervíz
*/
public class haromszog extends javax.swing.JFrame {
/**
* Creates new form haromszog
*/
public haromszog() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("beolvas");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
jButton1MousePressed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(109, 109, 109)
.addComponent(jButton1)
.addContainerGap(222, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jButton1)
.addContainerGap(257, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MousePressed
try {
String seged[] = new String[3000];
File fajl = new File("haromszogek.txt");
Scanner be = new Scanner(fajl);
int n = 0;
String sor = " ";
while (be.hasNextLine()) {
sor = be.nextLine();
n++;
System.out.println(sor);
}
be.close();
//split
double aoldal[] = new double[1000];
double boldal[] = new double[1000];
double coldal[] = new double[1000];
int a=0;
int b=0;
int c=0;
double oldalk[][]=new double[1000][3];
for (int i = 0; i < n; i++) {
seged=sor.split(" ");
oldalk[n][0]=Double.parseDouble(seged[0].replace(',', '.'));a++;
oldalk[n][1]=Double.parseDouble(seged[1].replace(',', '.'));b++;
oldalk[n][2]=Double.parseDouble(seged[2].replace(',', '.'));c++;
}
for (int i = 0; i < n; i++) {
System.out.println(oldalk[a][0]);
}
} catch (IOException ioe) {
}
}//GEN-LAST:event_jButton1MousePressed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(haromszog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(haromszog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(haromszog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(haromszog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new haromszog().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
// End of variables declaration//GEN-END:variables
}
|
package com.hwy.study01.common.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* @Description 学生类
* @Author yanghanwei
* @Mail yanghanwei@geotmt.com
* @Date 15:36 2019-10-29
* @Version v1
**/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Cloneable{
private String name;
private Integer age;
/**
* 选修课
*/
private Subject subject;
@Override
public Object clone() {
//浅拷贝
try {
// 直接调用父类的clone()方法
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
public static void main(String[] args) {
Subject subject = new Subject("qwe", "t1");
Student student = new Student("zhangsan",18, subject);
System.out.println(subject);
System.out.println(student.getSubject());
}
}
|
package com.lesports.airjordanplayer.data;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import com.lesports.airjordanplayer.utils.NetworkUtil;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Serializable;
/**
* Created by litzuhsien on 4/7/15.
*/
public class DeviceInfo implements Serializable {
private static final String DEFAULT_FAKE_IP_ADDRESS = "123.126.32.246";
private String hardwareInfo;
private String systemType;
private String systemVersion;
private String moduleVersion;
private String macAddress;
private String currentIPAddress;
private Context mContext;
public DeviceInfo(Context context) {
super();
mContext = context;
this.hardwareInfo = Build.MODEL; // ipad/iphone;S1/S3/T1/T2/C1/C1S;X40/X60/un 不清楚请填un // TODO: 硬件信息完善?
this.systemType = "android"; // macos/android/windows/linux/un 不清楚请填un
this.systemVersion = Build.VERSION.RELEASE;
this.moduleVersion = "1.0.0";
this.macAddress = captureMacAddress();
this.currentIPAddress = NetworkUtil.captureCurrentIPAddress();
}
public String captureMacAddress() {
String macSerial = null;
String str = "";
try {
Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (; null != str;) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();
break;
}
}
} catch (IOException ex) {
macSerial = "FF:FF:FF:FF";
ex.printStackTrace();
}
if(null == macSerial)
macSerial = captureMacAddressWifi();
return macSerial;
}
private String captureMacAddressWifi(){
WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = (wifi != null) ? wifi.getConnectionInfo() : null;
return (info != null) ? info.getMacAddress() : null;
}
public String getHardwareInfo() {
return hardwareInfo;
}
public String getSystemType() {
return systemType;
}
public String getSystemVersion() {
return systemVersion;
}
public String getModuleVersion() {
return moduleVersion;
}
public String getMacAddress() {
return macAddress;
}
public String getCurrentIPAddress() {
return currentIPAddress;
}
}
|
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* Action de inicialização do sistema que carrega funções cadastradas no SG no
* profile do usuário. Esta classe realiza integração com o SG através da
* factory SecurityGatewayFactory.
*
* @see com.citibank.ods.common.security;
* @version 1.0
* @author marcelo.s.oliveira,June 1 , 2007
*
*/
package com.citibank.ods.common.security;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.citibank.latam.sgway.util.RecordList;
import com.citibank.newcpb.security.SecurityUtil;
import com.citibank.ods.common.configuration.Configuration;
import com.citibank.ods.common.exception.UnexpectedException;
import com.citibank.ods.common.logger.ApplicationLogger;
import com.citibank.ods.common.logger.LoggerFactory;
import com.citibank.ods.common.security.connector.SecurityGatewayFactory;
import com.citibank.ods.common.security.connector.SecurityGatewayInterface;
import com.citibank.ods.common.user.User;
public class StartupAction extends Action
{
public final ActionForward execute( ActionMapping actionMapping_,
ActionForm actionForm_,
HttpServletRequest request_,
HttpServletResponse response_ )
throws Exception
{
MokAuthenticationForm mokActionForm = ( MokAuthenticationForm ) actionForm_;
String isMock = Configuration.getInstance().getValue( "isMock" );
String systemID = Configuration.getInstance().getValue( "systemID" );
String userID = null;
String ipAddress = request_.getRemoteAddr();
String sessionSpecs = null;
String firstName = null;
String lastName = null;
String actionForward = "";
// Inicializa factory de Login
LoggerFactory.initialize();
// Recupera instância de Application
ApplicationLogger applicationLogger = LoggerFactory.getApplicationLoggerInstance();
if ( "true".equals( isMock ) )
{
sessionSpecs = request_.getSession().getId();
userID = mokActionForm.getm_username();
}
else
{
sessionSpecs = request_.getHeader( "sm_serversessionspec" );
userID = request_.getHeader( "sm_user" ).trim();
}
// Cria nova instância de usuário
User user = new User();
// Carrega dados do ambiente para o usuário
setUserData( userID, ipAddress, sessionSpecs, user );
// Inicializa flag de permissão para acesso ao sistema
boolean canAccessSystemVar = false;
// Resgata instância de Security Gatewaty
SecurityGatewayInterface legacyConnector = SecurityGatewayFactory.getSecurityGatewayLegacyConnector();
// Mensagem de verificação de acesso ao sistema escrita no arquivo de log.
// (LogManager em modo DEBUG)
applicationLogger.debug( "Verificando se usuário pode acessar o sistema (método canAccessSystem): [usuário - "
+ user.getUserID()
+ "][IP - "
+ user.getIpAddress()
+ "][SessionSpecs - "
+ user.getSessionSpecs()
+ "][System ID - "
+ Integer.parseInt( systemID ) + "]" );
// Verifica se usuário tem permissão para acessar o sistema atribuindo flag
// de permissão
canAccessSystemVar = legacyConnector.canAccessSystem(
user.getUserID(),
user.getIpAddress(),
user.getSessionSpecs(),
Integer.parseInt( systemID ) );
// Atribui nome e sobrenome para modo de simulação
if ( "true".equals( isMock ) )
{
firstName = "Teste";
lastName = "ODS";
}
else
{
// Resgata nome e sobrenome do usuário
RecordList userBasicProfileRecordList = legacyConnector.getUserBasicProfile(
user.getUserID(),
user.getIpAddress(),
user.getSessionSpecs() );
for ( int i = 0; i < userBasicProfileRecordList.getRecordCount(); i++ )
{
firstName = ( String ) userBasicProfileRecordList.getString( i,
"FIRST_NAME" );
lastName = ( String ) userBasicProfileRecordList.getString( i,
"LAST_NAME" );
}
}
// Atribui FIRST_NAME e LAST_NAME resgatado do security gateway
user.setFirstName( firstName );
user.setLastName( lastName );
try
{
// Se usuário puder acessar o sistema
if ( canAccessSystemVar )
{
// Define redirecionamento para a primeira tela do sistema
actionForward = Configuration.getInstance().getValue( "firstFoward" );
// Carrega funções permitidas para o usuário
ArrayList functions = loadUserFunctions( mokActionForm, isMock,
systemID, applicationLogger,
user, legacyConnector );
// Atribui a lista de funções ao usuário
user.setFunctions( functions );
SecurityUtil securityUtil = new SecurityUtil();
user = securityUtil.initUserNewCPB(applicationLogger, user, systemID, isMock);
// Guarda instância de usuário criado na seção
request_.getSession().setAttribute( "user", user );
}
// Se usuário não puder acessar o sistema é realizado um redirecionamento
// para página de acesso negado
else
{
actionForward = "CannotAcessSystem";
}
}
catch ( Exception e )
{
applicationLogger.error("ERRO STATUP:" );
applicationLogger.error( e.getLocalizedMessage() );
e.printStackTrace();
throw new UnexpectedException( "Erro ao acessar SG" );
}
return actionMapping_.findForward( actionForward );
}
/**
* "Carrega funções permitidas para o usuário"
*/
private ArrayList loadUserFunctions( MokAuthenticationForm mokActionForm_,
String isMock_, String systemID_,
ApplicationLogger applicationLogger_,
User user_,
SecurityGatewayInterface legacyConnector_ )
throws Exception
{
ArrayList functions = new ArrayList();
RecordList modulesRecordList = null;
RecordList functionsRecordList = null;
RecordList modulesAndFunctionsRecordList = null;
// Se está em modo de simulação
if ( "true".equals( isMock_ ) )
{
// Popula lista de funções para usuário. (Modo de simulação)
populateMockFunctionList( mokActionForm_, systemID_, applicationLogger_,
user_, legacyConnector_, functions );
}
// Se não está em modo de simulação
else
{
// Popula lista de funções para usuário
populateFunctionList( systemID_, applicationLogger_, user_,
legacyConnector_, functions );
}
return functions;
}
/**
* "Carrega lista de funções para usuário"
*/
private void populateFunctionList( String systemID_,
ApplicationLogger applicationLogger_,
User user_,
SecurityGatewayInterface legacyConnector_,
ArrayList functions_ ) throws Exception
{
RecordList modulesRecordList;
// Carrega os módulos definidos para o usuário
modulesRecordList = legacyConnector_.getSystemModules(
user_.getUserID(),
user_.getIpAddress(),
user_.getSessionSpecs(),
Integer.parseInt( systemID_ ) );
// Adiciona as funções cadastradas para o usuário no ArrayList de
// funções
addModuleFunctions( systemID_, applicationLogger_, user_, legacyConnector_,
functions_, modulesRecordList );
}
/**
* "Carrega lista de funções para usuário. (Modo de simulação)"
*/
private void populateMockFunctionList(
MokAuthenticationForm mokActionForm_,
String systemID_,
ApplicationLogger applicationLogger_,
User user_,
SecurityGatewayInterface legacyConnector_,
ArrayList functions_ ) throws Exception
{
RecordList modulesAndFunctionsRecordList;
StringTokenizer tokenizer;
String groupName;
// Resgata groupName do Form de Login Mock
String groupNamesFromForm = mokActionForm_.getm_groupName();
// Carrega os módulos e funções definidos para o usuário
modulesAndFunctionsRecordList = legacyConnector_.getSystemModulesAndFunctions(
user_.getUserID(),
user_.getIpAddress(),
user_.getSessionSpecs(),
Integer.parseInt( systemID_ ) );
// Adiciona as funções cadastradas para o usuário no ArrayList de
// funções
addMockModuleFunctions( applicationLogger_, user_, functions_,
modulesAndFunctionsRecordList, groupNamesFromForm );
}
/**
* "Carrega dados do ambiente para o usuário"
*/
private void setUserData( String userID_, String ipAddress_,
String sessionSpecs_, User user_ )
{
// Atribui ID do usuário na nova instância
user_.setUserID( userID_ );
// Atribui IP do usuário na nova instância
user_.setIpAddress( ipAddress_ );
// Atribui SessionSpecs na nova instância
user_.setSessionSpecs( sessionSpecs_ );
}
/**
* "Adiciona as funções cadastradas para o usuário no ArrayList de funções"
*/
private void addModuleFunctions( String systemID_,
ApplicationLogger applicationLogger_,
User user_, SecurityGatewayInterface lc_,
ArrayList functions_,
RecordList modulesRecordList_ )
throws Exception
{
RecordList functionsRecordList;
applicationLogger_.debug( "***URIs permitidas para usuário "
+ user_.getUserID() + ": " );
// Para cada módulo do RecordList modulesRecordList_
for ( int i = 0; i < modulesRecordList_.getRecordCount(); i++ )
{
// Recupera função para cada elemento de modulesRecordList_
functionsRecordList = lc_.getSystemModuleFunctions(
user_.getUserID(),
user_.getIpAddress(),
user_.getSessionSpecs(),
Integer.parseInt( systemID_ ),
modulesRecordList_.getInt(
i,
0 ) );
// Para cada função em functionsRecordList
for ( int j = 0; j < functionsRecordList.getRecordCount(); j++ )
{
// Imprime as funções no arquivo de log. (LogManager em modo DEBUG)
// applicationLogger_.debug( "FUNCTION_NAME:" + functionsRecordList.getString( j, "FUNCTION_NAME" ) + "" );
// Verifica se função já está presente na lista de funçõs do usuário
if ( !functions_.contains( functionsRecordList.getString( j,
"FUNCTION_NAME" ) ) )
{
// Adiciona entrada no ArrayList de funções
functions_.add( functionsRecordList.getString( j, "FUNCTION_NAME" ) );
}
}
}
}
/**
* "Adiciona as funções cadastradas para o usuário no ArrayList de funções.
* (Modo de simulação)"
*/
private void addMockModuleFunctions( ApplicationLogger applicationLogger_,
User user_, ArrayList functions_,
RecordList modulesRecordList_,
String groupNamesFromForm_ )
{
StringTokenizer tokenizer;
String groupName;
// Para cada perfil contido em uma linha do arquivo access.xml
for ( StringTokenizer groupTokenizer = new StringTokenizer(
groupNamesFromForm_,
"-" ); groupTokenizer.hasMoreTokens(); )
{
// Resgata perfil a partir da tela de login
groupName = groupTokenizer.nextToken();
applicationLogger_.debug( "MOCK - URIs permitidas para usuário "
+ user_.getUserID() + ": " );
// Para cada registro trazido do arquivo access.xml
for ( int i = 0; i < modulesRecordList_.getRecordCount(); i++ )
{
applicationLogger_.debug( " "
+ modulesRecordList_.getString( i,
"FUNCTION_NAME" ) );
// Resgata perfil (GROUP_NAME) do xml
tokenizer = new StringTokenizer(
modulesRecordList_.getString( i,
"GROUP_NAME" ),
"-" );
// Verifica se função já está presente na lista de funçõs do usuário
if ( !functions_.contains( modulesRecordList_.getString( i,
"FUNCTION_NAME" ) ) )
{
// Enquanto houver mais perfis lidos do xml
while ( tokenizer.hasMoreTokens() )
{
// Se nome do perfil lido do formulário for igual ao nome do perfil
// lido do xml
if ( groupName.equals( tokenizer.nextToken() ) )
{
// Adiciona entrada no ArrayList de funções
functions_.add( modulesRecordList_.getString( i, "FUNCTION_NAME" ) );
break;
}
}
}
}
}
}
}
|
package pl.herbata.project.mvc.editplayerdialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import pl.herbata.project.Player;
import pl.herbata.project.mvc.Controller;
public class EditPlayerDialogController implements Controller {
private EditPlayerDialogModel model;
private EditPlayerDialogView view;
public EditPlayerDialogController(EditPlayerDialogModel model,
EditPlayerDialogView view) {
this.model = model;
this.view = view;
}
public void initialize() {
view.setAccceptButtonActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
acceptButtonActionPerformed(e);
}
});
view.setCancelButtonActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelButtonActionPerformed(e);
}
});
Player selectedPlayer = model.getSelectedPlayer();
view.setPlayersNickname(selectedPlayer.getNickname());
view.createAndShowUI();
}
private void acceptButtonActionPerformed(ActionEvent e) {
String playersNickname = view.getPlayersNickname();
if (playersNickname.length() == 0) {
view.showMessageDialog("Dane niepoprawne");
return;
}
model.updatePlayer(playersNickname);
view.close();
}
private void cancelButtonActionPerformed(ActionEvent e) {
view.close();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.