text
stringlengths 10
2.72M
|
|---|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.client.config.services.impl;
import de.hybris.platform.servicelayer.keygenerator.KeyGenerator;
import org.apache.log4j.Logger;
import com.cnk.travelogix.client.config.core.partpayment.model.PartPaymentMasterConfigModel;
import com.cnk.travelogix.client.config.services.PartPaymentService;
/**
* Generates id using keyGenerator and set into PartPymentId attribute.
*/
public class DefaultPartPaymentService implements PartPaymentService
{
private static Logger LOG = Logger.getLogger(DefaultPartPaymentService.class);
private KeyGenerator keyGenerator;
@Override
public void generatePartPaymentId(final PartPaymentMasterConfigModel partPaymentModel)
{
if (partPaymentModel.getPartPaymentId() == null)
{
partPaymentModel.setPartPaymentId("PPM" + keyGenerator.generate());
LOG.debug("Generated PPM is -" + partPaymentModel.getPartPaymentId());
}
}
/**
* @return the keyGenerator
*/
public KeyGenerator getKeyGenerator()
{
return keyGenerator;
}
/**
* @param keyGenerator
* the keyGenerator to set
*/
public void setKeyGenerator(final KeyGenerator keyGenerator)
{
this.keyGenerator = keyGenerator;
}
}
|
package org.example.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import java.util.concurrent.ExecutionException;
@RestController
public class SleepController {
@Autowired
private Sleeper sleeper;
@GetMapping("/sleep/{t}")
public Map<String, ?> sleep(@PathVariable final Float t) throws InterruptedException, ExecutionException {
final long start = System.nanoTime();
sleeper.sleep(t).get();
final double elapsed = (System.nanoTime() - start) / 1e9;
return Map.of("slept", t, "elapsed", elapsed);
}
}
|
package com.ssm.wechatpro.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.ssm.wechatpro.dao.WechatOrderManagerMapper;
import com.ssm.wechatpro.object.InputObject;
import com.ssm.wechatpro.object.OutputObject;
import com.ssm.wechatpro.service.WechatOrderManagerService;
import com.ssm.wechatpro.util.DateUtil;
import com.ssm.wechatpro.util.JudgeUtil;
@Service("wechatOrderManagerServiceImpl")
public class WechatOrderManagerServiceImpl implements WechatOrderManagerService {
@Autowired
private WechatOrderManagerMapper wechatOrderManagerMapper;
// 需要查询订单的表名
private final static String ORDERlOGTABLENAME = "wechat_customer_order_log_";
private final static String ORDERSHOPPINGTABLENAMW = "wechat_customer_order_shopping_log_";
/**
* 查询该商店当天所有已经付款的但是没有给顾客的订单(按照流水号排序)
* @param map
* @return
* @throws Exception
*/
public void selectPaiedOrderForm(InputObject inputObject, OutputObject outputObject) throws Exception{
// tableName
// orderAdminId 餐厅id
// shopIdAndDay 六位餐厅id和当前日期拼接
// 获取该商店登录id
Map<String, Object> map = inputObject.getLogParams();
Map<String, Object> mapParam = inputObject.getParams();
if(JudgeUtil.isNull(map.get("id") + "")){
return ;
}
// 尽心分页处理
int page = Integer.parseInt(mapParam.get("offset").toString())/Integer.parseInt(mapParam.get("limit").toString());
page++;
int limit = Integer.parseInt(mapParam.get("limit").toString());
mapParam.put("tableName", ORDERlOGTABLENAME + DateUtil.getTimeSixAndToString()); // 添加表名
String shopIdAndDay = "000000" + map.get("id") + "";
// 拼接商店id和当前日期字符串
mapParam.put("shopIdAndDay", shopIdAndDay.substring(shopIdAndDay.length()-6, shopIdAndDay.length()) + DateUtil.getTimeToString());
mapParam.put("orderAdminId", map.get("id") + "");
List<Map<String,Object>> returnInfo = wechatOrderManagerMapper.selectPaiedOrderForm(mapParam, new PageBounds(page, limit));
PageList<Map<String, Object>> pageList = (PageList<Map<String,Object>>)returnInfo;
// 获取当前页数
int total = pageList.getPaginator().getTotalCount();
outputObject.setBeans(returnInfo);
outputObject.settotal(total);
}
/**
* 根据订单的id和订单的单号查询订单详情
* @param map
* @return
* @throws Exception
*/
public void selectOrderFormInfo (InputObject inputObject, OutputObject outputObject) throws Exception{
Map<String, Object> mapParam = inputObject.getParams();
String string = mapParam.get("orderNumber").toString();
String data = string.substring(12,18);
String tableName = ORDERlOGTABLENAME + data; // 拼接表名
mapParam.put("tableName", tableName);
// 查询商品的基本信息
Map<String, Object> productBasic = wechatOrderManagerMapper.selectOrderFormBasic(mapParam);
// 拼接商品详情表的表名
mapParam.put("detailTableName", ORDERSHOPPINGTABLENAMW +data);
// 返回该订单中包含的商品信息
List<Map<String, Object>> productList = wechatOrderManagerMapper.selectOrderFormDetail(mapParam);
outputObject.setBean(productBasic);
outputObject.setBeans(productList);
}
/**
* 表示做好了给顾客
* @param map
* @throws Exception
*/
public void updateMake(InputObject inputObject, OutputObject outputObject) throws Exception{
// 获取当前餐厅的id
Map<String, Object> map = inputObject.getLogParams();
if(JudgeUtil.isNull(map.get("id") + "")){
return ;
}
// 获取单号
// 获取该订单的id
Map<String, Object> mapParam = inputObject.getParams();
// 拼接表名
mapParam.put("tableName", ORDERlOGTABLENAME + DateUtil.getTimeSixAndToString());
mapParam.put("nowTime", DateUtil.getTimeAndToString() + "");
wechatOrderManagerMapper.updateMake(mapParam);
// 同时将该订单中包含商品的数量在分配表中进行更新
mapParam.put("detailTableName", ORDERSHOPPINGTABLENAMW + DateUtil.getTimeSixAndToString());
// 传入订单id即可
List<Map<String, Object>> productList = wechatOrderManagerMapper.selectProductTotal(mapParam);
for(Map<String, Object> productInfo : productList){
productInfo.put("id", map.get("id") + "");
wechatOrderManagerMapper.updateMakeAddNum(productInfo);
}
}
/**
* 根据搜索的日期进行查询,订单统计
*/
@Override
public void selectAllOrderByDate(InputObject inputObject, OutputObject outputObject) throws Exception {
// tableName
// orderAdminId 餐厅id
// shopIdAndDay 六位餐厅id和当前日期拼接
// 获取该商店登录id
Map<String, Object> map = inputObject.getLogParams();
Map<String, Object> mapParam = inputObject.getParams();
String orderDate = mapParam.get("search").toString();
String orderYear = null;
if(!orderDate.isEmpty()){
if(orderDate.length()>7){
//获取年月份(201801),判断查询哪张表
String a = orderDate.substring(0, orderDate.lastIndexOf('-'));
orderYear = a.replace("-", "");
}else if(orderDate.length()<=7){
orderYear = orderDate.replace("-", "");
}
mapParam.put("tableName", ORDERlOGTABLENAME + orderYear);
}else{
mapParam.put("tableName", ORDERlOGTABLENAME + DateUtil.getTimeSixAndToString()); // 添加表名
}
if(JudgeUtil.isNull(map.get("id") + "")){
return ;
}
// 尽心分页处理
int page = Integer.parseInt(mapParam.get("offset").toString())/Integer.parseInt(mapParam.get("limit").toString());
page++;
int limit = Integer.parseInt(mapParam.get("limit").toString());
// String shopIdAndDay = "000000" + map.get("id") + "";
// 拼接商店id和当前日期字符串
// mapParam.put("shopIdAndDay", shopIdAndDay.substring(shopIdAndDay.length()-6, shopIdAndDay.length()) + DateUtil.getTimeToString());
mapParam.put("orderAdminId", map.get("id") + "");
List<Map<String,Object>> returnInfo = wechatOrderManagerMapper.selectAllOrderByDate(mapParam, new PageBounds(page, limit));
PageList<Map<String, Object>> pageList = (PageList<Map<String,Object>>)returnInfo;
// 获取当前页数
int total = pageList.getPaginator().getTotalCount();
outputObject.setBeans(returnInfo);
outputObject.settotal(total);
}
}
|
package common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 处理Properties文件
* Created by fansy on 2017/9/16.
*/
public class PropertiesUtil {
private static final Logger log = LoggerFactory.getLogger(PropertiesUtil.class);
public static Map<String, String> getProperties(String file) {
log.info("loading file :"+file);
Map<String, String> props = new HashMap<>();
Properties prop = new Properties();
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(file);
try {
prop.load(in);
Enumeration en = prop.propertyNames(); //得到配置文件的名字
while (en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = prop.getProperty(strKey);
props.put(strKey, strValue);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
}
|
package melerospaw.deudapp.iu.widgets;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;
public class CustomLinearLayoutManager extends LinearLayoutManager {
private boolean scrollEnabled;
public CustomLinearLayoutManager(Context context) {
super(context);
init();
}
public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
init();
}
public CustomLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
scrollEnabled = true;
}
public void setScrollEnabled(boolean enabled) {
this.scrollEnabled = enabled;
}
@Override
public boolean canScrollHorizontally() {
return scrollEnabled && super.canScrollHorizontally();
}
@Override
public boolean canScrollVertically() {
return scrollEnabled && super.canScrollVertically();
}
}
|
package cz.kojotak.udemy.vertx.stockBroker.api.watchlist;
import java.util.HashMap;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cz.kojotak.udemy.vertx.stockBroker.dto.WatchList;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
public class PutWatchListHandler implements Handler<RoutingContext> {
private static final Logger LOG = LoggerFactory.getLogger(PutWatchListHandler.class);
private final HashMap<UUID, WatchList> watchListPerAccount;
public PutWatchListHandler(HashMap<UUID, WatchList> watchListPerAccount) {
super();
this.watchListPerAccount = watchListPerAccount;
}
@Override
public void handle(RoutingContext ctx) {
var accountId = ctx.pathParam("accountId");
LOG.debug("{} for account {}", ctx.normalisedPath(), accountId);
var json = ctx.getBodyAsJson();
var watchList = json.mapTo(WatchList.class);
watchListPerAccount.put(UUID.fromString(accountId), watchList);
ctx.response().end(json.toBuffer());
}
}
|
package com.ibrahim.androidTask.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.cooltechworks.views.shimmer.ShimmerRecyclerView;
import com.ibrahim.androidTask.Models.MediaModel.Datum;
import com.ibrahim.androidTask.R;
import com.ibrahim.androidTask.Utils.ParentClass;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MediaAdapter extends RecyclerView.Adapter<MediaAdapter.ViewHolder> {
ArrayList<Datum> mediaList;
Context context;
LayoutInflater layoutInflater;
ShimmerRecyclerView rvMedia;
public MediaAdapter(Context context,ShimmerRecyclerView rvMedia) {
this.mediaList = new ArrayList<>();
this.context = context;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.rvMedia = rvMedia;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {
View v = layoutInflater.from(parent.getContext()).inflate(R.layout.item_media,parent,false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder,int position) {
if (mediaList.size() != 0) {
if (mediaList.get(position).getType().equals("image")) {
holder.viewVideo.setVisibility(View.GONE);
ParentClass.LoadImageWithGlide(mediaList.get(position).getValue(),context,holder.ivMedia);
} else {
holder.ivMedia.setVisibility(View.GONE);
holder.viewVideo.setVideoPath(mediaList.get(position).getValue());
holder.viewVideo.start();
}
}
}
@Override
public int getItemCount() {
if (mediaList.size() == 0) {
rvMedia.showShimmerAdapter();
return 10;
} else {
return mediaList.size();
}
}
public int getItemViewType(int position) {
return position;
}
public void addAll(List<Datum> data) {
mediaList.clear();
mediaList.addAll(data);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.ivMedia)
ImageView ivMedia;
@BindView(R.id.viewVideo)
VideoView viewVideo;
public ViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
}
}
|
package com.sojay.testfunction.utils;
import android.text.TextUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class DateUtils {
private static final String DATE_FORMAT_PATTERN_YMD = "yyyy-MM-dd";
private static final String DATE_FORMAT_PATTERN_YMD_HM = "yyyy-MM-dd HH:mm:ss";
/**
* 时间戳转字符串
*
* @param timestamp 时间戳
* @param isPreciseTime 是否包含时分秒
* @return 格式化的日期字符串
*/
public static String long2Str(long timestamp, boolean isPreciseTime) {
return long2Str(timestamp, getFormatPattern(isPreciseTime));
}
private static String long2Str(long timestamp, String pattern) {
return new SimpleDateFormat(pattern, Locale.CHINA).format(new Date(timestamp));
}
/**
* 字符串转时间戳
*
* @param dateStr 日期字符串
* @param isPreciseTime 是否包含时分秒
* @return 时间戳
*/
public static long str2Long(String dateStr, boolean isPreciseTime) {
return str2Long(dateStr, getFormatPattern(isPreciseTime));
}
private static long str2Long(String dateStr, String pattern) {
try {
return new SimpleDateFormat(pattern, Locale.CHINA).parse(dateStr).getTime();
} catch (Throwable ignored) {
}
return 0;
}
private static String getFormatPattern(boolean showSpecificTime) {
if (showSpecificTime) {
return DATE_FORMAT_PATTERN_YMD_HM;
} else {
return DATE_FORMAT_PATTERN_YMD;
}
}
/**
* 计算年龄差,与当前时间做比较
* @param beginDateStr 出生日期
* @return 格式:*岁*个月*天
*/
public static String DifferAgeDate(String beginDateStr) {
return DifferDate(beginDateStr, long2Str(System.currentTimeMillis(), false), "岁");
}
/**
* 计算时间差,距离当前时间
* @param beginDateStr 开始日期字符串
* @param endDateStr 结束日期字符串
* @param yearUnit 返回时年的单位:年/岁
* @return
*/
private static String DifferDate(String beginDateStr, String endDateStr, String yearUnit) {
if (TextUtils.isEmpty(beginDateStr))
return "";
try {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_PATTERN_YMD, Locale.getDefault());
Calendar beginDateCal = Calendar.getInstance();
beginDateCal.setTime(sdf.parse(beginDateStr));
Calendar nowDateCal = Calendar.getInstance();
nowDateCal.setTime(sdf.parse(endDateStr));
int beginYear = beginDateCal.get(Calendar.YEAR);
int endYear = nowDateCal.get((Calendar.YEAR));
//当前年份小于开始年份 返回:“”【时间错误】
if (endYear < beginYear)
return "";
int beginMonth = beginDateCal.get(Calendar.MONTH);
int endMonth = nowDateCal.get((Calendar.MONTH));
int beginMaxDay = beginDateCal.getActualMaximum(Calendar.DAY_OF_MONTH);
int beginDay = beginDateCal.get(Calendar.DAY_OF_MONTH);
int endDay = nowDateCal.get((Calendar.DAY_OF_MONTH));
// 年份相同
if (endYear == beginYear) {
// 月份相同
// 日期相同 返回:0年0月0天
// 当前日期大于开始日期 返回:0年0月 天数差
// 当前日期小于开始日期 返回:“”【时间错误】
if (endMonth == beginMonth) {
if (endDay < beginDay)
return "";
return "0" + yearUnit + "0个月" + (endDay - beginDay) + "天";
}
// 当前月份大开始月份
// 日期相同 返回:0年 月数差 0天
// 当前日期大于 返回:0年 月数差 天数差
// 当前日期小于 返回:0年 月数差-1 开始月天数-开始天数+当前天数
if (endMonth > beginMonth) {
if (endDay < beginDay)
return "0" + yearUnit + (endMonth - beginMonth - 1) + "个月" + (beginMaxDay - beginDay + endDay) + "天";
return "0" + yearUnit + (endMonth - beginMonth) + "个月" + (endDay - beginDay) + "天";
}
// 当前月份小于开始月份 返回:“"【时间错误】
return "";
}
// 当前年份大于开始年份
// 上面年份情况已经判断,只剩下这一种情况,所以不用写年份判断
// 月份相同
// 日期相同 返回:年数差 0月0天
// 当前日期大于开始日期 返回:年数差 0月 天数差
// 当前日期小于开始日期 返回:年数差-1 11月 开始月天数-开始天数+当前天数
if (endMonth == beginMonth) {
if (endDay < beginDay)
return (endYear - beginYear - 1) + yearUnit + "11个月" + (beginMaxDay - beginDay + endDay) + "天";
return (endYear - beginYear) + yearUnit + "0个月" + (endDay - beginDay) + "天";
}
// 当前月份大于开始月份
// 日期相同 返回:年数差 月数差 0天
// 当前日期大于开始日期 返回:年数差 月数差 天数差
// 当前日期小于开始开始日期 返回:年数差 月数差-1 开始月天数-开始天数+当前天数
if (endMonth > beginMonth) {
if (endDay < beginDay)
return (endYear - beginYear) + yearUnit + (endMonth - beginMonth - 1) + "个月" + (beginMaxDay - beginDay + endDay) + "天";
return (endYear - beginYear) + yearUnit + (endMonth - beginMonth) + "个月" + (endDay - beginDay) + "天";
}
// 当前月份小于开始月份
// 日期相同 返回:年数差-1 12-开始月份+当前月份 0天
// 当前日期大于开始日期 返回:年数差-1 12-开始月份+当前月份 天数差
// 当前日期小于开始日期 返回:年数差-1 12-开始月份+当前月份-1 开始月天数-开始天数+当前天数
// 上面月份情况已经判断,只剩下这一种情况,所以不用写月份判断
if (endDay < beginDay)
return (endYear - beginYear) + yearUnit + (12 - beginMonth + endMonth -1) + "个月" + (beginMaxDay - beginDay + endDay) + "天";
return (endYear - beginYear) + yearUnit + (12 - beginMonth + endMonth) + "个月" + (endDay - beginDay) + "天";
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
}
|
interface Area{
public abstract void getArea();
}
class Rectangle implements Area{
private int length;
private int width;
Rectangle(int l, int w){
if (l <= 0 || w <= 0){
throw new DiyArguementException("矩形的边长必须大于0");
}
this.length = l;
this.width = w;
}
public void getArea(){
MyUtil.println(this.length * this.width);
}
}
class Circle implements Area{
public static final Double PI = 3.14;
private double radius;
Circle(double r){
if (r < 0){
throw new DiyArguementException("半径不能小于0");
}
this.radius = r;
}
public void getArea(){
MyUtil.println(String.valueOf(radius * radius * PI));
}
}
class DiyArguementException extends RuntimeException{
DiyArguementException(String s){
super(s);
}
}
class TestArea{
public static void main(String[] args){
// Circle c = new Circle(-1);
// c.getArea();
Rectangle r = new Rectangle(0, 1);
r.getArea();
}
}
|
/*
* 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 banco_dados;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import model.C_Contato;
/**
*
* @author maria
*/
public class Contato {
private Connection conBanco;
private PreparedStatement psComando;
private ResultSet rsRegistros;
private C_Contato c_contato = new C_Contato();
public void configurarConexao(Connection conBanco) {
this.conBanco = conBanco;
}
public boolean inserirRegistro(C_Contato c_contato) {
String strComandoSQL;
try {
strComandoSQL = "INSERT INTO contato(idContato, nome, cargo, empresa, dataAniversario, idUsuario)"
+ "VALUES('" + c_contato.getNome() + "', "
+ "'" + c_contato.getCargo() + "', "
+ "'" + c_contato.getEmpresa() + "')"
+ "'" + c_contato.getDataAniversario() + "')"
+ "'" + c_contato.getIdUsuario() + "')";
psComando = conBanco.prepareStatement(strComandoSQL);
psComando.executeUpdate();
return true;
} catch (Exception erro) {
erro.printStackTrace();
return false;
}
}
public boolean alterarRegistro(C_Contato c_contato) {
String strComandoSQL;
try {
strComandoSQL = "UPDATE contato SET nome = '" + c_contato.getNome() + "',"
+ "cargo = '" + c_contato.getCargo() + "',"
+ "empresa = '" + c_contato.getEmpresa() + "' "
+ "dataAniversario = '" + c_contato.getDataAniversario() + "' "
+ "WHERE idContato = " + c_contato.getIdContato();
psComando = conBanco.prepareStatement(strComandoSQL);
psComando.executeUpdate();
return true;
} catch (Exception erro) {
erro.printStackTrace();
return false;
}
}
public boolean excluirRegistro(int idContato) {
String strComandoSQL;
try {
strComandoSQL = "DELETE FROM contato WHERE idContato = " + idContato;
psComando = conBanco.prepareStatement(strComandoSQL);
psComando.executeUpdate();
return true;
} catch (Exception erro) {
erro.printStackTrace();
return false;
}
}
public ResultSet listarRegistros() {
String strComandoSQL;
try {
strComandoSQL = "SELECT * FROM contato";
psComando = conBanco.prepareStatement(strComandoSQL);
rsRegistros = psComando.executeQuery();
return rsRegistros;
} catch (Exception erro) {
erro.printStackTrace();
return null;
}
}
}
|
package com.smxknife.netty.v5.demo04;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
* @author smxknife
* 2018-12-04
*/
public class EchoClientHandler extends ChannelHandlerAdapter {
private static final String REQ_MSG = "_Hello, Netty.#_";
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
for (int i = 0; i < 100; i++) {
ByteBuf byteBuf = Unpooled.copiedBuffer((i + REQ_MSG).getBytes());
ctx.writeAndFlush(byteBuf);
}
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String body = (String) msg;
System.out.println("TimeClient : " + body);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
ctx.close();
}
}
|
package ai2018.group18;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import genius.core.Bid;
import genius.core.bidding.BidDetails;
import genius.core.boaframework.*;
import genius.core.uncertainty.UserModel;
import genius.core.utility.AdditiveUtilitySpace;
/**
* This acceptance class will accept bids if they are higher than the threshold,
* defined by a function of time and the difference between our own best offer
* and the opponents best offer.
*/
public class Group18_AS extends AcceptanceStrategy {
private UserModel userModel;
private UtilityFunctionEstimate utilityFunctionEstimate;
private double a; // alpha
private double b; // beta
@Override
public void init(NegotiationSession negoSession, OfferingStrategy strat, OpponentModel opponentModel,
Map<String, Double> parameters) {
this.negotiationSession = negoSession;
this.offeringStrategy = strat;
userModel = negotiationSession.getUserModel();
if (userModel != null) { // "enable uncertainty" is checked
// create utility space with estimated preferences
List<Bid> bidOrder = userModel.getBidRanking().getBidOrder();
AdditiveUtilitySpace utilitySpaceEstimate = (AdditiveUtilitySpace) negotiationSession.getUtilitySpace().copy();
utilityFunctionEstimate = new UtilityFunctionEstimate(utilitySpaceEstimate, bidOrder);
}
// initialize alpha and beta
if (parameters.get("a") != null || parameters.get("b") != null) {
a = parameters.get("a");
b = parameters.get("b");
} else {
a = 1.4;
b = 0.02;
}
}
@Override
public String printParameters() {
String str = "[a: " + a + "]";
return str;
}
/**
* Determines the acceptability based on the acceptance function, given (un)discounted or (un)certainty domain
*/
@Override
public Actions determineAcceptability() {
if (negotiationSession.getDiscountFactor() < 0.7) {
if (userModel != null) {
return determineAcceptabilityAction(true, true);
} else {
return determineAcceptabilityAction(true, false);
}
} else {
if (userModel != null) {
return determineAcceptabilityAction(false, true);
} else {
return determineAcceptabilityAction(false, false);
}
}
}
/**
* Determines the acceptability based on the acceptance function.
* Acceptance function is based on the time left and the difference between our best offer and the opponents best offer.
* for (un)discounted or (un)certainty domains
*/
public Actions determineAcceptabilityAction(boolean discount, boolean uncertainty) {
double percentageTimeLeft = getPercentageTimeLeft();
// get utility of my first bid, my next bid, opponent's best bid, opponent's last bid
double myFirstBidUtility = getMyFirstBidUtility(uncertainty);
double myNextBidUtility = getMyNextBidUtility(uncertainty);
double opponentsBestBidUtility = getOpponentsBestBidUtility(uncertainty);
double opponentsLastBidUtility = getOpponentsLastBidUtility(uncertainty);
// find minimum offer that we are ever willing to accept
double minimumOffer = findMinimumOffer(myFirstBidUtility, opponentsBestBidUtility);
// calculate difference between our first bid and the best bid of the opponent
double difference = myFirstBidUtility - opponentsBestBidUtility;
// find minimum offer that we are willing to accept at the current time
double acceptableOffer;
if (discount) {
acceptableOffer = findAcceptableOfferDiscounted(minimumOffer);
} else {
acceptableOffer = findAcceptableOffer(minimumOffer, percentageTimeLeft, myFirstBidUtility, difference);
}
// Accept an offer if it is better than my next bid OR if it is better than the acceptableOffer variable
if (opponentsLastBidUtility >= myNextBidUtility && opponentsLastBidUtility >= opponentsBestBidUtility) {
return Actions.Accept;
} else if (opponentsLastBidUtility >= acceptableOffer) {
return Actions.Accept;
} else {
return Actions.Reject;
}
}
/**
* Determines minimum offer based on our optimal bid and the opponent's best bid.
* @param myFirstBid
* @param opponentsBestBid
* @return minimimOffer
*/
public double findMinimumOffer(double myFirstBid, double opponentsBestBid) {
if (myFirstBid / a > opponentsBestBid) {
return myFirstBid / a;
} else {
return opponentsBestBid;
}
}
/**
* An acceptable offer: the closer we come to the end of a negotiation, the lower it gets. In the last 2% of rounds it is
* equal to the minimumoffer variable.
* @param minimumOffer
* @param percentageTimeLeft
* @param myFirstBid
* @param difference
* @return acceptableOffer utility
*/
public double findAcceptableOffer(double minimumOffer, double percentageTimeLeft, double myFirstBid, double difference) {
if (percentageTimeLeft > b) {
return myFirstBid - (difference * Math.pow((1 - percentageTimeLeft), 2));
} else {
return minimumOffer;
}
}
/**
* Finds an acceptable offer for a discounted domain, using a different function.
* @param minimumOffer
* @return acceptableOffer utility
*/
public double findAcceptableOfferDiscounted(double minimumOffer) {
double discountFactor = 0.45 - negotiationSession.getDiscountFactor();
if (discountFactor > 0) {
return minimumOffer - discountFactor;
} else {
return minimumOffer;
}
}
/**
*
* @return percentage time left
*/
public double getPercentageTimeLeft() {
double totalTime = negotiationSession.getTimeline().getTotalTime();
double currentTime = negotiationSession.getTimeline().getCurrentTime();
return (totalTime - currentTime) / totalTime;
}
/**
*
* @param uncertainty
* @return get utility of my first bid
*/
public double getMyFirstBidUtility(boolean uncertainty) {
if (negotiationSession.getTimeline().getCurrentTime() > 1) {
BidDetails myFirstBidDetails = negotiationSession.getOwnBidHistory().getFirstBidDetails();
if (uncertainty) {
return utilityFunctionEstimate.getUtilityEstimate(myFirstBidDetails.getBid());
} else {
return myFirstBidDetails.getMyUndiscountedUtil();
}
} else {
return 1;
}
}
/**
*
* @param uncertainty
* @return get utility of my next bid
*/
public double getMyNextBidUtility(boolean uncertainty) {
BidDetails myNextBidDetails = offeringStrategy.getNextBid();
if (uncertainty) {
return utilityFunctionEstimate.getUtilityEstimate(myNextBidDetails.getBid());
} else {
return myNextBidDetails.getMyUndiscountedUtil();
}
}
/**
*
* @param uncertainty
* @return get utility of the best bid of the opponent
*/
public double getOpponentsBestBidUtility(boolean uncertainty) {
BidDetails opponentsBestBidDetails = negotiationSession.getOpponentBidHistory().getBestBidDetails();
if (uncertainty) {
return utilityFunctionEstimate.getUtilityEstimate(opponentsBestBidDetails.getBid());
} else {
return opponentsBestBidDetails.getMyUndiscountedUtil();
}
}
/**
*
* @param uncertainty
* @return get utility of the last bid of the opponent
*/
public double getOpponentsLastBidUtility(boolean uncertainty) {
BidDetails opponentsLastBidDetails = negotiationSession.getOpponentBidHistory().getLastBidDetails();
if (uncertainty) {
return utilityFunctionEstimate.getUtilityEstimate(opponentsLastBidDetails.getBid());
} else {
return opponentsLastBidDetails.getMyUndiscountedUtil();
}
}
@Override
public Set<BOAparameter> getParameterSpec() {
Set<BOAparameter> set = new HashSet<BOAparameter>();
set.add(new BOAparameter("a", 1.4,
"Acceptable bid becomes starting offer divided by a if that is higher than the timedependent bid"));
set.add(new BOAparameter("b", 0.02,
"The last b percentage of rounds, the agent will accept offers equal to its minimum offer variable"));
return set;
}
@Override
public String getName() {
return "Group18_AS";
}
}
|
package com.myRabbitMQ.ack;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Producer {
public static void main(String[] args) throws IOException, TimeoutException {
//1.创建连接工场
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("10.0.1.119");
factory.setPort(5672);
factory.setVirtualHost("/");
//2.通过连接工程创建连接
Connection connection = factory.newConnection();
//3.通过connection创建Channel
Channel channel = connection.createChannel();
//设置消息的一些属性
Map<String,Object> headers = new HashMap<>();
headers.put("args1", "11");
//expiration:自动删除时间
String exchange = "test_ack_exchange";
String routingKey = "ack.test";
//4.通过Channel发送数据
for(int i=0;i<5;i++){
headers.put("num", i);
AMQP.BasicProperties properties = new AMQP.BasicProperties().builder()
.deliveryMode(2)
.contentType("utf-8")
.headers(headers)
.build();
String message = "Hello RabbitMq" + i;
//不设置exchange,会有个默认的exchange,根据routingkey去寻找queue
channel.basicPublish(exchange, routingKey, properties, message.getBytes());
}
//5.关闭连接
/*channel.close();
connection.close();*/
}
}
|
package com.herokuapp.apimotooto.dto;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@Data
public class UserDto {
@NotBlank (message = "Username is mandatory")
private String username;
@Email (message = "Email not valid")
@NotBlank (message = "Username is mandatory")
private String email;
@Size (min = 8, max = 128, message = "Password must be minimum 8 characters")
@NotBlank (message = "Password is mandatory")
private String password;
}
|
// OneShotLatch.java 二元闭锁实现
package mygroup;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.*;
public class OneShotLatch {
private final Sync sync = new Sync();
public void signal() { sync.releaseShared(0); }
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(0);
}
private class Sync extends AbstractQueuedSynchronizer {
@Override
protected int tryAcquireShared(int ignored) {
return (getState() == 1) ? 1 : -1;
}
@Override
protected boolean tryReleaseShared(int ignored) {
setState(1); // 现在打开锁
return true; // 现在其他线程可以获取该闭锁
}
}
public static void main(String[] args) {
OneShotLatch osl = new OneShotLatch();
CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() ->{
System.out.println("开始Acquire");
try {
osl.await();
} catch (Exception ignored) {}
System.out.println("成功Acquire");
Helper.sleepForSeconds(1);
return 0;
});
CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(() ->{
System.out.println("开始 signal");
osl.signal();
System.out.println("结束 signal");
Helper.sleepForSeconds(1);
return 0;
});
cf1.join();
cf2.join();
}
}
|
package org.fhcrc.honeycomb.metapop;
/**
* Returns a number that can be interpreted as a step.
*
* Created on 26 Apr, 2013
* @author Adam Waite
* @version $Rev: 2300 $, $Date: 2013-08-16 12:21:32 -0700 (Fri, 16 Aug 2013) $, $Author: ajwaite $
*/
public interface StepProvider {
int getStep();
int incrementStep();
}
|
package com.tencent.mm.plugin.game.gamewebview.jsapi.biz;
import android.content.Intent;
import android.text.TextUtils;
import com.tencent.mm.a.e;
import com.tencent.mm.plugin.game.gamewebview.jsapi.a;
import com.tencent.mm.plugin.game.gamewebview.ui.GameWebViewUI;
import com.tencent.mm.plugin.game.gamewebview.ui.d;
import com.tencent.mm.plugin.webview.model.WebViewJSSDKFileItem;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity;
import org.json.JSONObject;
public final class al extends a {
public static final int CTRL_BYTE = 252;
public static final String NAME = "previewVideo";
public final void a(final d dVar, JSONObject jSONObject, final int i) {
x.i("MicroMsg.GameJsApiPreviewVideo", "invoke");
if (jSONObject == null || bi.oW(jSONObject.optString("localId"))) {
x.i("MicroMsg.GameJsApiPreviewVideo", "data is invalid");
dVar.E(i, a.f("previewVideo:fail_invalid_data", null));
return;
}
WebViewJSSDKFileItem Db = com.tencent.mm.plugin.game.gamewebview.a.d.Db(jSONObject.optString("localId"));
if (Db == null || TextUtils.isEmpty(Db.fnM) || !e.cn(Db.fnM)) {
x.e("MicroMsg.GameJsApiPreviewVideo", "the item is null or the File item not exist for localId: %s", new Object[]{r0});
dVar.E(i, a.f("previewVideo:fail", null));
return;
}
Intent intent = new Intent();
intent.putExtra("key_video_path", Db.fnM);
GameWebViewUI pageActivity = dVar.getPageActivity();
pageActivity.geJ = new MMActivity.a() {
public final void b(int i, int i2, Intent intent) {
if (i == (al.this.hashCode() & 65535)) {
switch (i2) {
case -1:
dVar.E(i, a.f("previewVideo:ok", null));
return;
case 0:
dVar.E(i, a.f("previewVideo:cancel", null));
return;
default:
dVar.E(i, a.f("previewVideo:fail", null));
return;
}
}
}
};
com.tencent.mm.bg.d.b(pageActivity, "card", ".ui.CardGiftVideoUI", intent, hashCode() & 65535);
}
}
|
package dataStructures;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Trie_Shaq{
private TrieNode_Shaq rootNode;
private Map<Character, Set<String>> dictionary;
public Trie_Shaq() {
this.rootNode = new TrieNode_Shaq();
this.dictionary = new HashMap<Character, Set<String>>();
}
public boolean findWord(String word) {
TrieNode_Shaq node = rootNode;
word = word.toLowerCase();
for (int i=0; i<word.length();i++) {
char currentLetter = word.charAt(i);
if(node.checkChildrenContainLetter(currentLetter)) {
node = node.getFoundNode();
} else {
return false;
}
}
return true;
}
public void insertWord(String word) {
TrieNode_Shaq node = rootNode;
word = word.toLowerCase();
char firstLetter = word.charAt(0);
if (!dictionary.containsKey(firstLetter))
dictionary.put(firstLetter, new HashSet<String>());
dictionary.get(firstLetter).add(word);
for(int i=0; i<word.length(); i++) {
char currentLetter = word.charAt(i);
if(node.checkChildrenContainLetter(currentLetter)) {
node = node.getFoundNode();
} else {
TrieNode_Shaq newNode = new TrieNode_Shaq(currentLetter);
node.addNodeToChildren(newNode);
node = newNode;
}
}
node.setIsWord(true);
}
public Map<Character, Set<String>> getDictionary() {
return dictionary;
}
public String dictionaryToString() {
String toString = "";
for (Character firstLetter : dictionary.keySet()) {
toString += firstLetter + ":\n";
for (String word : dictionary.get(firstLetter)) {
toString += word + ",";
}
toString += "\n";
}
return toString;
}
}
|
package com.mango.leo.zsproject.personalcenter.show.shenbao.listener;
import com.mango.leo.zsproject.personalcenter.show.shenbao.bean.ShenBaoBean;
import java.util.List;
/**
* Created by admin on 2018/5/21.
*/
public interface OnShenBaoListener {
void onSuccess(List<ShenBaoBean> list);
void onFailure(String msg, Exception e);
}
|
package com.udogan.magazayonetimi.ui;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JComponent;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import static javax.swing.JOptionPane.showMessageDialog;
import com.udogan.magazayonetimi.models.Kullanici;
import com.udogan.magazayonetimi.models.enums.Yetkiler;
import com.udogan.magazayonetimi.utils.dao.DbServicessBase;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComboBox;
public class KullaniciDegistirme extends JFrame {
private JPanel panel;
private JButton btnKaydet;
private JButton btnIptal;
private JButton btnSil;
private Kullanici kullanici;
public JComponent parentComponent;
public KullaniciIslemleriPaneli parentFrame;
private JTextField txtKullaniciAdi;
private JTextField txtSifre;
private JComboBox cmbYetki;
private JLabel lblKullanciAdi;
private JLabel lblSifre;
private JLabel lblYetki;
public KullaniciDegistirme(MouseEvent e, Kullanici kullanici) {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
parentFrame.parentFrame.setEnabled(true);
parentFrame.tabloyuDoldur();
parentFrame.parentFrame.toFront();
}
});
this.kullanici = kullanici;
this.parentComponent = (JComponent) e.getSource();
this.parentFrame = (KullaniciIslemleriPaneli) parentComponent.getParent().getParent().getParent().getParent();
setTitle("Distributor Bilgileri Değiştirme Ekranı");
setSize(332, 186);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
getContentPane().add(getPanel(), BorderLayout.CENTER);
alanlariDoldur();
}
private void alanlariDoldur() {
txtKullaniciAdi.setText(kullanici.getKullaniciAdi());
txtSifre.setText(kullanici.getSifre());
cmbYetki.setModel(new DefaultComboBoxModel(Yetkiler.values()));
if (kullanici.getYetki() != null) {
cmbYetki.setSelectedItem(kullanici.getYetki());
} else {
cmbYetki.setSelectedIndex(-1);
}
}
private JPanel getPanel() {
if (panel == null) {
panel = new JPanel();
panel.setLayout(null);
panel.add(getBtnKaydet());
panel.add(getBtnIptal());
panel.add(getBtnSil());
panel.add(getTxtKullaniciAdi());
panel.add(getTxtSifre());
panel.add(getCmbYetki());
panel.add(getLblKullanciAdi());
panel.add(getLblSifre());
panel.add(getLblYetki());
}
return panel;
}
private JButton getBtnKaydet() {
if (btnKaydet == null) {
btnKaydet = new JButton("KAYDET");
btnKaydet.setBounds(36, 110, 80, 20);
btnKaydet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DbServicessBase<Kullanici> dao = new DbServicessBase<Kullanici>();
Kullanici degiseKullanici = new Kullanici();
degiseKullanici.setId(kullanici.getId());
;
degiseKullanici.setKullaniciAdi(txtKullaniciAdi.getText());
degiseKullanici.setSifre(txtSifre.getText());
degiseKullanici.setYetki((Yetkiler) cmbYetki.getSelectedItem());
if (dao.update(degiseKullanici)) {
showMessageDialog(null, "Kaydetme İşlemi Başarılı!");
KullaniciDegistirme.this.dispose();
} else {
showMessageDialog(null, "Kaydetme İşlemi Başarısız Oldu!");
}
}
});
}
return btnKaydet;
}
private JButton getBtnIptal() {
if (btnIptal == null) {
btnIptal = new JButton("\u0130PTAL");
btnIptal.setBounds(222, 110, 80, 20);
btnIptal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
KullaniciDegistirme.this.dispose();
}
});
}
return btnIptal;
}
private JButton getBtnSil() {
if (btnSil == null) {
btnSil = new JButton("S\u0130L");
btnSil.setBounds(129, 110, 80, 20);
btnSil.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DbServicessBase<Kullanici> dao = new DbServicessBase<Kullanici>();
if (dao.delete(kullanici)) {
KullaniciDegistirme.this.dispose();
} else {
showMessageDialog(null, "Silme İşlemi Başarısız Oldu!");
}
}
});
}
return btnSil;
}
private JTextField getTxtKullaniciAdi() {
if (txtKullaniciAdi == null) {
txtKullaniciAdi = new JTextField();
txtKullaniciAdi.setBounds(90, 13, 212, 20);
txtKullaniciAdi.setColumns(10);
}
return txtKullaniciAdi;
}
private JTextField getTxtSifre() {
if (txtSifre == null) {
txtSifre = new JTextField();
txtSifre.setText("");
txtSifre.setBounds(90, 46, 212, 20);
txtSifre.setColumns(10);
}
return txtSifre;
}
private JComboBox getCmbYetki() {
if (cmbYetki == null) {
cmbYetki = new JComboBox();
cmbYetki.setBounds(90, 79, 212, 20);
}
return cmbYetki;
}
private JLabel getLblKullanciAdi() {
if (lblKullanciAdi == null) {
lblKullanciAdi = new JLabel("Kullan\u0131c\u0131 Ad\u0131 :");
lblKullanciAdi.setHorizontalAlignment(SwingConstants.RIGHT);
lblKullanciAdi.setLabelFor(getTxtKullaniciAdi());
lblKullanciAdi.setBounds(10, 13, 70, 20);
}
return lblKullanciAdi;
}
private JLabel getLblSifre() {
if (lblSifre == null) {
lblSifre = new JLabel("\u015Eifre :");
lblSifre.setHorizontalAlignment(SwingConstants.RIGHT);
lblSifre.setLabelFor(getTxtSifre());
lblSifre.setBounds(10, 46, 70, 20);
}
return lblSifre;
}
private JLabel getLblYetki() {
if (lblYetki == null) {
lblYetki = new JLabel("Yetki :");
lblYetki.setHorizontalAlignment(SwingConstants.RIGHT);
lblYetki.setLabelFor(getCmbYetki());
lblYetki.setBounds(10, 79, 70, 20);
}
return lblYetki;
}
}
|
package trees.citrus;
public class RCU {
static private int numThreads;
static private RCUNode rcuTable[];
static public void initRCU(int runNumThreads) {
numThreads = runNumThreads;
rcuTable = new RCUNode[runNumThreads];
for( int i=0; i < runNumThreads ; i++){
rcuTable[i] = new RCUNode();
}
}
static private final ThreadLocal<Integer> id = new ThreadLocal<Integer>();
static private final ThreadLocal<Long[]> threadTimes = new ThreadLocal<Long[]>();
static public void register(int thread_id){
id.set(thread_id);
threadTimes.set(new Long[numThreads]);
}
static public void unregister(){
//do nothing
}
static public void rcuReadLock(){
rcuTable[id.get()].lock();
}
static public void rcuReadUnlock(){
rcuTable[id.get()].unlock();
}
static public void synchronize(){
Long[] times = threadTimes.get();
for( int i=0; i < numThreads ; i++){
times[i] = rcuTable[i].getTime();
}
for( int i=0; i < numThreads ; i++){
if((times[i] & 1) !=0) continue;
while(true){
long t = rcuTable[i].getTime();
if((t & 1) !=0 || t > times[i]){
break;
}
}
}
}
}
|
package fr.cg95.cvq.service.request.ecitizen;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.*;
import fr.cg95.cvq.business.authority.School;
import fr.cg95.cvq.business.request.RequestState;
import fr.cg95.cvq.business.request.RequestType;
import fr.cg95.cvq.business.request.ecitizen.HomeFolderModificationRequest;
import fr.cg95.cvq.business.request.school.SchoolRegistrationRequest;
import fr.cg95.cvq.business.users.Address;
import fr.cg95.cvq.business.users.Adult;
import fr.cg95.cvq.business.users.Child;
import fr.cg95.cvq.business.users.CreationBean;
import fr.cg95.cvq.business.users.FamilyStatusType;
import fr.cg95.cvq.business.users.HistoryEntry;
import fr.cg95.cvq.business.users.HomeFolder;
import fr.cg95.cvq.business.users.Individual;
import fr.cg95.cvq.business.users.IndividualRole;
import fr.cg95.cvq.business.users.RoleType;
import fr.cg95.cvq.business.users.SectionType;
import fr.cg95.cvq.business.users.SexType;
import fr.cg95.cvq.business.users.TitleType;
import fr.cg95.cvq.dao.users.IHistoryEntryDAO;
import fr.cg95.cvq.exception.CvqException;
import fr.cg95.cvq.exception.CvqObjectNotFoundException;
import fr.cg95.cvq.security.SecurityContext;
import fr.cg95.cvq.service.request.IRequestService;
import fr.cg95.cvq.service.request.RequestTestCase;
import fr.cg95.cvq.util.development.BusinessObjectsFactory;
/**
* The tests for the home folder modification request service.
*
* @author bor@zenexity.fr
*/
public class HomeFolderModificationRequestServiceTest extends RequestTestCase {
@Resource(name="homeFolderModificationRequestService")
protected IRequestService homeFolderModificationRequestService;
@Resource(name="schoolRegistrationRequestService")
protected IRequestService schoolRegistrationRequestService;
@Autowired
protected IHistoryEntryDAO historyEntryDAO;
// define some objects that will be reused throughout the different tests
private Address adress;
private List<Adult> adults;
private List<Child> children;
private HomeFolder homeFolder;
private HomeFolderModificationRequest hfmr;
private String proposedLogin;
private Child newChild;
private Adult newAdult;
// Useful to clean individual who do not belong to homeFolder in onTearDown
protected Set< Long> foreignOwnersIds = new HashSet<Long>();
/**
* Overrided to run invariant tests.
*/
@Override
public void onTearDown() throws Exception {
continueWithNewTransaction();
try {
// check entries have been deleted from history table
List<HistoryEntry> remainingEntries = historyEntryDAO.listByRequestId(hfmr.getId());
assertEquals(0, remainingEntries.size());
} catch (Exception e) {
// just catch and let tear down go up to his parent
}
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.delete(hfmr.getId());
Iterator<Long> it = foreignOwnersIds.iterator();
while (it.hasNext()) {
Adult a = individualService.getAdultById(it.next());
individualService.delete(a);
it.remove();
}
super.onTearDown();
}
private void createModificationRequest() throws CvqException {
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.FRONT_OFFICE_CONTEXT);
// create a vo card request (to create home folder and associates)
CreationBean cb = gimmeAnHomeFolderWithRequest();
Long requestId = cb.getRequestId();
proposedLogin = cb.getLogin();
// be an agent to perform request state changes
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(requestId, RequestState.COMPLETE, null);
requestWorkflowService.updateRequestState(requestId, RequestState.VALIDATED, null);
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.FRONT_OFFICE_CONTEXT);
SecurityContext.setCurrentEcitizen(proposedLogin);
// get the home folder id
homeFolder = homeFolderService.getById(cb.getHomeFolderId());
// create the home folder modification request
hfmr = new HomeFolderModificationRequest();
// prepare objects for modifications
adress = homeFolder.getAdress();
List<Individual> individuals = homeFolder.getIndividuals();
adults = new ArrayList<Adult>();
children = new ArrayList<Child>();
for (Individual individual : individuals) {
if (individual instanceof Child)
children.add((Child) individual);
else
adults.add((Adult) individual);
}
}
@Test
public void testMultiHibernateTransaction()
throws CvqException {
createModificationRequest();
continueWithNewTransaction();
List<Adult> copyAdults = new ArrayList<Adult>();
List<Child> copyChildren = new ArrayList<Child>();
for (Individual individual : homeFolder.getIndividuals()) {
if (individual instanceof Adult)
copyAdults.add((Adult)individual);
else if (individual instanceof Child)
copyChildren.add((Child)individual );
}
List<Adult> foreignOwners = new ArrayList<Adult>();
foreignOwners.add(BusinessObjectsFactory.gimmeAdult(TitleType.MADAM, "TUTOR", "Foreign",
address.clone(), FamilyStatusType.OTHER));
homeFolderService.addHomeFolderRole(foreignOwners.get(0), homeFolder.getId(),
RoleType.HOME_FOLDER_RESPONSIBLE);
continueWithNewTransaction();
requestWorkflowService.createAccountModificationRequest(hfmr, copyAdults, copyChildren,
foreignOwners, adress, null, null);
assertEquals(copyAdults.size() + copyChildren.size(),
homeFolder.getIndividuals().size());
continueWithNewTransaction();
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.COMPLETE, null);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.VALIDATED, null);
continueWithNewTransaction();
for (Adult adult : foreignOwners)
foreignOwnersIds.add(adult.getId());
}
private void prepareSimpleModifications()
throws CvqException {
createModificationRequest();
// start modifications ...
// ... on an adult
homeFolderUncle.setFirstName("Yarglaa");
homeFolderUncle.setFirstName3("Groumph");
homeFolderUncle.setProfession("Entraineur du PSG");
homeFolderUncle.setSex(SexType.FEMALE);
homeFolderUncle.setBirthDate(new Date());
Address newAdress =
BusinessObjectsFactory.gimmeAdress("1","Rue du centre",
"Drancy", "93700");
homeFolderUncle.setAdress(newAdress);
Adult testReloadedWoman = individualService.getAdultById(homeFolderWoman.getId());
testReloadedWoman.setFirstName2("Angélique");
List<Adult> newAdults = new ArrayList<Adult>();
newAdults.add(homeFolderUncle);
newAdults.add(homeFolderResponsible);
newAdults.add(testReloadedWoman);
// ... and on the adress
adress.setPostalCode("75013");
adress.setCity("Paris Ville Lumière");
requestWorkflowService.createAccountModificationRequest(hfmr, newAdults, children,
null, adress, null, null);
}
@Test
public void testSimpleModificationsValidated()
throws CvqException {
prepareSimpleModifications();
continueWithNewTransaction();
// now retrieve and display them
HomeFolderModificationRequest hfmrFromDb =
(HomeFolderModificationRequest) requestSearchService.getById(hfmr.getId(), false);
homeFolder = homeFolderService.getById(hfmrFromDb.getHomeFolderId());
adress = homeFolder.getAdress();
assertEquals(adress.getPostalCode(), "75013");
assertEquals(adress.getCity(), "Paris Ville Lumière".toUpperCase());
List<Individual> individuals = homeFolder.getIndividuals();
for (Individual individual : individuals) {
if (individual.getId().equals(homeFolderUncle.getId())) {
assertEquals(homeFolderUncle.getFirstName3(), "Groumph");
assertEquals(homeFolderUncle.getProfession(), "Entraineur du PSG");
}
}
continueWithNewTransaction();
// validate request and check we did not loose any information
// (be an agent to perform this state change)
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.COMPLETE, null);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.VALIDATED, null);
continueWithNewTransaction();
// check modifications are still there
hfmrFromDb =
(HomeFolderModificationRequest) requestSearchService.getById(hfmr.getId(), false);
homeFolder = homeFolderService.getById(hfmrFromDb.getHomeFolderId());
adress = homeFolder.getAdress();
assertEquals(adress.getPostalCode(), "75013");
assertEquals(adress.getCity(), "Paris Ville Lumière".toUpperCase());
}
@Test
public void testSimpleModificationsCancelled()
throws CvqException {
prepareSimpleModifications();
continueWithNewTransaction();
// cancel request and check we got back to the original state
// (be an agent to perform this state change)
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.CANCELLED, null);
continueWithNewTransaction();
HomeFolderModificationRequest hfmrFromDb =
(HomeFolderModificationRequest) requestSearchService.getById(hfmr.getId(), false);
homeFolder = homeFolderService.getById(hfmrFromDb.getHomeFolderId());
adress = homeFolder.getAdress();
assertEquals(adress.getPostalCode(), "75012");
assertEquals(adress.getCity(), "Paris".toUpperCase());
List<Individual> individuals = homeFolder.getIndividuals();
for (Individual individual : individuals) {
if (individual.getId().equals(homeFolderUncle.getId())) {
assertEquals(individual.getLastName(), "LASTNAME");
assertTrue(individual.getFirstName().startsWith("uncle"));
}
}
}
private void prepareChildAdultAddWithClr()
throws CvqException {
createModificationRequest();
newAdult = BusinessObjectsFactory.gimmeAdult(TitleType.MISTER, "adult", "new",
null, FamilyStatusType.SINGLE);
adults.add(newAdult);
homeFolderService.addIndividualRole(newAdult, child1, RoleType.CLR_TUTOR);
homeFolderService.removeIndividualRole(homeFolderUncle, child1,
RoleType.CLR_TUTOR);
newChild = BusinessObjectsFactory.gimmeChild("child", "new");
homeFolderService.addIndividualRole(homeFolderResponsible,
newChild, RoleType.CLR_FATHER);
homeFolderService.addIndividualRole(newAdult, newChild, RoleType.CLR_TUTOR);
children.add(newChild);
requestWorkflowService.createAccountModificationRequest(hfmr, adults, children,
null, adress, null, null);
}
@Test
public void testChildAdultAddWithClrValidated()
throws CvqException {
prepareChildAdultAddWithClr();
continueWithNewTransaction();
// be an agent to perform request state changes
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.COMPLETE, null);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.VALIDATED, null);
continueWithNewTransaction();
// become back an ecitizen to retrieve information
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.FRONT_OFFICE_CONTEXT);
SecurityContext.setCurrentEcitizen(proposedLogin);
Adult adult = individualService.getAdultById(newAdult.getId());
assertNotNull(adult);
assertNotNull(adult.getIndividualRoles());
assertEquals(2, adult.getIndividualRoles().size());
IndividualRole individualRole = adult.getIndividualRoles().iterator().next();
if (individualRole.getIndividualId().equals(child1.getId())) {
assertEquals(RoleType.CLR_TUTOR, individualRole.getRole());
assertEquals(child1.getId(), individualRole.getIndividualId());
} else if (individualRole.getIndividualId().equals(newChild.getId())) {
assertEquals(RoleType.CLR_TUTOR, individualRole.getRole());
assertEquals(newChild.getId(), individualRole.getIndividualId());
} else {
fail("should have been one of above");
}
}
@Test
public void testChildAdultAddWithClrCancelled()
throws CvqException {
prepareChildAdultAddWithClr();
continueWithNewTransaction();
List<Individual> individuals =
homeFolderService.getBySubjectRole(child1.getId(), RoleType.CLR_TUTOR);
assertEquals(1, individuals.size());
assertEquals(newAdult.getId(), individuals.get(0).getId());
// be an agent to perform request state changes
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.CANCELLED, null);
continueWithNewTransaction();
try {
individualService.getById(newAdult.getId());
fail("should have thrown an exception");
} catch (CvqObjectNotFoundException confe) {
// that was expected
}
individuals = homeFolderService.getBySubjectRole(child1.getId(), RoleType.CLR_TUTOR);
assertEquals(1, individuals.size());
assertEquals(homeFolderUncle.getId(), individuals.get(0).getId());
}
private void prepareChildrenAddRemove()
throws CvqException {
createModificationRequest();
children.remove(child2);
child1.setBirthCity("Paris");
newChild = BusinessObjectsFactory.gimmeChild("Badiane", "XXXX");
homeFolderService.addIndividualRole(homeFolderResponsible,
newChild, RoleType.CLR_FATHER);
homeFolderService.addIndividualRole(homeFolderWoman,
newChild, RoleType.CLR_MOTHER);
homeFolderService.addIndividualRole(homeFolderUncle,
newChild, RoleType.CLR_TUTOR);
children.add(newChild);
requestWorkflowService.createAccountModificationRequest(hfmr, adults, children,
null, adress, null, null);
}
@Test
public void testChildrenAddRemoveValidated()
throws Exception {
prepareChildrenAddRemove();
continueWithNewTransaction();
assertNotNull(newChild.getId());
// used to resync home folder responsible wrt home folder state
homeFolderResponsible =
homeFolderService.getHomeFolderResponsible(hfmr.getHomeFolderId());
SecurityContext.setCurrentEcitizen(homeFolderResponsible);
// check modifications have been saved
children = homeFolderService.getChildren(homeFolder.getId());
assertEquals(2, children.size());
RoleType[] roles = {RoleType.CLR_FATHER, RoleType.CLR_MOTHER, RoleType.CLR_TUTOR };
for (Child child : children) {
if (child.getFirstName().equals(child1.getFirstName())) {
assertEquals(child.getBirthCity(), "Paris");
assertEquals(3, homeFolderService.getBySubjectRoles(child.getId(), roles).size());
} else if (child.getFirstName().equals(newChild.getFirstName())) {
assertEquals(child.getLastName(), "Badiane");
assertEquals(3, homeFolderService.getBySubjectRoles(child.getId(), roles).size());
} else {
fail("Don't know this child : " + child);
}
}
continueWithNewTransaction();
// be an agent to perform request state changes
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.COMPLETE, null);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.VALIDATED, null);
continueWithNewTransaction();
// become back an ecitizen to retrieve information
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.FRONT_OFFICE_CONTEXT);
SecurityContext.setCurrentEcitizen(proposedLogin);
// check modifications are still saved
children = homeFolderService.getChildren(homeFolder.getId());
assertEquals(2, children.size());
for (Child child : children) {
if (child.getFirstName().equals(child1.getFirstName())) {
assertEquals(child.getBirthCity(), "Paris");
assertEquals(3, homeFolderService.getBySubjectRoles(child.getId(), roles).size());
} else if (child.getFirstName().equals(newChild.getFirstName())) {
assertEquals(child.getLastName(), "Badiane");
assertEquals(3, homeFolderService.getBySubjectRoles(child.getId(), roles).size());
} else {
fail("Don't know this child : " + child);
}
}
}
@Test
public void testChildrenAddRemoveCancelled()
throws Exception {
prepareChildrenAddRemove();
continueWithNewTransaction();
// be an agent to perform request state changes
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.CANCELLED, null);
continueWithNewTransaction();
// become back an ecitizen to retrieve information
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.FRONT_OFFICE_CONTEXT);
SecurityContext.setCurrentEcitizen(proposedLogin);
// check modifications have been effectively cancelled
HomeFolderModificationRequest hfmrFromDb =
(HomeFolderModificationRequest) requestSearchService.getById(hfmr.getId(), false);
homeFolder = homeFolderService.getById(hfmrFromDb.getHomeFolderId());
children = homeFolderService.getChildren(homeFolder.getId());
assertEquals(2, children.size());
RoleType[] roles = {RoleType.CLR_FATHER, RoleType.CLR_MOTHER, RoleType.CLR_TUTOR };
for (Child child : children) {
assertNotSame(child.getFirstName(), "XXXX");
assertNotNull(child.getAdress());
assertEquals(child.getLastName(), "LASTNAME");
if (child.getFirstName().equals("childone")) {
assertEquals(3, homeFolderService.getBySubjectRoles(child.getId(), roles).size());
} else if (child.getFirstName().equals("childtwo")) {
assertEquals(1, homeFolderService.getBySubjectRoles(child.getId(), roles).size());
}
}
}
private void prepareSimpleAdultsAddRemove()
throws CvqException {
createModificationRequest();
// remove an adult and add a new one
adults.remove(homeFolderUncle);
Address newAdress =
BusinessObjectsFactory.gimmeAdress("1","Rue des Ecoles", "Paris", "75005");
Adult newAdult = BusinessObjectsFactory.gimmeAdult(TitleType.MISTER,"adult",
"new", newAdress, FamilyStatusType.SINGLE);
newAdult.setPassword("toto");
adults.add(newAdult);
requestWorkflowService.createAccountModificationRequest(hfmr, adults, children,
null, adress, null, null);
}
@Test
public void testSimpleAdultsAddRemoveValidated()
throws CvqException {
prepareSimpleAdultsAddRemove();
continueWithNewTransaction();
// check modifications have been saved
List<Adult> allAdults = homeFolderService.getAdults(homeFolder.getId());
assertEquals(3, allAdults.size());
assertFalse(allAdults.contains(homeFolderUncle));
continueWithNewTransaction();
// be an agent to perform request state changes
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.COMPLETE, null);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.VALIDATED, null);
continueWithNewTransaction();
// check removed adult has been deleted from DB
try {
individualService.getById(homeFolderUncle.getId());
fail("Adult should have been removed");
} catch (CvqObjectNotFoundException confe) {
// that's what we expected
}
// check new adult and its specific adress are well stored
allAdults = homeFolderService.getAdults(homeFolder.getId());
assertEquals(3, allAdults.size());
boolean foundNewAdult = false;
for (Adult tempAdult : allAdults) {
if (tempAdult.getLastName().equals("adult")) {
foundNewAdult = true;
assertNotNull(tempAdult.getAdress());
assertEquals("75005", tempAdult.getAdress().getPostalCode());
}
}
if (!foundNewAdult)
fail("Newly added adult has not been found in home folder");
}
@Test
public void testSimpleAdultsAddRemoveCancelled()
throws CvqException {
prepareSimpleAdultsAddRemove();
continueWithNewTransaction();
// be an agent to perform request state changes
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.CANCELLED, null);
continueWithNewTransaction();
// check removed adult has been restored
try {
individualService.getById(homeFolderUncle.getId());
} catch (CvqObjectNotFoundException confe) {
fail("Adult should have been restored");
}
}
private void prepareHomeFolderResponsibleChange()
throws CvqException {
createModificationRequest();
Adult responsibleToRemove =
homeFolderService.getHomeFolderResponsible(homeFolder.getId());
adults.remove(responsibleToRemove);
homeFolderService.addHomeFolderRole(homeFolderUncle, homeFolder.getId(),
RoleType.HOME_FOLDER_RESPONSIBLE);
homeFolderService.addIndividualRole(homeFolderUncle, child2, RoleType.CLR_FATHER);
homeFolderUncle.setPassword("toto");
homeFolderService.removeHomeFolderRole(responsibleToRemove,
homeFolder.getId(), RoleType.HOME_FOLDER_RESPONSIBLE);
requestWorkflowService.createAccountModificationRequest(hfmr, adults, children,
null, adress, null, null);
}
@Test
public void testHomeFolderResponsibleChangeValidated()
throws CvqException {
prepareHomeFolderResponsibleChange();
continueWithNewTransaction();
// be an agent to perform request state changes
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.COMPLETE, null);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.VALIDATED, null);
continueWithNewTransaction();
homeFolder = homeFolderService.getById(homeFolder.getId());
adults = homeFolderService.getAdults(homeFolder.getId());
assertEquals(adults.size(), 2);
Adult homeFolderResponsible =
homeFolderService.getHomeFolderResponsible(homeFolder.getId());
assertEquals(homeFolderResponsible.getLastName(), homeFolderUncle.getLastName());
assertEquals(homeFolderResponsible.getFirstName(), homeFolderUncle.getFirstName());
}
@Test
public void testHomeFolderResponsibleChangeCancelled()
throws CvqException {
prepareHomeFolderResponsibleChange();
continueWithNewTransaction();
// be an agent to perform request state changes
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(hfmr.getId(), RequestState.CANCELLED, null);
continueWithNewTransaction();
homeFolder = homeFolderService.getById(homeFolder.getId());
adults = homeFolderService.getAdults(homeFolder.getId());
assertEquals(adults.size(), 3);
Adult homeFolderResponsible =
homeFolderService.getHomeFolderResponsible(homeFolder.getId());
assertEquals(homeFolderResponsible.getLastName(), "LASTNAME");
assertEquals(homeFolderResponsible.getFirstName(), "responsible");
}
/**
* A side effect noticed on production : an home folder with a child registered to school.
* if the home folder issue an home folder modification request then the child reappears
* in the list of subjects authorized to issue a school registration request.
*
* TODO - org.hibernate.StaleObjectStateException occur on iHomeFolderModificationRequestService.modify()
*/
public void _testSchoolRegistrationsSideEffect()
throws CvqException {
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.FRONT_OFFICE_CONTEXT);
// create a vo card request (to create home folder and associates)
CreationBean cb = gimmeAnHomeFolderWithRequest();
Long requestId = cb.getRequestId();
proposedLogin = cb.getLogin();
continueWithNewTransaction();
// be an agent to perform request state changes
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(requestId, RequestState.COMPLETE, null);
requestWorkflowService.updateRequestState(requestId, RequestState.VALIDATED, null);
continueWithNewTransaction();
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.FRONT_OFFICE_CONTEXT);
SecurityContext.setCurrentEcitizen(proposedLogin);
// get the home folder id
homeFolder = homeFolderService.getById(cb.getHomeFolderId());
Long homeFolderId = homeFolder.getId();
assertNotNull(homeFolderId);
// register a child to school
// get a school for our school and canteen registrations
List<School> schools = schoolService.getAll();
if (schools == null || schools.isEmpty())
fail("No school created in the system, can't go further");
School school = schools.get(0);
// fill the child with the most we can
child1.setNote("Coucou, je suis l'enfant child1");
child1.setBirthPostalCode("93240");
child1.setBirthCity("Livry-Gargan");
child1.setSex(SexType.MALE);
child1.setBadgeNumber("XXX111GGG");
SchoolRegistrationRequest srr = new SchoolRegistrationRequest();
srr.setCurrentSchoolName("Ecolde des Yarglas");
srr.setSection(SectionType.CP);
srr.setUrgencyPhone("0102030405");
srr.setSchool(school);
srr.setSubjectId(child1.getId());
srr.setRequesterId(SecurityContext.getCurrentUserId());
Long srrId = requestWorkflowService.create(srr, null, null, null);
continueWithNewTransaction();
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.updateRequestState(srrId, RequestState.COMPLETE, null);
requestWorkflowService.updateRequestState(srrId, RequestState.VALIDATED, null);
continueWithNewTransaction();
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.FRONT_OFFICE_CONTEXT);
SecurityContext.setCurrentEcitizen(proposedLogin);
RequestType requestType =
requestTypeService.getRequestTypeByLabel(schoolRegistrationRequestService.getLabel());
Set<Long> authorizedSchoolRegistrations =
requestWorkflowService.getAuthorizedSubjects(requestType, homeFolderId).keySet();
assertEquals(1, authorizedSchoolRegistrations.size());
// create the home folder modification request
homeFolder = homeFolderService.getById(homeFolderId);
homeFolderResponsible =
homeFolderService.getHomeFolderResponsible(homeFolder.getId());
HomeFolderModificationRequest hfmr = new HomeFolderModificationRequest();
List<Adult> adultSet = new ArrayList<Adult>();
adultSet.add(homeFolderResponsible);
adultSet.add(homeFolderWoman);
adultSet.add(homeFolderUncle);
List<Child> childSet = new ArrayList<Child>();
childSet.add(child1);
childSet.add(child2);
Address newAdress =
BusinessObjectsFactory.gimmeAdress("1","Rue du centre", "Drancy", "93700");
requestWorkflowService.createAccountModificationRequest(hfmr, adultSet, childSet,
null, newAdress, null, null);
continueWithNewTransaction();
authorizedSchoolRegistrations =
requestWorkflowService.getAuthorizedSubjects(requestType, homeFolderId).keySet();
assertEquals(1, authorizedSchoolRegistrations.size());
// that's ok, cancel the home folder modification request
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
requestWorkflowService.delete(srrId);
}
}
|
package tw.org.iii.java;
import tw.org.iii.myclass.Bike;
public class Brad34 {
public static void main(String[] args) {
Bike b1;
b1 = new Bike();
System.out.println(b1.getColor());
}
}
|
package org.fao.unredd.api.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.fao.unredd.api.json.LayerUpdatesResponseRoot;
import org.fao.unredd.api.model.LayerUpdates;
import org.fao.unredd.api.model.Layers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Path("/layers/{layerId}/layerupdates")
public class LayerLayerUpdateListResource extends AbstractLayerBasedResource {
@Autowired
private Layers layers;
@GET
@Produces(MediaType.APPLICATION_JSON)
public LayerUpdatesResponseRoot asJSON(@PathParam("layerId") String layerId) {
LayerUpdates updates = getLayer(layers, layerId).getLayerUpdates();
return new LayerUpdatesResponseRoot(updates.getJSON());
}
}
|
package com.kgitbank.spring.domain.chat.dto;
import lombok.Data;
@Data
public class ChattingUser {
private int roomId;
private int seqId;
private String id;
}
|
/*
* Copyright 2007 Jens Dietrich
* 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 example.nz.org.take.compiler.eurent;
/**
* Domain class implemented as PLOJO (plain old Java object).
* @author <a href="http://www-ist.massey.ac.nz/JBDietrich/">Jens Dietrich</a>
*/
public class Rental {
private String id = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
|
public class Optimizations {
private static final int radix = 10;
public static void main(final String[] args) {
System.out.println(1+1);
System.out.println(radix * 1);
System.out.println("var" + 1);
}
}
|
package monopoly.view;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import monopoly.controller.StartGameController;
import monopoly.model.Model;
import monopoly.model.bank.Bank;
import monopoly.model.bank.StandardBank;
import monopoly.model.board.StandardBoard;
import monopoly.model.deck.ChanceCardDeck;
import monopoly.model.deck.CommunityCardDeck;
import monopoly.model.deck.card.Card;
import monopoly.model.deck.card.ChanceCard;
import monopoly.model.deck.card.CommunityCard;
import monopoly.model.dice.StandardDice;
import monopoly.model.dice.TwoStandardDices;
import monopoly.model.player.Player;
import monopoly.model.player.changer.SequentialPlayerChanger;
import monopoly.util.logger.InGameLogger;
import monopoly.util.random.JavaRandom;
import monopoly.viewmodel.ViewModel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Bank bank = new StandardBank();
StandardBoard board = new StandardBoard(bank);
TwoStandardDices dices = new TwoStandardDices(new StandardDice(new JavaRandom()),
new StandardDice(new JavaRandom()));
SequentialPlayerChanger playerChanger = new SequentialPlayerChanger(Arrays.asList(new Player("", 1500),
new Player("", 1500), new Player("", 1500), new Player("", 1500)));
InGameLogger logger = new InGameLogger();
List<Card> communityCards = new ArrayList<>();
List<Card> chanceCards = new ArrayList<>();
for (int i=1; i<=17; i++) {
chanceCards.add(new ChanceCard(i, playerChanger, board, new Random()));
if (i<17) {
communityCards.add(new CommunityCard(i, playerChanger, board));
}
}
ChanceCardDeck chanceCardDeck = new ChanceCardDeck(chanceCards);
CommunityCardDeck communityCardDeck = new CommunityCardDeck(communityCards);
Model model = new Model(board, dices, playerChanger, logger, chanceCardDeck, communityCardDeck, bank);
ViewModel viewModel = new ViewModel(model);
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("StartGameFrame.fxml"));
loader.setControllerFactory(aClass -> new StartGameController(viewModel));
Parent root = loader.load();
primaryStage.setTitle("Start monopoly");
primaryStage.setMinHeight(556);
primaryStage.setMinWidth(800);
Scene scene = new Scene(root, 800, 556);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
package com.tencent.mm.ui.chatting.g;
class e$14 implements Runnable {
final /* synthetic */ e tYu;
e$14(e eVar) {
this.tYu = eVar;
}
public final void run() {
if (e.c(this.tYu) != null) {
e.c(this.tYu).cwC();
}
}
}
|
package com.springBlog.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by Emanuele on 28/12/2016.
*/
@Controller
@RequestMapping("/")
public class FrontController {
@RequestMapping(path = "/home", method = RequestMethod.GET)
public String home(Model model){
model.addAttribute("name", "Emanuele");
return "home";
}
@RequestMapping(path = "/posts", method = RequestMethod.GET)
public String posts(Model model){
return "posts";
}
@RequestMapping(path = "/posts/{id}", method = RequestMethod.GET)
public String getPost(Model model){
return "singlePost";
}
@RequestMapping(path = "/about", method = RequestMethod.GET)
public String about(Model model){
return "about";
}
@RequestMapping(path = "/contact", method = RequestMethod.GET)
public String contact(Model model){
return "contact";
}
}
|
package br.edu.ifam.saf.api.data;
public class ItemRelatorio {
private String descricao;
private Double valor;
public ItemRelatorio(String descricao, Double valor) {
this.descricao = descricao;
this.valor = valor;
}
public ItemRelatorio() {
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Double getValor() {
return valor;
}
public void setValor(Double valor) {
this.valor = valor;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ItemRelatorio that = (ItemRelatorio) o;
if (descricao != null ? !descricao.equals(that.descricao) : that.descricao != null)
return false;
return valor != null ? valor.equals(that.valor) : that.valor == null;
}
@Override
public int hashCode() {
int result = descricao != null ? descricao.hashCode() : 0;
result = 31 * result + (valor != null ? valor.hashCode() : 0);
return result;
}
}
|
package Display;
public class Interface
{
public static void main(String[] args)
{
Aj obj=new Ak();
obj.show();
//obj.ipl(); //coz we created the object Aj as the reference.
}
}
interface Aj
{
public void show();
}
class Ak implements Aj
{
public void show()
{
System.out.println("Show has been overidden.");
}
public void ipl()
{
System.out.println("Ipl 2020 has been cancelled due to COVID 19 spread.");
}
}
|
package com.pskwiercz;
/**
* Created by pskwierc on 28/12/2016.
*/
public interface Expression {
Expression plus(Expression add);
Expression times(int multipler);
Money reduce(Bank bank, String to);
}
|
package com.tencent.mm.plugin.appbrand.jsapi;
import com.tencent.mm.plugin.appbrand.jsapi.d.3;
class d$3$1 implements Runnable {
final /* synthetic */ 3 fEW;
d$3$1(3 3) {
this.fEW = 3;
}
public final void run() {
if (this.fEW.fEP.fEJ != null && this.fEW.fEP.fEJ.isRunning()) {
d.a(this.fEW.fEP, this.fEW.fES, this.fEW.fET, this.fEW.doP, this.fEW.fEU);
}
}
}
|
package com.example.OCP.advancedClassDesing.nestedClasses.localInnerClass;
/**
* Created by guille on 10/14/18.
*/
/* LocalInnerClasses
They do not have an access specifier
They cannot be declare static and cannot have static methods or fields
They have access to all fields and methods of the enclosing class
They do not have access to local variables of a method unless those variables are final
*/
public class Outer {
private int length = 5;
public void calculate (){
final int width =20;
class Inner{
public void multiply () {
System.out.println(length * width);
}
}
System.out.println(width);
Inner inner = new Inner();
inner.multiply();
}
public static void main (String...args){
Outer outer = new Outer();
outer.calculate();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.config;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.BeanAttributes;
import org.apache.webbeans.exception.WebBeansConfigurationException;
import org.apache.webbeans.plugins.PluginLoader;
import org.apache.webbeans.spi.plugins.OpenWebBeansEjbPlugin;
public final class EJBWebBeansConfigurator
{
private EJBWebBeansConfigurator()
{
}
/**
* Returns true if given class is an deployed ejb bean class, false otherwise.
* @param clazz bean class
* @param webBeansContext
* @return true if given class is an deployed ejb bean class
* @throws WebBeansConfigurationException if any exception occurs
*/
public static boolean isSessionBean(Class<?> clazz, WebBeansContext webBeansContext) throws WebBeansConfigurationException
{
PluginLoader loader = webBeansContext.getPluginLoader();
OpenWebBeansEjbPlugin ejbPlugin = loader.getEjbPlugin();
//There is no ejb container
if(ejbPlugin == null)
{
return false;
}
return ejbPlugin.isSessionBean(clazz);
}
/**
* Returns ejb bean.
* @param webBeansContext
* @param <T> bean class info
* @param clazz bean class
* @return ejb bean
*/
public static <T> Bean<T> defineEjbBean(Class<T> clazz, AnnotatedType<T> annotatedType, BeanAttributes<T> attributes,
WebBeansContext webBeansContext)
{
PluginLoader loader = webBeansContext.getPluginLoader();
OpenWebBeansEjbPlugin ejbPlugin = loader.getEjbPlugin();
if(ejbPlugin == null)
{
throw new IllegalStateException("There is no provided EJB plugin. Unable to define session bean for class : " + clazz.getName());
}
return ejbPlugin.defineSessionBean(clazz, attributes, annotatedType);
}
}
|
package com.example.ninjagang;
import java.util.ArrayList;
import java.util.Random;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("NewApi")
public class level3 extends Activity {
public int play=1;
public int score=0;
ArrayList<Integer> i1 = new ArrayList<Integer>();
ArrayList<Integer> i2 = new ArrayList<Integer>();
@SuppressWarnings("unused")
private RelativeLayout rl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rl = (RelativeLayout) findViewById(R.id.frame);
// final Button button;
//final Button stop;
final TextView tv;
final ImageView iv,iv2,iv3,iv4,iv5,iv6,iv7;
// button = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.abc);
iv=(ImageView) findViewById(R.id.imageView1);
iv2=(ImageView) findViewById(R.id.playbtn);
iv3=(ImageView) findViewById(R.id.imageView3);
iv4=(ImageView) findViewById(R.id.imageView4);
iv5=(ImageView) findViewById(R.id.imageView5);
iv6=(ImageView) findViewById(R.id.imageView6);
iv7=(ImageView) findViewById(R.id.imageView7);
// stop=(Button)findViewById(R.id.button2);
// int width=rl.getWidth();
//int height = rl.getHeight();
Display display = getWindowManager().getDefaultDisplay();
@SuppressWarnings("deprecation")
int width = display.getWidth();
@SuppressWarnings("deprecation")
int height = display.getHeight();
// Toast.makeText(getApplicationContext()," "+height+" "+width, Toast.LENGTH_LONG).show();
if(height>80 && width >40)
{
height-=100;
width-=70;
}
// Toast.makeText(getApplicationContext()," " + height+" " + width, Toast.LENGTH_LONG).show();
Random r = new Random();
int i;
for(i=0;i<7;i++)
{
i2.add((r.nextInt(height)+30));
i1.add((r.nextInt(width)+30));
// Toast.makeText(getApplicationContext(),"data " + i1.get(i)+" " + i2.get(i), Toast.LENGTH_LONG).show();
}
iv.postDelayed(new Runnable() {
public void run() {
iv.setX(i1.get(0));
iv.setY(i2.get(0));
iv.setVisibility(View.VISIBLE);
}
}, 4000);
iv.postDelayed(new Runnable() {
public void run() {
iv.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),"1 " + score, Toast.LENGTH_LONG).show();
}
}, 4700);
iv2.postDelayed(new Runnable() {
public void run() {
iv2.setX(i1.get(1));
iv2.setY(i2.get(1));
iv2.setVisibility(View.VISIBLE);
}
}, 4700);
iv2.postDelayed(new Runnable() {
public void run() {
iv2.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),"2 " + score, Toast.LENGTH_LONG).show();
}
}, 5500);
iv3.postDelayed(new Runnable() {
public void run() {
iv3.setX(i1.get(2));
iv3.setY(i2.get(2));
iv3.setVisibility(View.VISIBLE);
}
}, 5500);
iv3.postDelayed(new Runnable() {
public void run() {
iv3.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),"3 " + score, Toast.LENGTH_LONG).show();
}
}, 63000);
iv4.postDelayed(new Runnable() {
public void run() {
iv4.setX(i1.get(3));
iv4.setY(i2.get(3));
iv4.setVisibility(View.VISIBLE);
}
}, 63000);
iv4.postDelayed(new Runnable() {
public void run() {
iv4.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),"4 " + score, Toast.LENGTH_LONG).show();
}
}, 7000);
iv5.postDelayed(new Runnable() {
public void run() {
iv5.setX(i1.get(4));
iv5.setY(i2.get(4));
iv5.setVisibility(View.VISIBLE);
}
}, 7000);
iv5.postDelayed(new Runnable() {
public void run() {
iv5.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),"5 " + score, Toast.LENGTH_LONG).show();
}
}, 7600);
iv6.postDelayed(new Runnable() {
public void run() {
iv6.setX(i1.get(5));
iv6.setY(i2.get(5));
iv6.setVisibility(View.VISIBLE);
}
}, 7600);
iv6.postDelayed(new Runnable() {
public void run() {
iv6.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),"6 " + score, Toast.LENGTH_LONG).show();
}
}, 8500);
iv7.postDelayed(new Runnable() {
public void run() {
iv7.setX(i1.get(6));
iv7.setY(i2.get(6));
iv7.setVisibility(View.VISIBLE);
}
}, 8500);
iv7.postDelayed(new Runnable() {
public void run() {
iv7.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),"7 "+score, Toast.LENGTH_LONG).show();
}
},9300);
/* stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"score "+score, Toast.LENGTH_LONG).show();
play=1;
stop.setEnabled(false);
button.setEnabled(true);
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//tv.setText("Kapil Rupavatiya");
iv.setVisibility(View.VISIBLE);
stop.setEnabled(true);
button.setEnabled(false);
play=0;
Toast.makeText(getApplicationContext(),"score "+score, Toast.LENGTH_LONG).show();
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
tv.setText("Kapil Rupavatiya");
stop.setVisibility(View.VISIBLE);
}
});
*/
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(play==0)
{
}
else
{
score +=3;
tv.setText(""+score);
iv.setVisibility(View.INVISIBLE);
}
}
});
iv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(play==0)
{
}
else
{
score +=5;
tv.setText(""+score);
iv2.setVisibility(View.INVISIBLE);
}
}
});
iv3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(play==0)
{
}
else
{
score +=6;
tv.setText(""+score);
iv3.setVisibility(View.INVISIBLE);
}
}
});
iv4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(play==0)
{
}
else
{
score +=3;
tv.setText(""+score);
iv4.setVisibility(View.INVISIBLE);
}
}
});
iv5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(play==0)
{
}
else
{
score +=5;
tv.setText(""+score);
iv5.setVisibility(View.INVISIBLE);
}
}
});
iv6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(play==0)
{
}
else
{
score +=6;
tv.setText(""+score);
iv6.setVisibility(View.INVISIBLE);
}
}
});
iv7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(play==0)
{
}
else
{
score +=6;
tv.setText(""+score);
iv7.setVisibility(View.INVISIBLE);
}
}
});
// Toast.makeText(getApplicationContext(),"score "+score, Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
|
package com.acculytixs.wayuparty.dto.vendor;
public class SpecialPackageDetailsDTO {
private String vendorUUID;
private String serviceType;
private String eventBannerImage;
private String eventMobileBannerImage;
public String getVendorUUID() {
return vendorUUID;
}
public void setVendorUUID(String vendorUUID) {
this.vendorUUID = vendorUUID;
}
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public String getEventBannerImage() {
return eventBannerImage;
}
public void setEventBannerImage(String eventBannerImage) {
this.eventBannerImage = eventBannerImage;
}
public String getEventMobileBannerImage() {
return eventMobileBannerImage;
}
public void setEventMobileBannerImage(String eventMobileBannerImage) {
this.eventMobileBannerImage = eventMobileBannerImage;
}
@Override
public String toString() {
return "SpecialPackageDetailsDTO [vendorUUID=" + vendorUUID + ", serviceType=" + serviceType
+ ", eventBannerImage=" + eventBannerImage + ", eventMobileBannerImage=" + eventMobileBannerImage + "]";
}
}
|
package orionlofty.com.apps.gadspracticeproject.fragments;
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.DialogFragment;
import orionlofty.com.apps.gadspracticeproject.R;
public class SuccessDialogFragment extends DialogFragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.custom_success_dialog, container);
}
public SuccessDialogFragment() {
}
}
|
/*
* 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 vasylts.blackjack.game;
/**
*
* @author VasylcTS
*/
public class Bet {
private double bet;
public Bet(double bet) {
this.bet = bet;
}
/**
* @return the bet
*/
public double getBet() {
return bet;
}
/**
* @param bet the bet to set
*/
public void setBet(double bet) {
this.bet = bet;
}
public double addToBet(double addBet) {
bet += addBet;
return bet;
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* SReportData generated by hbm2java
*/
public class SReportData implements java.io.Serializable {
private SReportDataId id;
public SReportData() {
}
public SReportData(SReportDataId id) {
this.id = id;
}
public SReportDataId getId() {
return this.id;
}
public void setId(SReportDataId id) {
this.id = id;
}
}
|
package sk.itsovy.strausz.projectdp;
public class Casein implements Protein {
@Override
public void print() {
System.out.println("Iam casein protein.");
}
}
|
package com.tencent.mm.plugin.sns.ui;
import com.tencent.mm.sdk.platformtools.x;
class SnsTimeLineUI$26 implements Runnable {
final /* synthetic */ SnsTimeLineUI odw;
SnsTimeLineUI$26(SnsTimeLineUI snsTimeLineUI) {
this.odw = snsTimeLineUI;
}
public final void run() {
x.i("MicroMsg.SnsTimeLineUI", "onResume go to playAnim " + SnsTimeLineUI.B(this.odw));
if (SnsTimeLineUI.B(this.odw)) {
SnsTimeLineUI.C(this.odw);
SnsTimeLineUI.D(this.odw).bEj();
}
}
}
|
package utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class ConnectionUtil {
private static String driver;
private static String url;
private static String user;
private static String password;
static {
InputStream is = ConnectionUtil.class
.getResourceAsStream("db.properties");
Properties p = new Properties();
try {
p.load(is);
driver = p.getProperty("DRIVER");
url = p.getProperty("URL");
user = p.getProperty("USER");
password = p.getProperty("PASSWORD");
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
e.getStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void close(Connection con, Statement stmt, ResultSet rs)
throws SQLException {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (con != null)
con.close();
}
public static void close1(Connection con, Statement stmt, Statement stmt2)
throws SQLException {
if (stmt != null)
stmt.close();
if (stmt2 != null)
stmt2.close();
if (con != null)
con.close();
}
public static void close(Connection con, Statement stmt)
throws SQLException {
close(con,stmt,null);
}
public static void close(Connection con)
throws SQLException {
close(con,null,null);
}
}
|
package com.tencent.mm.plugin.voip.ui;
class VideoActivity$7 implements Runnable {
final /* synthetic */ int hdX;
final /* synthetic */ VideoActivity oQn;
VideoActivity$7(VideoActivity videoActivity, int i) {
this.oQn = videoActivity;
this.hdX = i;
}
public final void run() {
VideoActivity.a(this.oQn, this.hdX);
}
}
|
package example.nz.org.take.compiler.example1.spec;
import nz.org.take.rt.*;
/**
* Interface generated by the take compiler.
* @version Fri Feb 01 10:12:41 NZDT 2008
*/
@SuppressWarnings("unchecked")
public interface DiscountPolicy {
/**
* Method generated for query /discount[in,out]
* @param customer input parameter generated from slot 0
* @return an iterator for instances of CustomerDiscount
*/
public ResultSet<CustomerDiscount> getDiscount(
final example.nz.org.take.compiler.example1.Customer customer);
/**
* Method that can be used to query annotations at runtime.
* @param id the id of the rule (or other knowledge element)
* @return a map of annotations (string-string mappings)
* code generated using velocity template LocalAnnotationMethod.vm
*/
public java.util.Map<String, String> getAnnotations(String id);
/**
* Method that can be used to query global annotations at runtime.
* Global annotations are attached to the knowledge base, not to
* a particular element (rule,..).
* @return a map of annotations (string-string mappings)
* code generated using velocity template GlobalAnnotationMethod.vm
*/
public java.util.Map<String, String> getAnnotations();
}
|
package VSMTests;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import org.apache.commons.compress.compressors.CompressorException;
import VSMUtilityClasses.VSMUtil;
public class TestCorpusExtraction {
public static void main(String... args) {
/*
* Checking whether the program is running on bravas or not
*/
InetAddress ip;
String hostname;
try {
ip = InetAddress.getLocalHost();
hostname = ip.getHostName();
System.out.println("Your current IP address : " + ip);
System.out.println("Your current Hostname : " + hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
}
/*
* The directory root
*/
String directoryRoot = "/group/corpora/public/bllip/bllip_nanc_mem/data";
/*
* Get all the directories into the data directory
*/
File[] files = VSMUtil.getFiles(directoryRoot);
Collections.sort(Arrays.asList(files), new Comparator<File>() {
public int compare(File file1, File file2) {
String a = file1.getName().replaceFirst("^0+(?!$)", "");
String b = file2.getName().replaceFirst("^0+(?!$)", "");
return Integer.parseInt(a) - Integer.parseInt(b);
}
});
for (File file : files) {
System.out.println(file.getName());
}
ArrayList<File> filePaths = VSMUtil.getFilePaths(files);
System.out.println("***Total Files in BLLIP Corpus***"
+ filePaths.size());
/*
* Testing
*/
int count = 0;
for (File file : filePaths) {
// System.out.println(path);
count += 1;
// System.out.println(count);
System.out.println(file.getName());
VSMUtil.extractAndAddTrees(file.getAbsolutePath());
}
}
}
|
package com.tencent.mm.ui.chatting;
import android.content.Context;
import android.os.Build.VERSION;
import android.view.View;
import android.view.View.OnHoverListener;
import com.tencent.mm.g.a.su;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.b.a;
import com.tencent.mm.sdk.platformtools.x;
public final class q {
public static b tJt = new b();
static /* synthetic */ void q(Context context, String str, int i) {
su suVar = new su();
suVar.cdE.bOh = 5;
suVar.cdE.talker = str;
suVar.cdE.context = context;
suVar.cdE.cdz = i;
a.sFg.m(suVar);
h.mEJ.h(11033, new Object[]{Integer.valueOf(4), Integer.valueOf(1), Integer.valueOf(0)});
}
public static void dq(View view) {
b bVar = tJt;
if (view == null || bVar == null) {
x.w("MicroMsg.OnHoverCompatibleHelper", "view or callback is null.");
} else if (VERSION.SDK_INT >= 14) {
ai cui = ai.cui();
if (VERSION.SDK_INT >= 14 && cui.tMB == null) {
cui.tMB = new ai.a(bVar);
}
Object obj = cui.tMB;
if (obj != null && VERSION.SDK_INT >= 14 && (obj instanceof OnHoverListener)) {
view.setOnHoverListener((OnHoverListener) obj);
}
}
}
public static void dismiss() {
try {
if (tJt != null) {
b.a(tJt);
}
} catch (Exception e) {
x.e("MicroMsg.ChattingItemAvatarOnHoverHelper", "exception in dismiss, %s", new Object[]{e.getMessage()});
}
}
}
|
package com.example.demo.repository;
import com.example.demo.model.Role;
import com.example.demo.model.Service;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional(readOnly = true)
public interface ServiceRepository extends JpaRepository<Service, Long> {
@EntityGraph(value = "Service.withAccessKeys", type = EntityGraph.EntityGraphType.LOAD)
List<Service> findAll();
}
|
package com.android.medicaladvisor.initialdiagnosis;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.medicaladvisor.Injection;
import com.android.medicaladvisor.R;
import com.android.medicaladvisor.backend.DiagnosisRepository;
import com.android.medicaladvisor.medicalcenters.ShowAvailableMedicalCenters;
import com.android.medicaladvisor.models.Diagnosis;
import androidx.appcompat.app.AppCompatActivity;
public class InitialDiagnosis extends AppCompatActivity implements DiagnosisRepository.DiagnosisCallback {
private InitialDiagnosisPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_initial_diagnosis);
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
presenter = new InitialDiagnosisPresenter(Injection.provideDiagnosisRepository(), Injection.provideDiagnosisSharedPref(sharedPreferences));
presenter.detectDiagnosis(this);
setComplaintSummaryContents();
}
private void setComplaintSummaryContents() {
TextView categoryTextView = findViewById(R.id.category_textview);
TextView initialSymptomTextView = findViewById(R.id.initial_symptoms_textview);
TextView symptomDetailTextView = findViewById(R.id.symptom_detail_textview);
categoryTextView.setText(String.format(getString(R.string.speciality_value), presenter.getSelectedCategoryName()));
initialSymptomTextView.setText(String.format(getString(R.string.initial_symptom_value), presenter.getSelectedInitialSymptomName()));
symptomDetailTextView.setText(String.format(getString(R.string.symptom_detail_value), presenter.getSelectedSymptomDetailName()));
}
public void onBackClicked(View view) {
onBackPressed();
}
public void onNextClicked(View view) {
startActivity(new Intent(this, ShowAvailableMedicalCenters.class));
}
@Override
public void onDiagnosisDetected(Diagnosis diagnosis) {
TextView diagnosisTextView = findViewById(R.id.diagnosis_textview);
diagnosisTextView.setText(diagnosis.getName());
presenter.saveDiagnosis(diagnosis);
}
@Override
public void onDiagnosisDetectedFailed(String errmsg) {
Toast.makeText(this, errmsg, Toast.LENGTH_LONG).show();
}
}
|
package workstarter.web.rest;
import com.codahale.metrics.annotation.Timed;
import workstarter.domain.Jobadvertisment;
import workstarter.repository.JobadvertismentRepository;
import workstarter.repository.search.JobadvertismentSearchRepository;
import workstarter.web.rest.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing Jobadvertisment.
*/
@RestController
@RequestMapping("/api")
public class JobadvertismentResource {
private final Logger log = LoggerFactory.getLogger(JobadvertismentResource.class);
private static final String ENTITY_NAME = "jobadvertisment";
private final JobadvertismentRepository jobadvertismentRepository;
private final JobadvertismentSearchRepository jobadvertismentSearchRepository;
public JobadvertismentResource(JobadvertismentRepository jobadvertismentRepository, JobadvertismentSearchRepository jobadvertismentSearchRepository) {
this.jobadvertismentRepository = jobadvertismentRepository;
this.jobadvertismentSearchRepository = jobadvertismentSearchRepository;
}
/**
* POST /jobadvertisments : Create a new jobadvertisment.
*
* @param jobadvertisment the jobadvertisment to create
* @return the ResponseEntity with status 201 (Created) and with body the new jobadvertisment, or with status 400 (Bad Request) if the jobadvertisment has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/jobadvertisments")
@Timed
public ResponseEntity<Jobadvertisment> createJobadvertisment(@Valid @RequestBody Jobadvertisment jobadvertisment) throws URISyntaxException {
log.debug("REST request to save Jobadvertisment : {}", jobadvertisment);
if (jobadvertisment.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new jobadvertisment cannot already have an ID")).body(null);
}
Jobadvertisment result = jobadvertismentRepository.save(jobadvertisment);
jobadvertismentSearchRepository.save(result);
return ResponseEntity.created(new URI("/api/jobadvertisments/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /jobadvertisments : Updates an existing jobadvertisment.
*
* @param jobadvertisment the jobadvertisment to update
* @return the ResponseEntity with status 200 (OK) and with body the updated jobadvertisment,
* or with status 400 (Bad Request) if the jobadvertisment is not valid,
* or with status 500 (Internal Server Error) if the jobadvertisment couldnt be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/jobadvertisments")
@Timed
public ResponseEntity<Jobadvertisment> updateJobadvertisment(@Valid @RequestBody Jobadvertisment jobadvertisment) throws URISyntaxException {
log.debug("REST request to update Jobadvertisment : {}", jobadvertisment);
if (jobadvertisment.getId() == null) {
return createJobadvertisment(jobadvertisment);
}
Jobadvertisment result = jobadvertismentRepository.save(jobadvertisment);
jobadvertismentSearchRepository.save(result);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, jobadvertisment.getId().toString()))
.body(result);
}
/**
* GET /jobadvertisments : get all the jobadvertisments.
*
* @return the ResponseEntity with status 200 (OK) and the list of jobadvertisments in body
*/
@GetMapping("/jobadvertisments")
@Timed
public List<Jobadvertisment> getAllJobadvertisments() {
log.debug("REST request to get all Jobadvertisments");
List<Jobadvertisment> jobadvertisments = jobadvertismentRepository.findAll();
return jobadvertisments;
}
/**
* GET /jobadvertisments/:id : get the "id" jobadvertisment.
*
* @param id the id of the jobadvertisment to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the jobadvertisment, or with status 404 (Not Found)
*/
@GetMapping("/jobadvertisments/{id}")
@Timed
public ResponseEntity<Jobadvertisment> getJobadvertisment(@PathVariable Long id) {
log.debug("REST request to get Jobadvertisment : {}", id);
Jobadvertisment jobadvertisment = jobadvertismentRepository.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(jobadvertisment));
}
/**
* DELETE /jobadvertisments/:id : delete the "id" jobadvertisment.
*
* @param id the id of the jobadvertisment to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/jobadvertisments/{id}")
@Timed
public ResponseEntity<Void> deleteJobadvertisment(@PathVariable Long id) {
log.debug("REST request to delete Jobadvertisment : {}", id);
jobadvertismentRepository.delete(id);
jobadvertismentSearchRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
/**
* SEARCH /_search/jobadvertisments?query=:query : search for the jobadvertisment corresponding
* to the query.
*
* @param query the query of the jobadvertisment search
* @return the result of the search
*/
@GetMapping("/_search/jobadvertisments")
@Timed
public List<Jobadvertisment> searchJobadvertisments(@RequestParam String query) {
log.debug("REST request to search Jobadvertisments for query {}", query);
return StreamSupport
.stream(jobadvertismentSearchRepository.search(queryStringQuery(query)).spliterator(), false)
.collect(Collectors.toList());
}
}
|
package Lohnberechnung;
public class lohnberechnung {
private String vorname;
private String nachname;
private int mitarbeiternummer;
private double gehalt;
private int alter;
private static int mitarbeiter_counter = 0;
public lohnberechnung (String vorname, String nachname, double gehalt) {
this.vorname=vorname;
this.nachname=nachname;
this.gehalt=gehalt;
this.mitarbeiternummer=mitarbeiter_counter++;
this.alter = 0;
}
public String getNachname() {
return nachname;
}
public void setNachname(String nachname) {
this.nachname = nachname;
}
public double getGehalt() {
return gehalt;
}
public void setGehalt(double gehalt) {
this.gehalt = gehalt;
}
public String getVorname() {
return vorname;
}
public int getMitarbeiternummer() {
return mitarbeiternummer;
}
public int getAlter() {
return alter;
}
public double monatsAbrechnung()
{
double newGehalt=this.gehalt*12*0.8;
double steuer = 0;
// if (newGehalt < 10000)
// steuer = newGehalt * (10/100);
// if (newGehalt < 20000)
// newGehalt = newGehalt + ((newGehalt-10000) * (20/100));
// if (newGehalt < 30000)
// newGehalt = newGehalt + ((newGehalt-20000) * (32/100));
// if (newGehalt < 50000)
// newGehalt = newGehalt + ((newGehalt-30000) * (45/100));
// if (newGehalt > 50000)
// newGehalt = newGehalt + ((newGehalt-50000) * (60/100));
// return newGehalt/12;
if (newGehalt > 50000) {
steuer = steuer + (newGehalt - 50000)*0.6;
newGehalt=50000; }
if (newGehalt > 30000) {
steuer = steuer + (newGehalt - 30000)*0.45;
newGehalt=30000; }
if (newGehalt > 20000) {
steuer = steuer + (newGehalt - 20000)*0.32;
newGehalt=20000; }
if (newGehalt > 10000) {
steuer = steuer + (newGehalt - 10000)*0.20;
newGehalt=10000; }
if (newGehalt <= 10000) {
steuer = steuer + newGehalt *0.1;
}
return (((this.gehalt*12*0.8)-steuer)/12);
}
public double jahresAbrechnung()
{
return jahresAbrechnung(12);
}
public double jahresAbrechnung(int monate)
{
return monatsAbrechnung() * monate;
}
}
|
package dk.aarhustech.edu.rainbow.horario;
import com.google.gson.Gson;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings({"MismatchedReadAndWriteOfArray", "unused", "MismatchedQueryAndUpdateOfCollection"})
class RandomForestClassifier {
private Data data;
private int nClasses;
private int nEstimators;
RandomForestClassifier(InputStream stream) throws UnsupportedEncodingException {
Reader reader = new InputStreamReader(stream, "UTF-8");
Gson gson = new Gson();
this.data = gson.fromJson(reader, Data.class);
this.nEstimators = this.data.forest.size();
this.nClasses = this.data.forest.get(0).classes[0].length;
}
private static int findMax(double[] nums) {
int index = 0;
for (int i = 0; i < nums.length; i++) {
index = nums[i] > nums[index] ? i : index;
}
return index;
}
double getMaxScore() {
return (double) nEstimators;
}
Map<String, Double> predict_proba(Map<String, Double> features) {
double[] featureArray = new double[this.data.features.length];
for (int i = 0; i < this.data.features.length; i++) {
featureArray[i] = features.containsKey(this.data.features[i]) ? features.get(this.data.features[i]) : 0.0;
}
return predict_proba(featureArray);
}
Map<String, Double> predict_proba(double[] features) {
double[] classes = new double[this.nClasses];
for (int i = 0; i < this.nEstimators; i++) {
classes[this.data.forest.get(i).predict(features, 0)]++;
}
Map<String, Double> out = new HashMap<>();
for (int i = 0; i < this.data.classes.length; i++) {
out.put(this.data.classes[i], classes[i]);
}
return out;
}
public String predict(double[] features) {
double[] classes = new double[this.nClasses];
for (int i = 0; i < this.nEstimators; i++) {
classes[this.data.forest.get(i).predict(features, 0)]++;
}
return this.data.classes[RandomForestClassifier.findMax(classes)];
}
private class Data {
private String[] features;
private String[] classes;
private List<Tree> forest;
private class Tree {
private int[] childrenLeft;
private int[] childrenRight;
private double[] thresholds;
private int[] indices;
private double[][] classes;
private int predict(double[] features, int node) {
if (this.thresholds[node] != -2) {
if (features[this.indices[node]] <= this.thresholds[node]) {
return this.predict(features, this.childrenLeft[node]);
} else {
return this.predict(features, this.childrenRight[node]);
}
}
return RandomForestClassifier.findMax(this.classes[node]);
}
private int predict(double[] features) {
return this.predict(features, 0);
}
}
}
}
|
package com.study.server;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
/**
* 目标:封装请求信息中参数转成map
* @author Administrator
*
*/
public class Server04 {
private ServerSocket serverSocket;
public static void main(String[] args) {
Server04 server=new Server04();
server.start();
}
//启动服务
public void start(){
try {
serverSocket=new ServerSocket(8888);
receive();
} catch (IOException e) {
System.out.println("服务器启动失败");
}
}
//接受连接处理
public void receive(){
try {
Socket client=serverSocket.accept();
System.out.println("一个客户端建立了连接...");
//获取请求协议
Request2 request=new Request2(client);
Response response=new Response(client);
//关注内容
response.print("<html>");
response.print("<head>");
response.print("<title>");
response.print("服务器响应成功");
response.print("</title>");
response.print("</head>");
response.print("<body>");
response.print("终于回来了。。。"+request.getParameter("uname"));
response.print("</body>");
response.print("</html>");
//关注了状态
response.pushToBrowser(200);
} catch (IOException e) {
System.out.println("客户端错误");
}
}
//停止服务
public void stop(){
}
}
|
package com.facebook.react.flat;
import android.text.Layout;
import android.text.Spanned;
final class TextNodeRegion extends NodeRegion {
private Layout mLayout;
TextNodeRegion(float paramFloat1, float paramFloat2, float paramFloat3, float paramFloat4, int paramInt, boolean paramBoolean, Layout paramLayout) {
super(paramFloat1, paramFloat2, paramFloat3, paramFloat4, paramInt, paramBoolean);
this.mLayout = paramLayout;
}
final Layout getLayout() {
return this.mLayout;
}
final int getReactTag(float paramFloat1, float paramFloat2) {
Layout layout = this.mLayout;
if (layout != null) {
CharSequence charSequence = layout.getText();
if (charSequence instanceof Spanned) {
int i = Math.round(paramFloat2 - getTop());
if (i >= this.mLayout.getLineTop(0)) {
Layout layout1 = this.mLayout;
if (i < layout1.getLineBottom(layout1.getLineCount() - 1)) {
float f = Math.round(paramFloat1 - getLeft());
i = this.mLayout.getLineForVertical(i);
if (this.mLayout.getLineLeft(i) <= f && f <= this.mLayout.getLineRight(i)) {
i = this.mLayout.getOffsetForHorizontal(i, f);
RCTRawText[] arrayOfRCTRawText = (RCTRawText[])((Spanned)charSequence).getSpans(i, i, RCTRawText.class);
if (arrayOfRCTRawText.length != 0)
return arrayOfRCTRawText[0].getReactTag();
}
}
}
}
}
return super.getReactTag(paramFloat1, paramFloat2);
}
final boolean matchesTag(int paramInt) {
if (super.matchesTag(paramInt))
return true;
Layout layout = this.mLayout;
if (layout != null) {
CharSequence charSequence = layout.getText();
if (charSequence instanceof Spanned) {
RCTRawText[] arrayOfRCTRawText = (RCTRawText[])((Spanned)charSequence).getSpans(0, charSequence.length(), RCTRawText.class);
int j = arrayOfRCTRawText.length;
for (int i = 0; i < j; i++) {
if (arrayOfRCTRawText[i].getReactTag() == paramInt)
return true;
}
}
}
return false;
}
public final void setLayout(Layout paramLayout) {
this.mLayout = paramLayout;
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\flat\TextNodeRegion.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
/***********************************************************************
* Module: Patient.java
* Author: WIN 10
* Purpose: Defines the Class Patient
***********************************************************************/
package com.hesoyam.pharmacy.user.model;
import com.hesoyam.pharmacy.medicine.model.Medicine;
import javax.persistence.*;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Entity
public class Patient extends User {
@Column
@Min(0)
private int penaltyPoints;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name="patient_allergies", joinColumns = @JoinColumn(name = "patient_id", referencedColumnName="id"), inverseJoinColumns = @JoinColumn(name="medicine_id", referencedColumnName="id"))
private List<Medicine> allergies;
@OneToOne(optional = true, fetch = FetchType.LAZY, mappedBy = "patient")
private LoyaltyAccount loyaltyAccount;
public Patient(){}
public List<Medicine> getAllergies() {
if (allergies == null)
allergies = new ArrayList<>();
return allergies;
}
public Iterator<Medicine> getIteratorAllergies() {
if (allergies == null)
allergies = new ArrayList<>();
return allergies.iterator();
}
public void setAllergies(List<Medicine> newAllergies) {
removeAllAllergies();
for (Iterator<Medicine> iter = newAllergies.iterator(); iter.hasNext();)
addAllergies(iter.next());
}
public void addAllergies(Medicine newMedicine) {
if (newMedicine == null)
return;
if (this.allergies == null)
this.allergies = new ArrayList<>();
if (!this.allergies.contains(newMedicine))
this.allergies.add(newMedicine);
}
public void removeAllergies(Medicine oldMedicine) {
if (oldMedicine == null)
return;
if (this.allergies != null && this.allergies.contains(oldMedicine))
this.allergies.remove(oldMedicine);
}
public void removeAllAllergies() {
if (allergies != null)
allergies.clear();
}
public int getPenaltyPoints() {
return penaltyPoints;
}
public void setPenaltyPoints(int penaltyPoints) {
this.penaltyPoints = penaltyPoints;
}
}
|
package com.example.ventas;
import me.tell.ventas.EliminarVentaRequest;
import me.tell.ventas.EliminarVentaResponse;
import me.tell.ventas.ModificarVentaRequest;
import me.tell.ventas.ModificarVentaResponse;
import me.tell.ventas.MostrarVentaResponse;
import me.tell.ventas.RealizarVentaRequest;
import me.tell.ventas.RealizarVentaResponse;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
@Endpoint
public class VentasEndPoint {
@Autowired
private Iventas iventas;
@PayloadRoot(namespace = "http://tell.me/ventas", localPart = "RealizarVentaRequest")
@ResponsePayload
public RealizarVentaResponse guardaVenta(@RequestPayload RealizarVentaRequest peticion) {
RealizarVentaResponse respuesta = new RealizarVentaResponse();
respuesta.setRespuesta("Venta Realizada " + peticion.getNombre());
Productos productos = new Productos();
productos.setNombre(peticion.getNombre());
productos.setDescripcion(peticion.getDescripcion());
productos.setPrecio(peticion.getPrecio());
productos.setStock(peticion.getStock());
iventas.save(productos);
return respuesta;
}
@PayloadRoot(namespace = "http://tell.me/ventas", localPart = "ModificarVentaRequest")
@PayloadRoot(namespace = "http://tell.me/ventas",localPart = "EliminarVentaRequest")
@ResponsePayload
public EliminarVentaResponse borrarVenta(
@RequestPayload EliminarVentaRequest peticion) {
EliminarVentaResponse respuesta = new EliminarVentaResponse();
respuesta.setRespuesta("Eliminado correctamente el id " + peticion.getId());
//validad que no existe
iventas.deleteById(peticion.getId());
return respuesta;
}
}
|
package com.gtfs.dto;
import java.io.Serializable;
import java.util.Date;
public class LicPisDto implements Serializable{
private Long applicationMstId;
private Long requirementId;
private String applicationNo;
private Date businessDate;
private String draftChqNo;
private Double draftChqInsAmt;
private Double draftChqTieAmt;
private Double cashAmt;
private Double totalAmt;
public Long getApplicationMstId() {
return applicationMstId;
}
public void setApplicationMstId(Long applicationMstId) {
this.applicationMstId = applicationMstId;
}
public String getApplicationNo() {
return applicationNo;
}
public void setApplicationNo(String applicationNo) {
this.applicationNo = applicationNo;
}
public Date getBusinessDate() {
return businessDate;
}
public void setBusinessDate(Date businessDate) {
this.businessDate = businessDate;
}
public String getDraftChqNo() {
return draftChqNo;
}
public void setDraftChqNo(String draftChqNo) {
this.draftChqNo = draftChqNo;
}
public Double getDraftChqInsAmt() {
return draftChqInsAmt;
}
public void setDraftChqInsAmt(Double draftChqInsAmt) {
this.draftChqInsAmt = draftChqInsAmt;
}
public Double getDraftChqTieAmt() {
return draftChqTieAmt;
}
public void setDraftChqTieAmt(Double draftChqTieAmt) {
this.draftChqTieAmt = draftChqTieAmt;
}
public Double getCashAmt() {
return cashAmt;
}
public void setCashAmt(Double cashAmt) {
this.cashAmt = cashAmt;
}
public Double getTotalAmt() {
return totalAmt;
}
public void setTotalAmt(Double totalAmt) {
this.totalAmt = totalAmt;
}
public Long getRequirementId() {
return requirementId;
}
public void setRequirementId(Long requirementId) {
this.requirementId = requirementId;
}
}
|
package razerdp.basepopup;
import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Message;
import android.util.LayoutDirection;
import android.util.Log;
import android.view.DisplayCutout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import java.util.Map;
import java.util.WeakHashMap;
import razerdp.blur.PopupBlurOption;
import razerdp.library.R;
import razerdp.util.KeyboardUtils;
import razerdp.util.PopupUiUtils;
import razerdp.util.PopupUtils;
import razerdp.util.log.PopupLog;
/**
* Created by 大灯泡 on 2017/12/12.
* <p>
* PopupHelper,这货与Popup强引用哦~
*/
@SuppressWarnings("all")
final class BasePopupHelper implements KeyboardUtils.OnKeyboardChangeListener, BasePopupFlag, ClearMemoryObject {
BasePopupWindow mPopupWindow;
WeakHashMap<Object, BasePopupEvent.EventObserver> eventObserverMap;
enum ShowMode {
RELATIVE_TO_ANCHOR,
SCREEN,
POSITION
}
static final int DEFAULT_OVERLAY_STATUS_BAR_MODE = OVERLAY_MASK | OVERLAY_CONTENT;
static final int DEFAULT_OVERLAY_NAVIGATION_BAR_MODE = OVERLAY_MASK;
private static final int CONTENT_VIEW_ID = R.id.base_popup_content_root;
Animation DEFAULT_MASK_SHOW_ANIMATION = new AlphaAnimation(0f, 1f) {
{
setFillAfter(true);
setInterpolator(new DecelerateInterpolator());
setDuration(Resources.getSystem().getInteger(android.R.integer.config_shortAnimTime));
}
};
Animation DEFAULT_MASK_DISMISS_ANIMATION = new AlphaAnimation(1f, 0f) {
{
setFillAfter(true);
setInterpolator(new DecelerateInterpolator());
setDuration(Resources.getSystem().getInteger(android.R.integer.config_shortAnimTime));
}
};
ShowMode mShowMode = ShowMode.SCREEN;
int contentRootId = CONTENT_VIEW_ID;
int flag = IDLE;
static int showCount;
//animate
Animation mShowAnimation;
Animator mShowAnimator;
Animation mDismissAnimation;
Animator mDismissAnimator;
Animation mMaskViewShowAnimation;
Animation mMaskViewDismissAnimation;
long showDuration;
long dismissDuration;
int animationStyleRes;
//callback
BasePopupWindow.OnDismissListener mOnDismissListener;
BasePopupWindow.OnBeforeShowCallback mOnBeforeShowCallback;
BasePopupWindow.OnPopupWindowShowListener mOnPopupWindowShowListener;
//option
BasePopupWindow.GravityMode horizontalGravityMode = BasePopupWindow.GravityMode.RELATIVE_TO_ANCHOR;
BasePopupWindow.GravityMode verticalGravityMode = BasePopupWindow.GravityMode.RELATIVE_TO_ANCHOR;
int popupGravity = Gravity.NO_GRAVITY;
int offsetX;
int offsetY;
int maskOffsetX;
int maskOffsetY;
int preMeasureWidth;
int preMeasureHeight;
int popupViewWidth = 0;
int popupViewHeight = 0;
int layoutDirection = LayoutDirection.LTR;
//锚点view的location
Rect mAnchorViewBound;
//模糊option(为空的话则不模糊)
PopupBlurOption mBlurOption;
//背景颜色
Drawable mBackgroundDrawable = new ColorDrawable(BasePopupWindow.DEFAULT_BACKGROUND_COLOR);
//背景对齐方向
int alignBackgroundGravity = Gravity.TOP;
//背景View
View mBackgroundView;
EditText mAutoShowInputEdittext;
KeyboardUtils.OnKeyboardChangeListener mKeyboardStateChangeListener;
KeyboardUtils.OnKeyboardChangeListener mUserKeyboardStateChangeListener;
BasePopupWindow.KeyEventListener mKeyEventListener;
int mSoftInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
ViewGroup.MarginLayoutParams layoutParams;
int maxWidth, maxHeight, minWidth, minHeight;
int keybaordAlignViewId;
View keybaordAlignView;
InnerShowInfo mShowInfo;
ViewTreeObserver.OnGlobalLayoutListener mGlobalLayoutListener;
LinkedViewLayoutChangeListenerWrapper mLinkedViewLayoutChangeListenerWrapper;
View mLinkedTarget;
Rect navigationBarBounds;
Rect cutoutSafeRect;
int lastOverLayStatusBarMode, overlayStatusBarMode = DEFAULT_OVERLAY_STATUS_BAR_MODE;
int lastOverlayNavigationBarMode, overlayNavigationBarMode = DEFAULT_OVERLAY_NAVIGATION_BAR_MODE;
BasePopupHelper(BasePopupWindow popupWindow) {
mAnchorViewBound = new Rect();
navigationBarBounds = new Rect();
cutoutSafeRect = new Rect();
this.mPopupWindow = popupWindow;
this.eventObserverMap = new WeakHashMap<>();
this.mMaskViewShowAnimation = DEFAULT_MASK_SHOW_ANIMATION;
this.mMaskViewDismissAnimation = DEFAULT_MASK_DISMISS_ANIMATION;
}
void observerEvent(Object who, BasePopupEvent.EventObserver observer) {
eventObserverMap.put(who, observer);
}
void removeEventObserver(Object who) {
eventObserverMap.remove(who);
}
void sendEvent(Message msg) {
if (msg == null) return;
if (msg.what < 0) return;
for (Map.Entry<Object, BasePopupEvent.EventObserver> entry : eventObserverMap.entrySet()) {
if (entry.getValue() != null) {
entry.getValue().onEvent(msg);
}
}
}
View inflate(Context context, int layoutId) {
try {
FrameLayout tempLayout = new FrameLayout(context);
View result = LayoutInflater.from(context).inflate(layoutId, tempLayout, false);
ViewGroup.LayoutParams childParams = result.getLayoutParams();
if (childParams != null) {
checkAndSetGravity(childParams);
if (childParams instanceof ViewGroup.MarginLayoutParams) {
layoutParams = new ViewGroup.MarginLayoutParams((ViewGroup.MarginLayoutParams) childParams);
} else {
layoutParams = new ViewGroup.MarginLayoutParams(childParams);
}
if (popupViewWidth != 0 && layoutParams.width != popupViewWidth) {
layoutParams.width = popupViewWidth;
}
if (popupViewHeight != 0 && layoutParams.height != popupViewHeight) {
layoutParams.height = popupViewHeight;
}
tempLayout = null;
return result;
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
void preMeasurePopupView(View mContentView, int w, int h) {
if (mContentView != null) {
int measureWidth = View.MeasureSpec.makeMeasureSpec(Math.max(w, 0),
w == ViewGroup.LayoutParams.WRAP_CONTENT ? View.MeasureSpec.UNSPECIFIED : View.MeasureSpec.EXACTLY);
int measureHeight = View.MeasureSpec.makeMeasureSpec(Math.max(w, h),
h == ViewGroup.LayoutParams.WRAP_CONTENT ? View.MeasureSpec.UNSPECIFIED : View.MeasureSpec.EXACTLY);
mContentView.measure(measureWidth, measureHeight);
preMeasureWidth = mContentView.getMeasuredWidth();
preMeasureHeight = mContentView.getMeasuredHeight();
mContentView.setFocusableInTouchMode(true);
}
}
void checkAndSetGravity(ViewGroup.LayoutParams p) {
//如果设置过gravity,则采取设置的gravity,顶替掉xml设置的(针对lazypopup)
//https://github.com/razerdp/BasePopup/issues/310
if (p == null || this.popupGravity != Gravity.NO_GRAVITY) return;
if (p instanceof LinearLayout.LayoutParams) {
this.popupGravity = ((LinearLayout.LayoutParams) p).gravity;
} else if (p instanceof FrameLayout.LayoutParams) {
this.popupGravity = ((FrameLayout.LayoutParams) p).gravity;
}
}
//region Animation
void startShowAnimate(int width, int height) {
if (getShowAnimation(width, height) == null) {
getShowAnimator(width, height);
}
//通知蒙层动画,此时duration已经计算完毕
Message msg = Message.obtain();
msg.what = BasePopupEvent.EVENT_SHOW;
sendEvent(msg);
if (mShowAnimation != null) {
mShowAnimation.cancel();
mPopupWindow.mDisplayAnimateView.startAnimation(mShowAnimation);
} else if (mShowAnimator != null) {
mShowAnimator.setTarget(mPopupWindow.getDisplayAnimateView());
mShowAnimator.cancel();
mShowAnimator.start();
}
}
void startDismissAnimate(int width, int height) {
if (getDismissAnimation(width, height) == null) {
getDismissAnimator(width, height);
}
if (mDismissAnimation != null) {
mDismissAnimation.cancel();
mPopupWindow.mDisplayAnimateView.startAnimation(mDismissAnimation);
if (mOnDismissListener != null) {
mOnDismissListener.onDismissAnimationStart();
}
setFlag(CUSTOM_ON_ANIMATE_DISMISS, true);
} else if (mDismissAnimator != null) {
mDismissAnimator.setTarget(mPopupWindow.getDisplayAnimateView());
mDismissAnimator.cancel();
mDismissAnimator.start();
if (mOnDismissListener != null) {
mOnDismissListener.onDismissAnimationStart();
}
setFlag(CUSTOM_ON_ANIMATE_DISMISS, true);
}
}
Animation getShowAnimation(int width, int height) {
if (mShowAnimation == null) {
mShowAnimation = mPopupWindow.onCreateShowAnimation(width, height);
if (mShowAnimation != null) {
showDuration = PopupUtils.getAnimationDuration(mShowAnimation, 0);
setToBlur(mBlurOption);
}
}
return mShowAnimation;
}
Animator getShowAnimator(int width, int height) {
if (mShowAnimator == null) {
mShowAnimator = mPopupWindow.onCreateShowAnimator(width, height);
if (mShowAnimator != null) {
showDuration = PopupUtils.getAnimatorDuration(mShowAnimator, 0);
setToBlur(mBlurOption);
}
}
return mShowAnimator;
}
Animation getDismissAnimation(int width, int height) {
if (mDismissAnimation == null) {
mDismissAnimation = mPopupWindow.onCreateDismissAnimation(width, height);
if (mDismissAnimation != null) {
dismissDuration = PopupUtils.getAnimationDuration(mDismissAnimation, 0);
setToBlur(mBlurOption);
}
}
return mDismissAnimation;
}
Animator getDismissAnimator(int width, int height) {
if (mDismissAnimator == null) {
mDismissAnimator = mPopupWindow.onCreateDismissAnimator(width, height);
if (mDismissAnimator != null) {
dismissDuration = PopupUtils.getAnimatorDuration(mDismissAnimator, 0);
setToBlur(mBlurOption);
}
}
return mDismissAnimator;
}
void setToBlur(PopupBlurOption option) {
this.mBlurOption = option;
if (option != null) {
if (option.getBlurInDuration() <= 0) {
if (showDuration > 0) {
option.setBlurInDuration(showDuration);
}
}
if (option.getBlurOutDuration() <= 0) {
if (dismissDuration > 0) {
option.setBlurOutDuration(dismissDuration);
}
}
}
}
void setShowAnimation(Animation showAnimation) {
if (mShowAnimation == showAnimation) return;
if (mShowAnimation != null) {
mShowAnimation.cancel();
}
mShowAnimation = showAnimation;
showDuration = PopupUtils.getAnimationDuration(mShowAnimation, 0);
setToBlur(mBlurOption);
}
/**
* animation优先级更高
*/
void setShowAnimator(Animator showAnimator) {
if (mShowAnimation != null || mShowAnimator == showAnimator) return;
if (mShowAnimator != null) {
mShowAnimator.cancel();
}
mShowAnimator = showAnimator;
showDuration = PopupUtils.getAnimatorDuration(mShowAnimator, 0);
setToBlur(mBlurOption);
}
void setDismissAnimation(Animation dismissAnimation) {
if (mDismissAnimation == dismissAnimation) return;
if (mDismissAnimation != null) {
mDismissAnimation.cancel();
}
mDismissAnimation = dismissAnimation;
dismissDuration = PopupUtils.getAnimationDuration(mDismissAnimation, 0);
setToBlur(mBlurOption);
}
void setDismissAnimator(Animator dismissAnimator) {
if (mDismissAnimation != null || mDismissAnimator == dismissAnimator) return;
if (mDismissAnimator != null) {
mDismissAnimator.cancel();
}
mDismissAnimator = dismissAnimator;
dismissDuration = PopupUtils.getAnimatorDuration(mDismissAnimator, 0);
setToBlur(mBlurOption);
}
//endregion
BasePopupHelper setPopupViewWidth(int popupViewWidth) {
if (popupViewWidth != 0) {
getLayoutParams().width = popupViewWidth;
}
return this;
}
BasePopupHelper setPopupViewHeight(int popupViewHeight) {
if (popupViewHeight != 0) {
getLayoutParams().height = popupViewHeight;
}
return this;
}
int getPreMeasureWidth() {
return preMeasureWidth;
}
int getPreMeasureHeight() {
return preMeasureHeight;
}
boolean isPopupFadeEnable() {
return (flag & FADE_ENABLE) != 0;
}
boolean isWithAnchor() {
return (flag & WITH_ANCHOR) != 0;
}
boolean isFitsizable() {
return (flag & FITSIZE) != 0;
}
BasePopupHelper withAnchor(boolean showAsDropDown) {
setFlag(WITH_ANCHOR, showAsDropDown);
return this;
}
BasePopupHelper setShowLocation(int x, int y) {
mAnchorViewBound.set(x, y, x + 1, y + 1);
return this;
}
int getPopupGravity() {
return Gravity.getAbsoluteGravity(popupGravity, layoutDirection);
}
BasePopupHelper setLayoutDirection(int layoutDirection) {
this.layoutDirection = layoutDirection;
return this;
}
BasePopupHelper setPopupGravity(BasePopupWindow.GravityMode mode, int popupGravity) {
setPopupGravityMode(mode, mode);
this.popupGravity = popupGravity;
return this;
}
BasePopupHelper setPopupGravityMode(BasePopupWindow.GravityMode horizontalGravityMode,
BasePopupWindow.GravityMode verticalGravityMode) {
this.horizontalGravityMode = horizontalGravityMode;
this.verticalGravityMode = verticalGravityMode;
return this;
}
int getOffsetX() {
return offsetX;
}
int getOffsetY() {
return offsetY;
}
boolean isAutoShowInputMethod() {
return (flag & AUTO_INPUT_METHOD) != 0;
}
boolean isAutoLocatePopup() {
return (flag & AUTO_LOCATED) != 0;
}
boolean isOutSideDismiss() {
return (flag & OUT_SIDE_DISMISS) != 0;
}
boolean isOutSideTouchable() {
return (flag & OUT_SIDE_TOUCHABLE) != 0;
}
BasePopupHelper getAnchorLocation(View v) {
if (v == null) return this;
int[] location = new int[2];
v.getLocationOnScreen(location);
mAnchorViewBound.set(location[0],
location[1],
location[0] + v.getWidth(),
location[1] + v.getHeight());
return this;
}
public Rect getAnchorViewBound() {
return mAnchorViewBound;
}
boolean isBackPressEnable() {
return (flag & BACKPRESS_ENABLE) != 0;
}
boolean isOverlayStatusbar() {
return (flag & OVERLAY_STATUS_BAR) != 0;
}
boolean isOverlayNavigationBar() {
return (flag & OVERLAY_NAVIGATION_BAR) != 0;
}
void refreshNavigationBarBounds() {
PopupUiUtils.getNavigationBarBounds(navigationBarBounds, mPopupWindow.getContext());
}
int getNavigationBarSize() {
return Math.min(navigationBarBounds.width(), navigationBarBounds.height());
}
int getNavigationBarGravity() {
return PopupUiUtils.getNavigationBarGravity(navigationBarBounds);
}
public int getCutoutGravity() {
getSafeInsetBounds(cutoutSafeRect);
if (cutoutSafeRect.left > 0) {
return Gravity.LEFT;
}
if (cutoutSafeRect.top > 0) {
return Gravity.TOP;
}
if (cutoutSafeRect.right > 0) {
return Gravity.RIGHT;
}
if (cutoutSafeRect.bottom > 0) {
return Gravity.BOTTOM;
}
return Gravity.NO_GRAVITY;
}
void getSafeInsetBounds(Rect r) {
if (r == null) return;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
r.setEmpty();
return;
}
try {
DisplayCutout cutout = mPopupWindow.getContext()
.getWindow()
.getDecorView()
.getRootWindowInsets()
.getDisplayCutout();
if (cutout == null) {
r.setEmpty();
return;
}
r.set(cutout.getSafeInsetLeft(), cutout.getSafeInsetTop(),
cutout.getSafeInsetRight(), cutout.getSafeInsetBottom());
} catch (Exception e) {
PopupLog.e(e);
}
}
BasePopupHelper overlayStatusbar(boolean overlay) {
if (!overlay && PopupUiUtils.isActivityFullScreen(mPopupWindow.getContext())) {
Log.e(BasePopupWindow.TAG, "setOverlayStatusbar: 全屏Activity下没有StatusBar,此处不能设置为false");
overlay = true;
}
setFlag(OVERLAY_STATUS_BAR, overlay);
if (!overlay) {
lastOverLayStatusBarMode = overlayStatusBarMode;
overlayStatusBarMode = 0;
} else {
overlayStatusBarMode = lastOverLayStatusBarMode;
}
return this;
}
BasePopupHelper setOverlayStatusbarMode(int mode) {
if (!isOverlayStatusbar()) {
lastOverLayStatusBarMode = mode;
} else {
lastOverLayStatusBarMode = overlayStatusBarMode = mode;
}
return this;
}
BasePopupHelper overlayNavigationBar(boolean overlay) {
setFlag(OVERLAY_NAVIGATION_BAR, overlay);
if (!overlay) {
lastOverlayNavigationBarMode = overlayNavigationBarMode;
overlayNavigationBarMode = 0;
} else {
overlayNavigationBarMode = lastOverlayNavigationBarMode;
}
return this;
}
BasePopupHelper setOverlayNavigationBarMode(int mode) {
if (!isOverlayNavigationBar()) {
lastOverlayNavigationBarMode = mode;
} else {
lastOverlayNavigationBarMode = overlayNavigationBarMode = mode;
}
return this;
}
PopupBlurOption getBlurOption() {
return mBlurOption;
}
Drawable getPopupBackground() {
return mBackgroundDrawable;
}
BasePopupHelper setPopupBackground(Drawable background) {
mBackgroundDrawable = background;
return this;
}
boolean isAlignBackground() {
return (flag & ALIGN_BACKGROUND) != 0;
}
BasePopupHelper setAlignBackgound(boolean mAlignBackground) {
setFlag(ALIGN_BACKGROUND, mAlignBackground);
if (!mAlignBackground) {
setAlignBackgroundGravity(Gravity.NO_GRAVITY);
}
return this;
}
int getAlignBackgroundGravity() {
if (isAlignBackground() && alignBackgroundGravity == Gravity.NO_GRAVITY) {
alignBackgroundGravity = Gravity.TOP;
}
return alignBackgroundGravity;
}
BasePopupHelper setAlignBackgroundGravity(int gravity) {
this.alignBackgroundGravity = gravity;
return this;
}
BasePopupHelper setForceAdjustKeyboard(boolean adjust) {
setFlag(KEYBOARD_FORCE_ADJUST, adjust);
return this;
}
boolean isAllowToBlur() {
return mBlurOption != null && mBlurOption.isAllowToBlur();
}
boolean isClipChildren() {
return (flag & CLIP_CHILDREN) != 0;
}
/**
* non null
*/
@NonNull
ViewGroup.MarginLayoutParams getLayoutParams() {
if (layoutParams == null) {
int w = popupViewWidth == 0 ? ViewGroup.LayoutParams.MATCH_PARENT : popupViewWidth;
int h = popupViewHeight == 0 ? ViewGroup.LayoutParams.WRAP_CONTENT : popupViewHeight;
layoutParams = new ViewGroup.MarginLayoutParams(w, h);
}
if (layoutParams.width > 0) {
if (minWidth > 0) {
layoutParams.width = Math.max(layoutParams.width, minWidth);
}
if (maxWidth > 0) {
layoutParams.width = Math.min(layoutParams.width, maxWidth);
}
}
if (layoutParams.height > 0) {
if (minHeight > 0) {
layoutParams.height = Math.max(layoutParams.height, minHeight);
}
if (maxHeight > 0) {
layoutParams.height = Math.min(layoutParams.height, maxHeight);
}
}
return layoutParams;
}
int getShowCount() {
return showCount;
}
BasePopupHelper setContentRootId(View contentRoot) {
if (contentRoot == null) return this;
if (contentRoot.getId() == View.NO_ID) {
contentRoot.setId(CONTENT_VIEW_ID);
}
this.contentRootId = contentRoot.getId();
return this;
}
int getSoftInputMode() {
return mSoftInputMode;
}
View getBackgroundView() {
return mBackgroundView;
}
BasePopupHelper setBackgroundView(View backgroundView) {
mBackgroundView = backgroundView;
return this;
}
int getMaxWidth() {
return maxWidth;
}
int getMaxHeight() {
return maxHeight;
}
ShowMode getShowMode() {
return mShowMode;
}
BasePopupHelper setShowMode(ShowMode showMode) {
mShowMode = showMode;
return this;
}
int getMinWidth() {
return minWidth;
}
int getMinHeight() {
return minHeight;
}
boolean isResizeable() {
return (flag & FITSIZE) != 0;
}
public BasePopupHelper linkTo(View anchorView) {
if (anchorView == null) {
if (mLinkedViewLayoutChangeListenerWrapper != null) {
mLinkedViewLayoutChangeListenerWrapper.detach();
mLinkedViewLayoutChangeListenerWrapper = null;
}
mLinkedTarget = null;
return this;
}
mLinkedTarget = anchorView;
return this;
}
boolean isSyncMaskAnimationDuration() {
return (flag & BasePopupFlag.SYNC_MASK_ANIMATION_DURATION) != 0;
}
boolean isAlignAnchorWidth() {
if (isWithAnchor()) {
//point mode时,由于是一像素,因此忽略
if (mShowInfo != null && mShowInfo.positionMode) {
return false;
}
return (flag & BasePopupFlag.AS_WIDTH_AS_ANCHOR) != 0;
}
return false;
}
boolean isAlignAnchorHeight() {
if (isWithAnchor()) {
//point mode时,由于是一像素,因此忽略
if (mShowInfo != null && mShowInfo.positionMode) {
return false;
}
return (flag & BasePopupFlag.AS_HEIGHT_AS_ANCHOR) != 0;
}
return false;
}
//-----------------------------------------controller-----------------------------------------
void prepare(View v, boolean positionMode) {
if (mShowInfo == null) {
mShowInfo = new InnerShowInfo(v, positionMode);
} else {
mShowInfo.mAnchorView = v;
mShowInfo.positionMode = positionMode;
}
if (positionMode) {
setShowMode(BasePopupHelper.ShowMode.POSITION);
} else {
setShowMode(v == null ? BasePopupHelper.ShowMode.SCREEN : BasePopupHelper.ShowMode.RELATIVE_TO_ANCHOR);
}
getAnchorLocation(v);
applyToPopupWindow();
}
private void applyToPopupWindow() {
if (mPopupWindow == null || mPopupWindow.mPopupWindowProxy == null) return;
mPopupWindow.mPopupWindowProxy.setSoftInputMode(mSoftInputMode);
mPopupWindow.mPopupWindowProxy.setAnimationStyle(animationStyleRes);
mPopupWindow.mPopupWindowProxy.setTouchable((flag & TOUCHABLE) != 0);
}
void onDismiss() {
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP ||
android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) {
showCount--;
showCount = Math.max(0, showCount);
}
if (isAutoShowInputMethod()) {
KeyboardUtils.close(mPopupWindow.getContext());
}
if (mLinkedViewLayoutChangeListenerWrapper != null) {
mLinkedViewLayoutChangeListenerWrapper.detach();
}
}
void setFlag(int flag, boolean added) {
if (!added) {
this.flag &= ~flag;
} else {
this.flag |= flag;
if (flag == AUTO_LOCATED) {
this.flag |= WITH_ANCHOR;
}
}
}
boolean onDispatchKeyEvent(KeyEvent event) {
if (mKeyEventListener != null && mKeyEventListener.onKey(event)) {
return true;
}
return mPopupWindow.onDispatchKeyEvent(event);
}
boolean onInterceptTouchEvent(MotionEvent event) {
return mPopupWindow.onInterceptTouchEvent(event);
}
boolean onTouchEvent(MotionEvent event) {
return mPopupWindow.onTouchEvent(event);
}
boolean onBackPressed() {
return mPopupWindow.onBackPressed();
}
boolean onOutSideTouch() {
return mPopupWindow.onOutSideTouch();
}
void onShow() {
prepareShow();
if ((flag & CUSTOM_ON_UPDATE) != 0) return;
if (mShowAnimation == null || mShowAnimator == null) {
mPopupWindow.mDisplayAnimateView.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mPopupWindow.mDisplayAnimateView.getViewTreeObserver()
.removeOnGlobalLayoutListener(
this);
startShowAnimate(mPopupWindow.mDisplayAnimateView.getWidth(),
mPopupWindow.mDisplayAnimateView.getHeight());
}
});
} else {
startShowAnimate(mPopupWindow.mDisplayAnimateView.getWidth(),
mPopupWindow.mDisplayAnimateView.getHeight());
}
//针对官方的坑(两个popup切换页面后重叠)
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP ||
android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) {
showCount++;
}
}
void onAttachToWindow() {
if (mPopupWindow != null) {
mPopupWindow.onShowing();
}
if (mOnPopupWindowShowListener != null) {
mOnPopupWindowShowListener.onShowing();
}
}
void onPopupLayout(@NonNull Rect popupRect, @NonNull Rect anchorRect) {
if (mPopupWindow != null) {
mPopupWindow.onPopupLayout(popupRect, anchorRect);
}
}
private void prepareShow() {
if (mGlobalLayoutListener == null) {
mGlobalLayoutListener = KeyboardUtils.observerKeyboardChange(mPopupWindow.getContext(),
new KeyboardUtils.OnKeyboardChangeListener() {
@Override
public void onKeyboardChange(Rect keyboardBounds, boolean isVisible) {
BasePopupHelper.this.onKeyboardChange(
keyboardBounds,
isVisible);
if (!mPopupWindow.isShowing()) {
PopupUiUtils.safeRemoveGlobalLayoutListener(
mPopupWindow.getContext()
.getWindow()
.getDecorView(),
mGlobalLayoutListener);
return;
}
}
});
}
PopupUiUtils.safeAddGlobalLayoutListener(mPopupWindow.getContext()
.getWindow()
.getDecorView(),
mGlobalLayoutListener);
if (mLinkedTarget != null) {
if (mLinkedViewLayoutChangeListenerWrapper == null) {
mLinkedViewLayoutChangeListenerWrapper = new LinkedViewLayoutChangeListenerWrapper(
mLinkedTarget);
}
if (!mLinkedViewLayoutChangeListenerWrapper.isAdded) {
mLinkedViewLayoutChangeListenerWrapper.attach();
}
}
}
void dismiss(boolean animateDismiss) {
if (mPopupWindow == null || !mPopupWindow.onBeforeDismissInternal(mOnDismissListener)) {
return;
}
if (mPopupWindow.mDisplayAnimateView == null || animateDismiss && (flag & CUSTOM_ON_ANIMATE_DISMISS) != 0) {
return;
}
Message msg = BasePopupEvent.getMessage(BasePopupEvent.EVENT_DISMISS);
if (animateDismiss) {
startDismissAnimate(mPopupWindow.mDisplayAnimateView.getWidth(),
mPopupWindow.mDisplayAnimateView.getHeight());
msg.arg1 = 1;
mPopupWindow.mDisplayAnimateView.removeCallbacks(dismissAnimationDelayRunnable);
mPopupWindow.mDisplayAnimateView.postDelayed(dismissAnimationDelayRunnable,
Math.max(dismissDuration, 0));
} else {
msg.arg1 = 0;
mPopupWindow.superDismiss();
}
BasePopupUnsafe.StackFetcher.remove(mPopupWindow);
sendEvent(msg);
}
private Runnable dismissAnimationDelayRunnable = new Runnable() {
@Override
public void run() {
flag &= ~CUSTOM_ON_ANIMATE_DISMISS;
if (mPopupWindow != null) {
//popup可能已经释放引用了
mPopupWindow.superDismiss();
}
}
};
void forceDismiss() {
if (mDismissAnimation != null) mDismissAnimation.cancel();
if (mDismissAnimator != null) mDismissAnimator.cancel();
if (mPopupWindow != null) {
KeyboardUtils.close(mPopupWindow.getContext());
}
if (dismissAnimationDelayRunnable != null) {
dismissAnimationDelayRunnable.run();
}
}
void onAnchorTop() {
}
void onAnchorBottom() {
}
@Override
public void onKeyboardChange(Rect keyboardBounds, boolean isVisible) {
if (mKeyboardStateChangeListener != null) {
mKeyboardStateChangeListener.onKeyboardChange(keyboardBounds, isVisible);
}
if (mUserKeyboardStateChangeListener != null) {
mUserKeyboardStateChangeListener.onKeyboardChange(keyboardBounds, isVisible);
}
}
void update(View v, boolean positionMode) {
if (!mPopupWindow.isShowing() || mPopupWindow.mContentView == null) return;
prepare(v, positionMode);
mPopupWindow.mPopupWindowProxy.update();
}
void onUpdate() {
if (mShowInfo != null) {
prepare(mShowInfo.mAnchorView == null ? null : mShowInfo.mAnchorView,
mShowInfo.positionMode);
}
}
void dispatchOutSideEvent(MotionEvent event) {
if (mPopupWindow != null) {
mPopupWindow.dispatchOutSideEvent(event);
}
}
static class InnerShowInfo {
View mAnchorView;
boolean positionMode;
InnerShowInfo(View mAnchorView, boolean positionMode) {
this.mAnchorView = mAnchorView;
this.positionMode = positionMode;
}
}
class LinkedViewLayoutChangeListenerWrapper implements ViewTreeObserver.OnPreDrawListener {
private View mTarget;
private boolean isAdded;
private float lastX, lastY;
private int lastWidth, lastHeight, lastVisible;
private boolean lastShowState, hasChange;
Rect lastLocationRect = new Rect();
Rect newLocationRect = new Rect();
public LinkedViewLayoutChangeListenerWrapper(View target) {
mTarget = target;
}
void attach() {
if (mTarget == null || isAdded) return;
mTarget.getGlobalVisibleRect(lastLocationRect);
refreshViewParams();
mTarget.getViewTreeObserver().addOnPreDrawListener(this);
isAdded = true;
}
void detach() {
if (mTarget == null || !isAdded) return;
try {
mTarget.getViewTreeObserver().removeOnPreDrawListener(this);
} catch (Exception e) {
}
isAdded = false;
}
void refreshViewParams() {
if (mTarget == null) return;
//之所以不直接用getGlobalVisibleRect,是因为getGlobalVisibleRect需要不断的找到parent然后获取位置,因此先比较自身属性,然后进行二次验证
float curX = mTarget.getX();
float curY = mTarget.getY();
int curWidth = mTarget.getWidth();
int curHeight = mTarget.getHeight();
int curVisible = mTarget.getVisibility();
boolean isShow = mTarget.isShown();
hasChange = (curX != lastX ||
curY != lastY ||
curWidth != lastWidth ||
curHeight != lastHeight ||
curVisible != lastVisible) && isAdded;
if (!hasChange) {
//不排除是recyclerview中那样子的情况,因此这里进行二次验证,获取view在屏幕中的位置
mTarget.getGlobalVisibleRect(newLocationRect);
if (!newLocationRect.equals(lastLocationRect)) {
lastLocationRect.set(newLocationRect);
//处理可能的在recyclerview回收的事情
if (!handleShowChange(mTarget, lastShowState, isShow)) {
hasChange = true;
}
}
}
lastX = curX;
lastY = curY;
lastWidth = curWidth;
lastHeight = curHeight;
lastVisible = curVisible;
lastShowState = isShow;
}
private boolean handleShowChange(View target, boolean lastShowState, boolean isShow) {
if (lastShowState && !isShow) {
if (mPopupWindow.isShowing()) {
dismiss(false);
return true;
}
} else if (!lastShowState && isShow) {
if (!mPopupWindow.isShowing()) {
mPopupWindow.tryToShowPopup(target, false);
return true;
}
}
return false;
}
@Override
public boolean onPreDraw() {
if (mTarget == null) return true;
refreshViewParams();
if (hasChange) {
update(mTarget, false);
}
return true;
}
}
@Nullable
static Activity findActivity(Object parent) {
return findActivity(parent, true);
}
@Nullable
static Activity findActivity(Object parent, boolean returnTopIfNull) {
Activity act = null;
if (parent instanceof Context) {
act = PopupUtils.getActivity((Context) parent);
} else if (parent instanceof Fragment) {
act = ((Fragment) parent).getActivity();
} else if (parent instanceof Dialog) {
act = PopupUtils.getActivity(((Dialog) parent).getContext());
}
if (act == null && returnTopIfNull) {
act = BasePopupSDK.getInstance().getTopActivity();
}
return act;
}
@Nullable
static View findDecorView(Object parent) {
View decorView = null;
Window window = null;
if (parent instanceof Dialog) {
window = ((Dialog) parent).getWindow();
} else if (parent instanceof DialogFragment) {
if (((DialogFragment) parent).getDialog() == null) {
decorView = ((DialogFragment) parent).getView();
} else {
window = ((DialogFragment) parent).getDialog().getWindow();
}
} else if (parent instanceof Fragment) {
decorView = ((Fragment) parent).getView();
} else if (parent instanceof Context) {
Activity act = PopupUtils.getActivity((Context) parent);
decorView = act == null ? null : act.findViewById(android.R.id.content);
}
if (decorView != null) {
return decorView;
} else {
return window == null ? null : window.getDecorView();
}
}
@Override
public void clear(boolean destroy) {
if (mPopupWindow != null && mPopupWindow.mDisplayAnimateView != null) {
//神奇的是,这个方式有可能失效,runnable根本就没有被remove掉
mPopupWindow.mDisplayAnimateView.removeCallbacks(dismissAnimationDelayRunnable);
}
if (eventObserverMap != null) {
eventObserverMap.clear();
}
if (mShowAnimation != null) {
mShowAnimation.cancel();
mShowAnimation.setAnimationListener(null);
}
if (mDismissAnimation != null) {
mDismissAnimation.cancel();
mDismissAnimation.setAnimationListener(null);
}
if (mShowAnimator != null) {
mShowAnimator.cancel();
mShowAnimator.removeAllListeners();
}
if (mDismissAnimator != null) {
mDismissAnimator.cancel();
mDismissAnimator.removeAllListeners();
}
if (mBlurOption != null) {
mBlurOption.clear();
}
if (mShowInfo != null) {
mShowInfo.mAnchorView = null;
}
if (mGlobalLayoutListener != null) {
PopupUiUtils.safeRemoveGlobalLayoutListener(mPopupWindow.getContext()
.getWindow()
.getDecorView(),
mGlobalLayoutListener);
}
if (mLinkedViewLayoutChangeListenerWrapper != null) {
mLinkedViewLayoutChangeListenerWrapper.detach();
}
dismissAnimationDelayRunnable = null;
mShowAnimation = null;
mDismissAnimation = null;
mShowAnimator = null;
mDismissAnimator = null;
eventObserverMap = null;
mPopupWindow = null;
mOnPopupWindowShowListener = null;
mOnDismissListener = null;
mOnBeforeShowCallback = null;
mBlurOption = null;
mBackgroundDrawable = null;
mBackgroundView = null;
mAutoShowInputEdittext = null;
mKeyboardStateChangeListener = null;
mShowInfo = null;
mLinkedViewLayoutChangeListenerWrapper = null;
mLinkedTarget = null;
mGlobalLayoutListener = null;
mUserKeyboardStateChangeListener = null;
mKeyEventListener = null;
keybaordAlignView = null;
}
}
|
package leetcode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author kangkang lou
*/
public class Main_345 {
public String reverseVowels(String s) {
char[] arr = {'a', 'e', 'i', 'o', 'u','A', 'E', 'I', 'O', 'U'};
List<Character> l = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
l.add(arr[i]);
}
Set<Integer> set = new HashSet<>();
List<Character> list = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (l.contains(c)) {
set.add(i);
list.add(0, c);
}
}
int pos = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (set.contains(i)) {
sb.append(list.get(pos++));
} else {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(new Main_345().reverseVowels("aA"));
System.out.println(new Main_345().reverseVowels("leetcode"));
}
}
|
package micro.websocket._config.actuator.httptrace;
import org.springframework.boot.actuate.trace.http.HttpTraceRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class MainConfig {
//https://www.programmersought.com/article/9988628357/
@Bean
@Primary
public HttpTraceRepository htttpTraceRepository() {
return new CustomTraceRepository();
}
}
|
public class SkyView
{
/** A rectangular array that holds the data representing a rectangular area of the sky. */
private double[][] view;
// Part(a)
/** Constructs a SkyView object from a 1-dimensional array of scan data.
* @param numRows the number of rows represented in the view
* Precondition: numRows > 0
* @param numCols the number of columns represented in the view
* Precondition: numCols > 0
* @param scanned the scan data received from the telescope, stored in telescope order
* Precondition: scanned.length == numRows * numCols
* Postcondition: view has been created as a rectangular 2-dimensional array
* with numRows rows and numCols columns and the values in
* scanned have been copied to view and are ordered as
* in the original rectangular area of sky.
*/
public SkyView(int numRows, int numCols, double[] scanned){
view=new double[numRows][numCols];
boolean goingRight=true;
int index=0;
for(int row=0;row<numRows;row++){
for(int col=0;col<numCols;col++){
if(goingRight){
view[row][col]=scanned[index];
}else{
view[row][numCols-1-col]=scanned[index];
}
index++;
}
goingRight=!goingRight;
}
}
// Part(b)
/** Returns the average of the values in a rectangular section of view.
* @param startRow the first row index of the section
* @param endRow the last row index of the section
* @param startCol the first column index of the section
* @param endCol the last column index of the section
* Precondition: 0 <= startRow <= endRow < view.length
* Precondition: 0 <= startCol <= endCol < view[0].length
* @return the average of the values in the specified section of view
*/
public double getAverage(int startRow, int endRow, int startCol, int endCol){
int count = 0;
double sum = 0.0;
for(int row = startRow;row<=endRow;row++){
for(int col=startCol;col<=endCol;col++){
sum+=view[row][col];
count++;
}
}
double average = sum/count;
return average;
}
/*******************************************************************************/
public double getViewElem(int r, int c) {
return view[r][c];
}
}
|
package com.jdyx.app.appvideo.service.impl;
import com.jdyx.app.appvideo.mapper.MessageMapper;
import com.jdyx.app.bean.Message;
import com.jdyx.app.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MessageServiceImpl implements MessageService {
@Autowired
MessageMapper messageMapper;
}
|
package com.takshine.wxcrm.message.sugar;
import java.util.ArrayList;
import java.util.List;
/**
* 传递给crm 新增项目接口的参数
* @author dengbo
*
*/
public class ProjectAdd extends BaseCrm{
private String rowid = null; //记录ID
private String name = null; //项目名称
private String startdate = null;//开始时间
private String enddate = null;//结束时间
private String status;//项目状态
private String statusname;
public String getStatusname() {
return statusname;
}
public void setStatusname(String statusname) {
this.statusname = statusname;
}
private String desc;//说明
private String priority;
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
private String priorityname;//优先级
private String assigner;//责任人
private String assignerid;//责任人名称
private String creater;
private String createdate;
private String modifier;
private String modifydate;
private String authority;//是否有分配权限,Y代表有权限,N代表没有
private String opptyid;
private String opptyname;
private String customer;
private String customerid;
public String getOpptyid() {
return opptyid;
}
public void setOpptyid(String opptyid) {
this.opptyid = opptyid;
}
public String getOpptyname() {
return opptyname;
}
public void setOpptyname(String opptyname) {
this.opptyname = opptyname;
}
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public String getCustomerid() {
return customerid;
}
public void setCustomerid(String customerid) {
this.customerid = customerid;
}
private List<OpptyAuditsAdd> audits = new ArrayList<OpptyAuditsAdd>();//跟进列表
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public List<OpptyAuditsAdd> getAudits() {
return audits;
}
public void setAudits(List<OpptyAuditsAdd> audits) {
this.audits = audits;
}
public String getCreater() {
return creater;
}
public void setCreater(String creater) {
this.creater = creater;
}
public String getCreatedate() {
return createdate;
}
public void setCreatedate(String createdate) {
this.createdate = createdate;
}
public String getModifier() {
return modifier;
}
public void setModifier(String modifier) {
this.modifier = modifier;
}
public String getModifydate() {
return modifydate;
}
public void setModifydate(String modifydate) {
this.modifydate = modifydate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPriorityname() {
return priorityname;
}
public void setPriorityname(String priorityname) {
this.priorityname = priorityname;
}
public String getAssigner() {
return assigner;
}
public void setAssigner(String assigner) {
this.assigner = assigner;
}
public String getAssignerid() {
return assignerid;
}
public void setAssignerid(String assignerid) {
this.assignerid = assignerid;
}
public String getRowid() {
return rowid;
}
public void setRowid(String rowid) {
this.rowid = rowid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStartdate() {
return startdate;
}
public void setStartdate(String startdate) {
this.startdate = startdate;
}
public String getEnddate() {
return enddate;
}
public void setEnddate(String enddate) {
this.enddate = enddate;
}
}
|
package VSMUtilityClasses;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.compress.compressors.CompressorInputStream;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
/**
* This class gets the buffered reader for a particular .bz2 file in the BLLIP
* corpus
*
* @author sameerkhurana10
*
*/
public class BLLIPCorpusReader {
public static BufferedReader getBufferedReaderForBZ2File(String fileIn)
throws FileNotFoundException, CompressorException {
FileInputStream fin = new FileInputStream(fileIn);
BufferedInputStream bis = new BufferedInputStream(fin);
CompressorInputStream input = new CompressorStreamFactory()
.createCompressorInputStream(bis);
BufferedReader br2 = new BufferedReader(new InputStreamReader(input));
return br2;
}
}
|
package org.apache.maven.plugin.deltacoverage.coverage;
import java.io.File;
import com.thoughtworks.xstream.XStream;
/**
* Class to read existing code coverage report and populates in memory graph of current code coverage.
* Currently supports Cobertura code coverage report format.
*
* @author Abhijeet_Kesarkar
*
* @see ModuleCoverage
*/
public class CoverageReportReader {
/**
* Reads the specified code coverage report in xml format.
* Uses xstream to convert from XML to java object.
* Xstream aliases are used to bridge gap between xml format and java object structure.
*
* @param coverageReport path to existing xml coverage report file
* @return {@link ModuleCoverage} instance
*/
public static ModuleCoverage getCoverageData(File coverageReport)
{
XStream xstream = new XStream();
xstream.alias("coverage", ModuleCoverage.class);
xstream.alias("package", PackageCoverage.class);
xstream.alias("class", ClassCoverage.class);
xstream.alias("method", MethodCoverage.class);
xstream.alias("line", LineCoverage.class);
xstream.alias("condition", ConditionCoverage.class);
xstream.alias("source", String.class);
xstream.useAttributeFor(ModuleCoverage.class, "timestamp");
xstream.useAttributeFor(ModuleCoverage.class, "lineRate");
xstream.useAttributeFor(ModuleCoverage.class, "branchRate");
xstream.useAttributeFor(ModuleCoverage.class, "version");
xstream.useAttributeFor(PackageCoverage.class, "name");
xstream.useAttributeFor(PackageCoverage.class, "lineRate");
xstream.useAttributeFor(PackageCoverage.class, "branchRate");
xstream.useAttributeFor(PackageCoverage.class, "complexity");
xstream.useAttributeFor(ClassCoverage.class, "name");
xstream.useAttributeFor(ClassCoverage.class, "filename");
xstream.useAttributeFor(ClassCoverage.class, "lineRate");
xstream.useAttributeFor(ClassCoverage.class, "branchRate");
xstream.useAttributeFor(ClassCoverage.class, "complexity");
xstream.useAttributeFor(MethodCoverage.class, "name");
xstream.useAttributeFor(MethodCoverage.class, "signature");
xstream.useAttributeFor(MethodCoverage.class, "lineRate");
xstream.useAttributeFor(MethodCoverage.class, "branchRate");
xstream.useAttributeFor(LineCoverage.class, "number");
xstream.useAttributeFor(LineCoverage.class, "hits");
xstream.useAttributeFor(LineCoverage.class, "branch");
xstream.useAttributeFor(LineCoverage.class, "conditionCoverage");
xstream.useAttributeFor(ConditionCoverage.class, "number");
xstream.useAttributeFor(ConditionCoverage.class, "type");
xstream.useAttributeFor(ConditionCoverage.class, "coverage");
xstream.aliasAttribute("condition-coverage", "conditionCoverage");
xstream.aliasAttribute("line-rate", "lineRate");
xstream.aliasAttribute("branch-rate", "branchRate");
return (ModuleCoverage) xstream.fromXML(coverageReport);
}
}
|
package duke.task;
import duke.Ui;
import java.lang.reflect.Array;
import java.util.ArrayList;
/**
* This class represents a TaskList, which is the list of tasks that Duke refers to to carry out commands provided
* to him.
*/
public class TaskList {
private ArrayList<Task> tasks;
/**
* Constructor for TaskList, which creates a new array of Tasks.
*/
public TaskList() {
this.tasks = new ArrayList<Task>();
}
/**
* Adds a task to the task list.
* @param task task to be added.
* @param shouldPrint true if should print, false if should not print
* @return output
*/
public String add(Task task, boolean shouldPrint) {
String str = null;
this.tasks.add(task);
if (shouldPrint) {
str = Ui.addTask(task);
str += Ui.numberOfTasks(tasks);
}
return str;
}
/**
* Finishes a task at a given index.
*
* @param index index from 1 (i.e lowest index is 1, so subtract 1 to get real index)
* @return output
*/
public String finishTask(int index) {
Task task = this.tasks.get(index - 1);
return task.doneTask(true);
}
/**
* Lists out the current items in the TaskList.
* @return output
*/
public String listOut() {
return Ui.listTasks(tasks);
}
/**
* This method is to be used when quitting and saving the file.
*
* @return the resulting string containing save-friendly information
*/
public String save() {
String output = "";
for (Task task: tasks) {
output += task.getSaveInfo() + "\n";
}
return output;
}
/**
* Deletes a task at a certain index
*
* @param index index from 1 (i.e lowest index is 1, so subtract 1 to get real index)
* @return output
*/
public String deleteTask(int index) {
Task item = this.tasks.remove(index - 1);
String str = Ui.deleteTask(item) + "\n";
str += Ui.remainingTasks(tasks);
return str;
}
/**
* Searches for a task given a keyword.
*
* @param keyword given keyword
* @return output
*/
public String searchTask(String keyword) {
TaskList matches = new TaskList();
for (Task t : tasks) {
if (t.doesNameContain(keyword)) {
matches.add(t, false);
}
}
String output = Ui.listTasksSearchResults(matches.tasks);
return output;
}
/**
* Returns the number of tasks in the list.
*
* @return number of tasks in the list.
*/
private int numTasks() {
return tasks.size();
}
/**
* Adds tags to the specified task through the index.
*
* @param index index of the task on the list
* @param tags array list of tags to be added to the task
* @return output
*/
public String addTags(int index, ArrayList<String> tags) {
Task taskToBeTagged = tasks.get(index - 1);
for (String tag: tags) {
taskToBeTagged.tag(tag);
}
String output = Ui.addTag(taskToBeTagged.toString());
return output;
}
}
|
package com.qunchuang.carmall.controller;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.qunchuang.carmall.service.AdminService;
import com.qunchuang.carmall.service.VerificationService;
import com.qunchuang.carmall.utils.AliyunOSSUtil;
import com.qunchuang.carmall.utils.BosUtils;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author Curtain
* @date 2019/1/21 11:17
*/
@RestController
public class CarMallRestController {
@Autowired
private AdminService adminService;
@Autowired
private VerificationService verificationService;
@Autowired
private WxMpService wxMpService;
@RequestMapping("/initAccount")
public String account(String curtain){
return adminService.init(curtain);
}
@RequestMapping("/sts")
public Object getStsToken() {
AssumeRoleResponse resp= AliyunOSSUtil.getToken();
Map<String,Object> result=new HashMap<>();
result.put("bucketName","biya-image");
result.put("endpoint","http://oss-cn-hangzhou.aliyuncs.com/");
result.put("assumeRoleResponse",resp);
result.put("resourceId", BosUtils.getZipUuid());
return result;
}
@RequestMapping("/getCode")
public String getCode(String phone){
return verificationService.getCode(phone);
}
@GetMapping(value = "/jsapisignature")
@ResponseBody
public Object createJsapiSignature(@RequestParam("url") String url) throws WxErrorException {
//是否加上url域名判断
return this.wxMpService.createJsapiSignature(url);
}
}
|
package com.medialets.data;
/**
* User: reaz
*/
public class MedialetsSignUpData {
private String firstName;
private String lastName;
private String company;
private String title;
private String phoneNumber;
private String email;
private String confirmEmail;
private String password;
private String confirmPassword;
public MedialetsSignUpData() {
setFirstName("Test User First Name").setLastName("Test User Last name")
.setCompany("Test Company").setPhoneNumber("212-212-2121")
.setEmail("testemail@test.com")
.setConfirmEmail("testemail@test.com");
setPassword("testPass");
setConfirmPassword("testPass");
setTitle("Test Architect");
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getConfirmEmail() {
return confirmEmail;
}
public void setConfirmEmail(String confirmEmail) {
this.confirmEmail = confirmEmail;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getFirstName() {
return firstName;
}
public MedialetsSignUpData setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public String getLastName() {
return lastName;
}
public MedialetsSignUpData setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public String getCompany() {
return company;
}
public MedialetsSignUpData setCompany(String company) {
this.company = company;
return this;
}
public String getPhoneNumber() {
return phoneNumber;
}
public MedialetsSignUpData setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
public String getEmail() {
return email;
}
public MedialetsSignUpData setEmail(String email) {
this.email = email;
return this;
}
}
|
package com.snow.gk.gurukula.pages;
import com.snow.gk.core.ui.elements.IElement;
import com.snow.gk.core.ui.elements.ILabel;
import com.snow.gk.core.ui.elements.impl.Element;
import com.snow.gk.core.ui.elements.impl.Label;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class MainPage extends HeaderPage {
@FindBy(xpath = "//h1[text() = 'Welcome to Gurukula!']")
private WebElement welcomeMessage;
@FindBy(xpath = "//div[contains(text(),'You are logged')]")
private WebElement txtYourLoggedInMessage;
public IElement getWelcomeMessage() { return getComponent(welcomeMessage, Element.class); }
public ILabel getYourLoggedIn() { return getComponent(txtYourLoggedInMessage, Label.class); }
public boolean validatePage(String username) {
String loggedInMsg = String.format("You are logged in as user \"%s\".", username);
if(getWelcomeMessage().getElement().isDisplayed() &&
loggedInMsg.equalsIgnoreCase(getYourLoggedIn().getLabel()))
return true;
else
return false;
}
}
|
package com.sunzequn.sdfs.node;
/**
* Created by Sloriac on 2016/12/18.
*/
public class LeaderHandler {
// 自己节点的相关信息
private NodeInfo selfInfo;
public LeaderHandler(NodeInfo selfInfo) {
this.selfInfo = selfInfo;
}
}
|
package com.nastenkapusechka.validation.analyzers;
import com.nastenkapusechka.validation.util.exceptions.EmailException;
import com.nastenkapusechka.validation.util.exceptions.PhoneNumberException;
import org.junit.Test;
public class ValidateAnalyzerTest {
ValidateAnalyzer analyzer = new ValidateAnalyzer();
@Test(expected = EmailException.class)
public void validate() throws Exception {
PlugClass cls = new PlugClass.Builder()
.withInnerClass("(495)1234567")
.build();
analyzer.validate(PlugClass.class
.getDeclaredField("innerClass"), cls);
}
@Test(expected = PhoneNumberException.class)
public void validate2() throws Exception {
PlugClass cls = new PlugClass.Builder()
.withInnerClass("good_email@mail.ru")
.build();
analyzer.validate(PlugClass.class
.getDeclaredField("innerClass"), cls);
}
@Test(expected = NullPointerException.class)
public void validate3() throws Exception {
PlugClass cls = new PlugClass.Builder()
.withInnerClass(null)
.build();
analyzer.validate(PlugClass.class
.getDeclaredField("innerClass"), cls);
}
}
|
package net.minecraft.entity;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
public abstract class EntityFlying extends EntityLiving {
public EntityFlying(World worldIn) {
super(worldIn);
}
public void fall(float distance, float damageMultiplier) {}
protected void updateFallState(double y, boolean onGroundIn, IBlockState state, BlockPos pos) {}
public void func_191986_a(float p_191986_1_, float p_191986_2_, float p_191986_3_) {
if (isInWater()) {
func_191958_b(p_191986_1_, p_191986_2_, p_191986_3_, 0.02F);
moveEntity(MoverType.SELF, this.motionX, this.motionY, this.motionZ);
this.motionX *= 0.800000011920929D;
this.motionY *= 0.800000011920929D;
this.motionZ *= 0.800000011920929D;
} else if (isInLava()) {
func_191958_b(p_191986_1_, p_191986_2_, p_191986_3_, 0.02F);
moveEntity(MoverType.SELF, this.motionX, this.motionY, this.motionZ);
this.motionX *= 0.5D;
this.motionY *= 0.5D;
this.motionZ *= 0.5D;
} else {
float f = 0.91F;
if (this.onGround)
f = (this.world.getBlockState(new BlockPos(MathHelper.floor(this.posX), MathHelper.floor((getEntityBoundingBox()).minY) - 1, MathHelper.floor(this.posZ))).getBlock()).slipperiness * 0.91F;
float f1 = 0.16277136F / f * f * f;
func_191958_b(p_191986_1_, p_191986_2_, p_191986_3_, this.onGround ? (0.1F * f1) : 0.02F);
f = 0.91F;
if (this.onGround)
f = (this.world.getBlockState(new BlockPos(MathHelper.floor(this.posX), MathHelper.floor((getEntityBoundingBox()).minY) - 1, MathHelper.floor(this.posZ))).getBlock()).slipperiness * 0.91F;
moveEntity(MoverType.SELF, this.motionX, this.motionY, this.motionZ);
this.motionX *= f;
this.motionY *= f;
this.motionZ *= f;
}
this.prevLimbSwingAmount = this.limbSwingAmount;
double d1 = this.posX - this.prevPosX;
double d0 = this.posZ - this.prevPosZ;
float f2 = MathHelper.sqrt(d1 * d1 + d0 * d0) * 4.0F;
if (f2 > 1.0F)
f2 = 1.0F;
this.limbSwingAmount += (f2 - this.limbSwingAmount) * 0.4F;
this.limbSwing += this.limbSwingAmount;
}
public boolean isOnLadder() {
return false;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\entity\EntityFlying.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
/*
打印等腰三角形:思路打印反三角+正三角
*/
class IsoscelesTriangle
{
public static void main(String[] args)
{
for (int x = 0; x < 5; x++)
{
for (int y = x+1; y<5;y++)
{
System.out.print("-");
}
for (int z=0; z<=x; z++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
|
package com.espendwise.tools.gencode.hbmxml.single;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the mypackage package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: mypackage
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Class }
*
*/
public Class createClass() {
return new Class();
}
/**
* Create an instance of {@link HibernateMapping }
*
*/
public HibernateMapping createHibernateMapping() {
return new HibernateMapping();
}
/**
* Create an instance of {@link Meta }
*
*/
public Meta createMeta() {
return new Meta();
}
/**
* Create an instance of {@link Id }
*
*/
public Id createId() {
return new Id();
}
/**
* Create an instance of {@link Property }
*
*/
public Property createProperty() {
return new Property();
}
/**
* Create an instance of {@link Version }
*
*/
public Version createVersion() {
return new Version();
}
/**
* Create an instance of {@link Column }
*
*/
public Column createColumn() {
return new Column();
}
/**
* Create an instance of {@link Param }
*
*/
public Param createParam() {
return new Param();
}
/**
* Create an instance of {@link Generator }
*
*/
public Generator createGenerator() {
return new Generator();
}
}
|
package cinema;
public class Main {
public static void main(String[] args) {
Reserve_Cinema reserve_cinema = new Reserve_Cinema("CGV", 6, 13);
reserve_cinema.printCinemaSeats();
if (reserve_cinema.reserveSeat("F03")) {
System.out.println("Trả tiền cho việc đặt ghế");
} else {
System.out.println("Ghế không tồn tại");
}
}
}
|
class Car {
//private으로 brand, owner, company, price 지정
//생성자 만들기
//메서드 start(), stop() 4번방법으로 만들기
public static void main(String ar[]) {
Car c1=new Car("sonata","mike","hyundae",210);
Car c2=new Car("Alice","kia",300);
Car c3=new Car("Tom",350);
Car c4=new Car("Benz","Tomas","mk",500);
//c3의 멤버변수들 출력
//c4의 메서드 호출
}
}
|
package univ.m2acdi.apprentissageborel.util;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import java.io.Serializable;
import java.util.Locale;
public class TextSpeaker implements Serializable, TextToSpeech.OnInitListener {
private static Locale language = Locale.FRANCE;
private static TextToSpeech textToSpeech;
private static boolean isReady = false;
public TextSpeaker(Context context){
textToSpeech = new TextToSpeech(context, this);
textToSpeech.setPitch(0.8f);
textToSpeech.setSpeechRate(0.9f);
}
@Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS){
textToSpeech.setLanguage(language);
isReady = true;
} else{
isReady = false;
}
}
public void speakText(String text){
if(isReady) {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
public void setSpeedRate(float speechrate) {
textToSpeech.setSpeechRate(speechrate);
}
public void setPitchRate(float pitchrate) {
textToSpeech.setPitch(pitchrate);
}
public boolean isSpeaking() {
return textToSpeech.isSpeaking();
}
public void pause(int duration){
textToSpeech.playSilentUtterance(duration, TextToSpeech.QUEUE_ADD, null);
}
public void stop() {
textToSpeech.stop();
}
public void destroy() {
textToSpeech.shutdown();
}
}
|
package com.designPattern.SOLID.ocp.solution;
public class WhatsAppServiceImpl implements NotificationService {
public void sendOTP(String message) {
// SEND OTP ON WHATSAPP
}
}
|
package com.example.tiamo.gym;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
public class MyContentProvider extends ContentProvider {
private WifiSsidDatabaseHelper dbOpenHelper;
private static final int trainercode =1;
private static final int newcode=2;
//数据库
public static final String AUTOHORITY = "myprovider";//权限
private static final String DATABASE_NAME = "gym.db";//数据库名称
public static final String TABLE_TRAINERINFO = "table_trainerinfo";//用户表和课程表
public static final String TABLE_NEW= "table_new";
private static final UriMatcher mMatcher;
static{
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 初始化
mMatcher.addURI(AUTOHORITY,"table_trainerinfo", trainercode);
mMatcher.addURI(AUTOHORITY, "table_new", newcode);
}
//创建数据库,只执行一次,如果创建了就不会再执行
@Override
public boolean onCreate() {
dbOpenHelper=new WifiSsidDatabaseHelper(getContext(),DATABASE_NAME,null,1);
dbOpenHelper.getReadableDatabase();
dbOpenHelper.getWritableDatabase();
return false;
}
//查询数据库
@Override
public Cursor query(Uri uri, String[] projection, String where, String[] selectionArgs, String sortOrder) {
String table=getTableName(uri);
SQLiteDatabase db=dbOpenHelper.getReadableDatabase();
return db.query(table, projection, where, selectionArgs, null, null, sortOrder, null);
}
@Override
public String getType(Uri uri) {
return null;
}
//插入数据
@Override
public Uri insert(Uri uri, ContentValues values) {
String table=getTableName(uri);
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
db.insert(table, "_id", values);
return null;
}
//删除数据
@Override
public int delete(Uri uri, String where, String[] selectionArgs) {
String table=getTableName(uri);
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
return db.delete(table, where, selectionArgs);
}
//修改数据
@Override
public int update(Uri uri, ContentValues values, String where, String[] selectionArgs) {
String table=getTableName(uri);
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
return db.update(table, values, where, selectionArgs);
}
private String getTableName(Uri uri){
String tableName = null;
switch (mMatcher.match(uri)) {
case trainercode:
tableName = TABLE_TRAINERINFO;
break;
case newcode:
tableName = TABLE_NEW;
break;
}
return tableName;
}
public class WifiSsidDatabaseHelper extends SQLiteOpenHelper {
private static final String CRATE_TABLE_TRAINERINFO_SQL =
"create table "
+ TABLE_TRAINERINFO
+"(name VARCHAR(50) primary key,age VARCHAR(50),sex VARCHAR(50),info VARCHAR(50))";
private static final String CRATE_TABLE_NEW_SQL =
"create table "
+TABLE_NEW
+"(title VARCHAR(50) primary key,content VARCHAR(50),time VARCHAR(50))";
public WifiSsidDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CRATE_TABLE_TRAINERINFO_SQL);
db.execSQL(CRATE_TABLE_NEW_SQL);
}
//版本更新
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
|
package com.studio.saradey.aplicationvk.ui.holder;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.view.View;
import android.widget.TextView;
import com.studio.saradey.aplicationvk.MyAplication;
import com.studio.saradey.aplicationvk.R;
import com.studio.saradey.aplicationvk.common.manager.MyFragmentManager;
import com.studio.saradey.aplicationvk.common.utils.Utils;
import com.studio.saradey.aplicationvk.common.utils.VkListHelper;
import com.studio.saradey.aplicationvk.model.Likes;
import com.studio.saradey.aplicationvk.model.Place;
import com.studio.saradey.aplicationvk.model.WallItem;
import com.studio.saradey.aplicationvk.model.view.NewsItemFooterViewModel;
import com.studio.saradey.aplicationvk.model.view.couter.CommentCounterViewModel;
import com.studio.saradey.aplicationvk.model.view.couter.LikeCounterViewModel;
import com.studio.saradey.aplicationvk.model.view.couter.RepostCounterViewModel;
import com.studio.saradey.aplicationvk.rest.api.LikeEventOnSubscribe;
import com.studio.saradey.aplicationvk.rest.api.WallApi;
import com.studio.saradey.aplicationvk.rest.model.request.WallGetByIdRequestModel;
import com.studio.saradey.aplicationvk.ui.activity.BaseActivity;
import com.studio.saradey.aplicationvk.ui.fragment.CommentsFragment;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.realm.Realm;
import io.realm.RealmObject;
/**
* @author jtgn on 11.08.2018
*/
public class NewsItemFooterHolder extends BaseViewHolder<NewsItemFooterViewModel> {
@Inject
Typeface mGoogleFontTypeface;
@BindView(R.id.tv_date)
TextView tvDate;
@BindView(R.id.tv_likes_count)
TextView tvLikesCount;
@BindView(R.id.tv_likes_icon)
TextView tvLikesIcon;
@BindView(R.id.tv_comments_icon)
TextView tvCommentIcon;
@BindView(R.id.tv_comments_count)
TextView tvCommentsCount;
@BindView(R.id.tv_reposts_icon)
TextView tvRepostIcon;
@BindView(R.id.tv_reposts_count)
TextView tvRepostsCount;
public static final String POST = "post";
@BindView(R.id.rl_comments)
View rlComments;
@BindView(R.id.rl_likes)
View rlLikes;
@Inject
MyFragmentManager mFragmentManager;
@Inject
WallApi mWallApi;
private Resources mResources;
private Context mContext;
public NewsItemFooterHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
MyAplication.getApplicationComponent().inject(this);
mContext = itemView.getContext();
mResources = mContext.getResources();
tvLikesIcon.setTypeface(mGoogleFontTypeface);
tvCommentIcon.setTypeface(mGoogleFontTypeface);
tvRepostIcon.setTypeface(mGoogleFontTypeface);
}
@Override
public void bindViewHolder(NewsItemFooterViewModel item) {
tvDate.setText(Utils.parseDate(item.getDateLong(), mContext)); //установка даты
bindLikes(item.getLikes());
bindComments(item.getComments());
bindReposts(item.getReposts());
rlComments.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mFragmentManager.addFragment((BaseActivity) view.getContext(),
CommentsFragment.newInstance(new Place(String.valueOf(item.getOwnerId()), String.valueOf(item.getId()))),
R.id.main_wrapper);
}
});
rlLikes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
like(item);
}
});
}
//установка лайков
private void bindLikes(LikeCounterViewModel likes) {
tvLikesCount.setText(String.valueOf(likes.getCount()));
tvLikesCount.setTextColor(mResources.getColor(likes.getTextColor()));
tvLikesIcon.setTextColor(mResources.getColor(likes.getIconColor()));
}
//установка комментариев
private void bindComments(CommentCounterViewModel comments) {
tvCommentsCount.setText(String.valueOf(comments.getCount()));
tvCommentsCount.setTextColor(mResources.getColor(comments.getTextColor()));
tvCommentIcon.setTextColor(mResources.getColor(comments.getIconColor()));
}
//установка репостов
private void bindReposts(RepostCounterViewModel reposts) {
tvRepostsCount.setText(String.valueOf(reposts.getCount()));
tvRepostsCount.setTextColor(mResources.getColor(reposts.getTextColor()));
tvRepostIcon.setTextColor(mResources.getColor(reposts.getIconColor()));
}
@Override
public void unbindViewHolder() {
tvDate.setText(null);
tvLikesCount.setText(null);
tvCommentsCount.setText(null);
tvRepostsCount.setText(null);
}
//метод like, который вызывает likeObservable
// и устанавливает или снимает лайк на основании информации от сервера, и метод getWallItemFromRealm.
public void saveToDb(RealmObject item) {
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(realm1 -> realm1.copyToRealmOrUpdate(item));
}
public Observable<LikeCounterViewModel> likeObservable(int ownerId, int postId, Likes likes) {
return Observable.create(new LikeEventOnSubscribe(POST, ownerId, postId, likes))
.observeOn(Schedulers.io())
.flatMap(count -> {
return mWallApi.getById(new WallGetByIdRequestModel(ownerId, postId).toMap());
})
.flatMap(full -> Observable.fromIterable(VkListHelper.getWallList(full.response)))
.doOnNext(this::saveToDb)
.map(wallItem -> new LikeCounterViewModel(wallItem.getLikes()));
}
@SuppressLint("CheckResult")
public void like(NewsItemFooterViewModel item) {
WallItem wallItem = getWallItemFromRealm(item.getId());
likeObservable(wallItem.getOwnerId(), wallItem.getId(), wallItem.getLikes())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(likes -> {
item.setLikes(likes);
bindLikes(likes);
}, Throwable::printStackTrace);
}
public WallItem getWallItemFromRealm(int postId) {
Realm realm = Realm.getDefaultInstance();
WallItem wallItem = realm.where(WallItem.class)
.equalTo("id", postId)
.findFirst();
return realm.copyFromRealm(wallItem);
}
}
|
package com.smclaughlin.tps.utils;
/**
* Created by sineadmclaughlin on 26/11/2016.
*/
public class FlashMessageTest extends AbstractPojoTester<FlashMessage> {
@Override
protected FlashMessage getPojoInstance() {
return new FlashMessage();
}
@Override
public void setCheckEquals() {
checkEquals = false;
}
}
|
package Loja;
public abstract class Pessoa
{
//Atributos:
private String nome;
private char genero;
private int anoNascimento;
//Construtores:
public Pessoa(String nome, char genero, int anoNascimento)
{
super();
this.nome = nome;
this.genero = genero;
this.anoNascimento = anoNascimento;
}
public Pessoa(String nome)
{
super();
this.nome = nome;
}
//Getters and Setters:
public String getNome()
{
return nome;
}
public void setNome(String nome)
{
this.nome = nome;
}
public char getGenero()
{
return genero;
}
public void setGenero(char genero)
{
this.genero = genero;
}
public int getAnoNascimento()
{
return anoNascimento;
}
public void setAnoNascimento(int anoNascimento)
{
this.anoNascimento = anoNascimento;
}
//Métodos:
public void voltaIdade(int anoAtual, int anoNascimento)
{
if (this.anoNascimento == 0 || this.anoNascimento <=1900)
{
System.out.println("Idade não pode ser calculada. Dados inválidos.");
}
else
{
int idade = anoAtual - anoNascimento;
System.out.printf("Idade: %d anos",idade);
}
}
}
|
package ru.hse.rpg.characters;
import ru.hse.rpg.AttackTarget;
import ru.hse.rpg.Damage;
public final class DeadMonster implements AttackTarget{
@Override
public AttackTarget apply(Damage damage) {
System.out.println("Monster is already dead. Attack is useless and causes no damage.");
return this;
}
@Override
public boolean isDead() {
return true;
}
}
|
package com.teemo.sbmp.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.teemo.sbmp.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author teemo
* @since 2020-02-16
*/
public interface IUserService extends IService<User> {
List<User> selectPage();
List<User> selectPage2(Page<User> page);
}
|
package com.tingke.admin.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "aliyun.send")
@Data
public class SendProperties {
private String accessKeyId;
private String accessKeySecret;
private String signName;
private String verifyCodeTemplate;
}
|
package com.acme.banking.dbo.domain;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class ClientTest {
@Test
public void shouldSavePropertiesWhenCreated() {
final long id = 1L;
final String name = "dummy client name";
Client sut = new Client(id, name);
assertThat(sut.getId(), equalTo(id));
assertThat(sut.getName(), equalTo(name));
}
@Test(expected = IllegalArgumentException.class)
public void shouldGetErrorWhenIdIsNull() {
new Client(null,"name");
}
@Test(expected = IllegalArgumentException.class)
public void shouldGetErrorWhenIdIsNegative() {
new Client(-1L,"name");
}
@Test(expected = IllegalArgumentException.class)
public void shouldGetErrorWhenNameIsNull() {
new Client(0L,null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldGetErrorWhenNameIsEmpty() {
new Client(0L,"");
}
@Test(expected = IllegalArgumentException.class)
public void shouldGetErrorWhenNameIsRestricted() {
new Client(0L,"Bill Gates");
}
}
|
package edu.kit.pse.osip.core.model.behavior;
import edu.kit.pse.osip.core.model.base.AbstractTank;
/**
* An Alarm which monitors whether the temperature breaks a given threshold.
*
* @author Maximilian Schwarzmann
* @version 1.0
*/
public class TemperatureAlarm extends TankAlarm<Float> {
/**
* Creates a new TemperatureAlarm.
*
* @param tank The tank to monitor the temperature.
* @param threshold The threshold in °K.
* @param behavior Whether the alarm should trigger if the temperature is above or below to threshold.
*/
public TemperatureAlarm(AbstractTank tank, Float threshold, AlarmBehavior behavior) {
super(tank, threshold, behavior);
}
/**
* Returns the temperature of the tank.
*
* @return the temperature.
*/
protected final Float getNotifiedValue() {
return liquid.getTemperature();
}
}
|
package writeAndReadXML;
public interface LocationReaderInterface {
boolean retrieveEventIdAndPrice();
}
|
package longestsequence;
public class LongestSequence {
private int[][] input = new int[25][25];
private int[] templongest = new int[25];
private int inputindex = 0, inputlength = 0, longest = 0, inputbefore, totaluserinputs = 0;
private String output = "Longest non decreasing sequence(s):\n";
public boolean maxinputs() {
if (totaluserinputs == 25)
return true;
else
return false;
}
public LongestSequence() {
int lownum = -9999999;
for (int counter1 = 0; counter1 <= 24; counter1++) {
for (int counter2 = 0; counter2 <= 24; counter2++) {
input[counter2][counter1] = lownum;
}
lownum = lownum - 1;
}
}
public void setInput(int a) {
if ((inputindex == 0) && (inputlength == 0)) {
// first user input v
input[inputindex][inputlength] = a;
inputbefore = a;
inputlength = inputlength + 1;
} else {
// everything after first user input v
if (a >= inputbefore) {
input[inputindex][inputlength] = a;
inputbefore = a;
inputlength = inputlength + 1;
} else {
inputlength = 0;
inputindex = inputindex + 1;
input[inputindex][inputlength] = a;
inputbefore = a;
inputlength = inputlength + 1;
}
}
totaluserinputs = totaluserinputs + 1;
}
public void DetermineLongest() {
for (int asdf = 0; asdf <= 24; asdf++) {
templongest[asdf] = 0;
}
for (int sequencenumber = 0; sequencenumber < totaluserinputs; sequencenumber++) {
int numberbefore = input[sequencenumber][0];
for (int sequencelength = 0; sequencelength < totaluserinputs; sequencelength++) {
if (input[sequencenumber][sequencelength] >= numberbefore) {
templongest[sequencenumber] = templongest[sequencenumber] + 1;
}
numberbefore = input[sequencenumber][sequencelength];
}
if (templongest[sequencenumber] > longest)
longest = templongest[sequencenumber];
}
}
public void buildOutput() {
output = "Longest non decreasing sequence(s):\n";
if (longest > 1) {
for (int counter = 0; counter <= 24; counter++) {
if (templongest[counter] == longest) {
for (int counter2 = 0; counter2 <= (longest - 1); counter2++) {
output = output + input[counter][counter2] + " ";
}
output = output + "\n";
}
}
} else {
output = output + "There were no non decreasing sequences";
}
}
public String getOutput() {
return (output);
}
public void reset() {
inputindex = inputlength = longest = totaluserinputs = 0;
output = "Longest non decreasing sequence(s):\n";
int lownum = -9999999;
for (int counter1 = 0; counter1 <= 24; counter1++) {
for (int counter2 = 0; counter2 <= 24; counter2++) {
input[counter2][counter1] = lownum;
}
lownum = lownum - 1;
}
}
}
|
/**
*
*/
package collections;
import java.util.HashSet;
/**
* @author Ashish
*
* The following program demonstrates the use of Hash set.
*
* Hash set is faster than Tree set.Hash Set is not based on insertion order.
*
* The set interface dosen't allow duplicate value.
*
*/
public class Set1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Integer> obj=new HashSet<>(); // New Hash set is created to store Integer values.
obj.add(5);
obj.add(4);
obj.add(3); // Values are added into the Hash set
obj.add(2);
obj.add(1);
for(int i: obj) // Enhanced for loop is used to iterate the set
{
System.out.println(i); // Values within the Hash set are displayed.
}
}
}
|
package de.zarncke.lib.unit;
import org.junit.Test;
import de.zarncke.lib.err.GuardedTest;
import de.zarncke.lib.err.Warden;
public class UnitTest extends GuardedTest {
private UnitSystem units;
@Override
public void setUp() throws Exception {
super.setUp();
this.units = new UnitSystem();
}
@Test
public void testValues() {
Value a3 = this.units.byName("A").value(3);
Value a4 = this.units.byName("A").value(4);
assertEquals(3 + 4, a3.plus(a4).getAmount(), 0.00001);
this.units.add(new DerivedUnit("A'", this.units.byName("A"), 2));
Value as1 = this.units.byName("A'").value(1);
assertEquals(3 + 2 * 1, a3.plus(as1).getAmount(), 0.00001);
}
@Test
public void testIllegal() {
Value a3 = this.units.byName("A").value(3);
Value a4 = this.units.byName("B").value(4);
try {
a3.plus(a4);
fail("must fail -> incompatible");
} catch (IllegalArgumentException e) {
Warden.disregard(e);
}
}
}
|
/*
* Copyright 2011 frdfsnlght <frdfsnlght@gmail.com>.
*
* 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.frdfsnlght.transporter.command;
import com.frdfsnlght.transporter.Context;
import com.frdfsnlght.transporter.LocalWorldImpl;
import com.frdfsnlght.transporter.Permissions;
import com.frdfsnlght.transporter.Utils;
import com.frdfsnlght.transporter.Worlds;
import com.frdfsnlght.transporter.api.TransporterException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.command.Command;
/**
*
* @author frdfsnlght <frdfsnlght@gmail.com>
*/
public class WorldCommand extends TrpCommandProcessor {
private static final String GROUP = "world ";
@Override
public boolean matches(Context ctx, Command cmd, List<String> args) {
return super.matches(ctx, cmd, args) &&
GROUP.startsWith(args.get(0).toLowerCase());
}
@Override
public List<String> getUsage(Context ctx) {
List<String> cmds = new ArrayList<String>();
cmds.add(getPrefix(ctx) + GROUP + "list");
// TODO: change to add, add remove
cmds.add(getPrefix(ctx) + GROUP + "add <world> [<env>[/<gen>] [<seed>]]");
cmds.add(getPrefix(ctx) + GROUP + "remove <world>");
cmds.add(getPrefix(ctx) + GROUP + "load <world>");
cmds.add(getPrefix(ctx) + GROUP + "unload <world>");
if (ctx.isPlayer())
cmds.add(getPrefix(ctx) + GROUP + "go [<coords>] [<world>]");
cmds.add(getPrefix(ctx) + GROUP + "spawn [<coords>] [<world>]");
cmds.add(getPrefix(ctx) + GROUP + "get <world> <option>|*");
cmds.add(getPrefix(ctx) + GROUP + "set <world> <option> <value>");
return cmds;
}
@Override
public void process(final Context ctx, Command cmd, List<String> args) throws TransporterException {
args.remove(0);
if (args.isEmpty())
throw new CommandException("do what with a world?");
String subCmd = args.remove(0).toLowerCase();
if ("list".startsWith(subCmd)) {
Permissions.require(ctx.getPlayer(), "trp.world.list");
List<LocalWorldImpl> worlds = Worlds.getAll();
Collections.sort(worlds, new Comparator<LocalWorldImpl>() {
@Override
public int compare(LocalWorldImpl a, LocalWorldImpl b) {
return a.getName().compareToIgnoreCase(b.getName());
}
});
ctx.send("%d worlds:", worlds.size());
for (LocalWorldImpl world : worlds) {
ctx.send(" %s (%s/%s) %s %s",
world.getName(),
world.getEnvironment(),
(world.getGenerator() == null) ? "-" : world.getGenerator(),
(world.getSeed() == null) ? "-" : world.getSeed(),
world.isLoaded() ? "loaded" : "not loaded");
ctx.send(" autoLoad: %s", world.getAutoLoad());
}
return;
}
if ("add".startsWith(subCmd)) {
if (args.isEmpty())
throw new CommandException("world name required");
String worldName = args.remove(0);
String environment = "NORMAL";
String generator = null;
String seed = null;
if (! args.isEmpty()) {
environment = args.remove(0);
int pos = environment.indexOf("/");
if (pos != -1) {
generator = environment.substring(pos + 1);
environment = environment.substring(0, pos);
}
if (! args.isEmpty())
seed = args.remove(0);
}
Environment env;
try {
env = Utils.valueOf(World.Environment.class, environment);
} catch (IllegalArgumentException e) {
throw new CommandException("%s value for environment", e.getMessage());
}
Permissions.require(ctx.getPlayer(), "trp.world.add");
LocalWorldImpl wp = new LocalWorldImpl(worldName, env, generator, seed);
wp.load(ctx);
ctx.sendLog("added world '%s'", worldName);
Worlds.add(wp);
return;
}
if ("remove".startsWith(subCmd)) {
if (args.isEmpty())
throw new CommandException("world name required");
String name = args.remove(0);
LocalWorldImpl world = Worlds.find(name);
if (world == null)
throw new CommandException("unknown or ambiguous world '%s'", name);
Permissions.require(ctx.getPlayer(), "trp.world.remove");
Worlds.remove(world);
ctx.sendLog("removed world '%s'", name);
return;
}
if ("load".startsWith(subCmd)) {
if (args.isEmpty())
throw new CommandException("world name required");
final String name = args.remove(0);
Permissions.require(ctx.getPlayer(), "trp.world.load");
LocalWorldImpl world = Worlds.find(name);
if (world == null)
throw new CommandException("unknown or ambiguous world '%s'", name);
if (world.isLoaded())
throw new CommandException("world '%s' is already loaded", world.getName());
ctx.send("loading world '%s'...", world.getName());
world.load(ctx);
ctx.send("loaded world '%s'", world.getName());
return;
}
if ("unload".startsWith(subCmd)) {
if (args.isEmpty())
throw new CommandException("world name required");
String name = args.remove(0);
Permissions.require(ctx.getPlayer(), "trp.world.unload");
LocalWorldImpl world = Worlds.find(name);
if (world == null)
throw new CommandException("unknown or ambiguous world '%s'", name);
if (! world.isLoaded())
throw new CommandException("world '%s' is not loaded", world.getName());
ctx.send("unloading world '%s'...", world.getName());
World w = world.unload();
ctx.send("unloaded world '%s'", world.getName());
return;
}
if ("go".startsWith(subCmd)) {
if (! ctx.isPlayer())
throw new CommandException("must be a player to use this command");
World world = ctx.getPlayer().getWorld();
Location location = world.getSpawnLocation();
String locationString = null;
if ((! args.isEmpty()) && (args.get(0).indexOf(',') != -1))
locationString = args.remove(0);
if (! args.isEmpty()) {
String name = args.remove(0);
LocalWorldImpl bworld = Worlds.find(name);
if (bworld == null)
throw new CommandException("unknown or ambiguous world '%s'", name);
if (! bworld.isLoaded()) {
ctx.send("loading world '%s'...", world.getName());
bworld.load(ctx);
ctx.send("loaded world '%s'", world.getName());
}
world = bworld.getWorld();
location = world.getSpawnLocation();
name = bworld.getName();
}
if (locationString != null) {
String ordStrings[] = locationString.split(",");
double ords[] = new double[ordStrings.length];
for (int i = 0; i < ordStrings.length; i++)
try {
ords[i] = Double.parseDouble(ordStrings[i]);
} catch (NumberFormatException e) {
throw new CommandException("invalid ordinate '%s'", ordStrings[i]);
}
if (ords.length == 2) {
// given x,z, so figure out sensible y
int y = world.getHighestBlockYAt((int)ords[0], (int)ords[1]) + 1;
while (y > 1) {
if ((world.getBlockTypeIdAt((int)ords[0], y, (int)ords[1]) == 0) &&
(world.getBlockTypeIdAt((int)ords[0], y, (int)ords[1]) == 0)) break;
y--;
}
if (y == 1)
throw new CommandException("unable to locate a space big enough for you");
location = new Location(world, ords[0], y, ords[1]);
} else if (ords.length == 3)
location = new Location(world, ords[0], ords[1], ords[2]);
else
throw new CommandException("expected 2 or 3 ordinates");
}
Permissions.require(ctx.getPlayer(), "trp.world.go");
ctx.getPlayer().teleport(location);
ctx.sendLog("teleported to world '%s'", world.getName());
return;
}
if ("spawn".startsWith(subCmd)) {
World world = ctx.isPlayer() ? ctx.getPlayer().getWorld() : null;
Location location = ctx.isPlayer() ? ctx.getPlayer().getLocation() : null;
String locationString = null;
if ((! args.isEmpty()) && (args.get(0).indexOf(',') != -1))
locationString = args.remove(0);
if (! args.isEmpty()) {
String name = args.remove(0);
LocalWorldImpl bworld = Worlds.find(name);
if (bworld == null)
throw new CommandException("unknown world '%s'", name);
if (! bworld.isLoaded())
throw new CommandException("world '%s' is not loaded", bworld.getName());
world = bworld.getWorld();
}
if ((world != null) && (locationString != null)) {
String ordStrings[] = locationString.split(",");
double ords[] = new double[ordStrings.length];
for (int i = 0; i < ordStrings.length; i++)
try {
ords[i] = Double.parseDouble(ordStrings[i]);
} catch (NumberFormatException e) {
throw new CommandException("invalid ordinate '%s'", ordStrings[i]);
}
if (ords.length == 2) {
// given x,z, so figure out sensible y
int y = world.getHighestBlockYAt((int)ords[0], (int)ords[1]) + 1;
while (y > 1) {
if ((world.getBlockTypeIdAt((int)ords[0], y, (int)ords[1]) == 0) &&
(world.getBlockTypeIdAt((int)ords[0], y, (int)ords[1]) == 0)) break;
y--;
}
if (y == 1)
throw new CommandException("unable to locate a space big enough for a player");
location = new Location(world, ords[0], y, ords[1]);
} else if (ords.length == 3)
location = new Location(world, ords[0], ords[1], ords[2]);
else
throw new CommandException("expected 2 or 3 ordinates");
}
if ((world != null) && (location == null))
throw new CommandException("location required");
if (world == null)
throw new CommandException("world name required");
Permissions.require(ctx.getPlayer(), "trp.world.spawn");
world.setSpawnLocation(location.getBlockX(), location.getBlockY(), location.getBlockZ());
ctx.sendLog("set spawn location for world '%s'", world.getName());
return;
}
if ("set".startsWith(subCmd)) {
if (args.isEmpty())
throw new CommandException("world name required");
String name = args.remove(0);
LocalWorldImpl world = Worlds.find(name);
if (world == null)
throw new CommandException("unknown world '%s'", name);
if (args.isEmpty())
throw new CommandException("option name required");
String option = args.remove(0);
if (args.isEmpty())
throw new CommandException("option value required");
String value = args.remove(0);
world.setOption(ctx, option, value);
return;
}
if ("get".startsWith(subCmd)) {
if (args.isEmpty())
throw new CommandException("world name required");
String name = args.remove(0);
LocalWorldImpl world = Worlds.find(name);
if (world == null)
throw new CommandException("unknown world '%s'", name);
if (args.isEmpty())
throw new CommandException("option name required");
String option = args.remove(0);
world.getOptions(ctx, option);
return;
}
throw new CommandException("do what with a world?");
}
}
|
package org.seasar.silverlight.connector;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface Connector
{
void doJSON(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws IOException, ServletException;
}
|
package com.tencent.mm.plugin.emoji.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class EmojiAddCustomDialogUI$4 implements OnClickListener {
final /* synthetic */ EmojiAddCustomDialogUI ilg;
EmojiAddCustomDialogUI$4(EmojiAddCustomDialogUI emojiAddCustomDialogUI) {
this.ilg = emojiAddCustomDialogUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
this.ilg.finish();
}
}
|
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogicReminder {
//Objects
static LinkedList<ReminderTask> taskToBeReminded = new LinkedList<ReminderTask>();
private static LogicReminder logicReminderInstance;
//Variables
private final static String LOG_NAME = "Logic Reminder Logger";
private static boolean isInitiated = false;
// Logger: Use to troubleshoot problems
private static Logger logger = Logger.getLogger(LOG_NAME);
/**************************************************************************/
/**************************************************************************/
/************************** APIs ********************************/
/**************************************************************************/
/**************************************************************************/
//@author A0112898U
/**
* Constructor for Logic Reminder Singleton, should only have one instance!
* Impt note - Only generate reminder for daily task - Only add today's task!
*
* @param tasks The list of tasks to initiate the system with.
*/
private LogicReminder(LinkedList<Task> tasks) {
//Loop through all tasks & add only tasks with today's reminder date
for (Task t:tasks) {
if (checkIsTodayTask(t) && !isReminderOver(t)) {
ReminderTask rTask = new ReminderTask(t,
new Date(t.getReminder()));
taskToBeReminded.add(rTask);
}
}
//Acknowledges the initiation
isInitiated = true;
}
//@author A0112898U
/**
* API function to initiate the Logic Reminder System's Singleton
*
* @param tasks The list of tasks to initiate the system with.
* @throws ParseException
*/
public static void initiateSingleton (LinkedList<Task> tasks) {
//Initiated the Singleton only if not initiated
if (!isInitiated) {
logicReminderInstance = new LogicReminder(tasks);
}
}
//@author A0112898U
/**
* Getter to get the instance for this Singleton class.
*
* @return LogicReminder returns the Singleton's Instance
*/
public static LogicReminder getInstance() {
return logicReminderInstance;
}
//@author A0112898U
/**
* Accessor for reminder tasks list
*
* @return LinkedList The reminder tasks list
*/
static public LinkedList<ReminderTask> getList() {
return taskToBeReminded;
}
//@author A0112898U
/**
* Mutator for reminder tasks list
*/
static public void editList(LinkedList<ReminderTask> _taskToBeReminded) {
taskToBeReminded = _taskToBeReminded;
}
//@author A0112898U
/**
* API function to refresh the Reminder System List.
* To Implement - Logic should call this every 0000 the tasks
* to be reminded should be re-generated.
*
* @param tasks The list of tasks to refresh the system with.
*/
public void regenReminderList(LinkedList<Task> tasks) {
//Loop through all tasks & add only tasks with today's reminder date
for (Task t:tasks) {
//Checks for today's task and not over task then add task.
if (checkIsTodayTask(t) && !(isReminderOver(t))) {
//Create a reminder task and add to the list of reminders
ReminderTask rTask = new ReminderTask(t,
new Date(t.getReminder()));
//Schedule an alarm for this task.
rTask.scheduleAlarm();
//Add task to system's list.
taskToBeReminded.add(rTask);
assert(checkIsTodayTask(t) && !(isReminderOver(t))): "Not Today's task and is over! Assertion Error!";
}
}
}
//@author A0112898U
/**
* Add new tasks or Updates the old task with the new task, and
* re-schedules/schedules the new reminder
*
* @param newTask The new task that is to be changed to
* @param oldTask The old task task that is to be changed.
*/
public void updateTaskTobeReminded(Task newTask, Task oldTask) {
//Local Variable for 'updateTaskTobeReminded' function
boolean isTaskAdded = false;
boolean isTodayReminder = false;
//check if the reminder for the new task is today
if (checkIsTodayTask(newTask)) {
isTodayReminder = true;
}
//Search for the old task (if any).
for (ReminderTask tempRtask:taskToBeReminded) {
//Update task if task exists.
if (isTaskExist(tempRtask.getTask(), oldTask)) {
//Stops the previous scheduled alarm.
tempRtask.stopAlarm();
if (isTodayReminder && !isReminderOver(newTask)) {
//Edit and reschedule task.
tempRtask.editTask(newTask);
tempRtask.scheduleAlarm();
} else {
//Remove reminder if if not for today or over.
taskToBeReminded.remove(oldTask);
}
//To indicate that task was present in the list.
isTaskAdded = true;
//Break from the loop if task already found.
break;
}
}
//If task doesn't exist in the current list.
if (!isTaskAdded && isTodayReminder) {
//Add new task!
addTaskTobeReminded(newTask);
}
}
//@author A0112898U
/**
* API function that is to be called when new tasks are added to
* the Logic System buffered tasks list. This function will then
* check if the task's indicated reminder time and date is for
* today before adding into the Reminder System.
*
* @param newTask The newly added task.
*/
public void addTaskTobeReminded(Task newTask) {
if (checkIsTodayTask(newTask) && !isReminderOver(newTask)) {
//Creates a new ReminderTask Object with the new Task.
ReminderTask rTask = new ReminderTask(newTask,
new Date(newTask.getReminder()));
//Add the new ReminderTask to the Singleton's ReminderTask List.
taskToBeReminded.add(rTask);
//Schedules an alarm for this new task.
rTask.scheduleAlarm();
}
}
//A0112898U
/**
* API function that is to be called when new tasks are deleted from
* the Logic System buffered tasks list. This function will then
* stops the scheduled alarm for the input(deleted) task.
*
* @param taskToStop Task that alarm should be stop.
*/
public void stopTask(Task taskToStop) {
//Loop through all collated tasks
for (ReminderTask rTsk:taskToBeReminded) {
if (isTaskExist(rTsk.getTask(), taskToStop)) {
//Stop the scheduled alarm.
rTsk.stopAlarm();
//break out of loop if task found.
break;
}
}
}
//A0112898U
/**
* Getter method to get the collated ReminderTasks
*
* @return tempList Returns a newList popuplate with
* the collated tasks from the Singleton.
*/
public LinkedList<ReminderTask> getReminderList() {
LinkedList<ReminderTask> tempList =
new LinkedList<ReminderTask>(taskToBeReminded);
return tempList;
}
//@author A0111942N
/**
* API function that stops all the existing tasks from sounding off
*/
public void stopAllTasksReminder() {
for ( ReminderTask rt : taskToBeReminded ) {
rt.stopAlarm();
}
}
/**************************************************************************/
/**************************************************************************/
/*********************** PRIVATEs *******************************/
/**************************************************************************/
/**************************************************************************/
//@author A0112898U
/**
* Check if the reminder for the task is today's task.
*
* @param inTask The task to be passed in.
* @return boolean True if Reminder is for today, false if otherwise.
*/
private static boolean checkIsTodayTask(Task inTask) {
//Create java calendar instance to get today's date
Calendar c = Calendar.getInstance();
//Set all other possible time to 0, other then the day
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
//Objects to help compare the dates
Date date1 = null;
Date date2 = null;
Date today = c.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
//Format today's date and the task's reminder's date
try {
date1 = sdf.parse(sdf.format(inTask.getReminder()));
date2 = sdf.parse(sdf.format(today));
} catch (ParseException e) {
e.printStackTrace();
logger.log(Level.WARNING,
"LogicReminder - Unable to Parse the dates");
}
//Compare the dates, if same return true.
if (date1.getTime() == date2.getTime()) {
return true;
}
return false;
}
//@author A0112898U
/**
* Checks if task's reminder time is already over
*
* @param task The task to check with
* @return boolean True if reminder time indication is over, False otherwise.
*/
private boolean isReminderOver(Task task) {
//if reminder time is greater then current system time means not over
if (task.getReminder() >= System.currentTimeMillis()) {
return false;
}
return true;
}
//@author A0112898U
/**
* Checks if the task to be added is same as the existed task.
*
* @param existedTask The task to check with.
* @param newTask Task that is to be added to check if it exists.
* @return boolean True if task is same as existed Task, false otherwise.
*/
private boolean isTaskExist(Task existedTask, Task newTask) {
if (existedTask.getName().equals(newTask.getName())
&& existedTask.getDescription().equals(newTask.getDescription())
&& (existedTask.getTimeStamp() == newTask.getTimeStamp())
&& (existedTask.getLabel() == newTask.getLabel())
) {
return true;
}
return false;
}
}
|
package pl.whirly.recruitment.charge.model;
import java.math.BigDecimal;
public class ChargeOrder {
private String id;
private String userId;
private BigDecimal amountNet;
private String currency;
public ChargeOrder(String userId, BigDecimal amountNet, String currency) {
this.userId = userId;
this.amountNet = amountNet;
this.currency = currency;
}
public String getId() {
return id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public BigDecimal getAmountNet() {
return amountNet;
}
public void setAmountNet(BigDecimal amountNet) {
this.amountNet = amountNet;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
|
package data;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
//singleton class
public class Utilities {
private static Utilities utilities = new Utilities();
public static Utilities Instance() {
return utilities;
}
//default constructor
public Utilities() {}
public String LocalDateToString(LocalDate date, DateTimeFormatter dateFormat) {
if (date == null) {
return null;
}
String text = date.format(dateFormat);
return text;
}
public LocalDate StringToLocalDate (String date, DateTimeFormatter dateFormat) {
return LocalDate.parse(date, dateFormat);
}
public String MonthNumberToString(int month) {
return new DateFormatSymbols().getMonths()[month-1];
}
public int StringToMonthNumber(String month) {
Date date;
try {
date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse(month);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.MONTH);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
}
}
|
package com.stickyblob.chords.utils;
import android.content.Context;
import android.util.Log;
import com.stickyblob.chords.R;
import java.util.ArrayList;
/**
* Created by thisi on 5/24/2017.
*/
public class Utility {
private static final String TAG = "Utility";
public static ArrayList<Chord> convertStringsToChordObjects(ArrayList<String> mainStringArray, Context context) {
// Initialize new Chord Array
ArrayList<Chord> chordArrayList = new ArrayList<>();
// Initialize new string voice Array
ArrayList<Double> sopranoList;
ArrayList<Double> altoList;
ArrayList<Double> tenorList;
ArrayList<Double> bassList;
// Get the split strings of all the voices;
String[] soprano_notes = mainStringArray.get(0).split(" ");
String[] alto_notes = mainStringArray.get(1).split(" ");
String[] tenor_notes = mainStringArray.get(2).split(" ");
String[] bass_notes = mainStringArray.get(3).split(" ");
// Below is the logic used to decide which string is the longest one
// The reason we need to do that is so the player plays all the notes,
// and not just as many as the string that is tested for length
int s_size = soprano_notes.length;
int a_size = alto_notes.length;
int t_size = tenor_notes.length;
int b_size = bass_notes.length;
int[] integer_list = new int[]{s_size, a_size, t_size, b_size};
int largest = integer_list[0];
for (int i = 1; i < integer_list.length; i++) {
if (integer_list[i] > largest) {
largest = integer_list[i];
}
}
// Set the values of the voice arrays
sopranoList = stringIntoIntArray(soprano_notes, context);
altoList = stringIntoIntArray(alto_notes, context);
tenorList = stringIntoIntArray(tenor_notes, context);
bassList = stringIntoIntArray(bass_notes, context);
// Build up each chord
for (int i = 0; largest > i; i++) {
Chord chord = new Chord();
Double s_note;
Double a_note;
Double t_note;
Double b_note;
try {
s_note = sopranoList.get(i);
} catch (Exception e) {
s_note = 0.0;
}
try {
a_note = altoList.get(i);
} catch (Exception e) {
a_note = 0.0;
}
try {
t_note = tenorList.get(i);
} catch (Exception e) {
t_note = 0.0;
}
try {
b_note = bassList.get(i);
} catch (Exception e) {
b_note = 0.0;
}
chord.setSopranoNote(s_note);
chord.setAltoNote(a_note);
chord.setTenorNote(t_note);
chord.setBassNote(b_note);
chordArrayList.add(chord);
}
return chordArrayList;
}
// Private method used to convert the strings into the proper
// double frequency
private static ArrayList<Double> stringIntoIntArray(String[] string, Context context) {
ArrayList<Double> voiceArrList = new ArrayList<>();
Double noteToPlay;
for (String t : string) {
String noteStringUsedToDecideNote = t.toLowerCase();
switch (noteStringUsedToDecideNote) {
case "do":
noteToPlay = Double.parseDouble(context.getString(R.string.note_c5));
voiceArrList.add(noteToPlay);
break;
case "re":
noteToPlay = Double.parseDouble(context.getString(R.string.note_d5));
voiceArrList.add(noteToPlay);
break;
case "mi":
noteToPlay = Double.parseDouble(context.getString(R.string.note_e5));
voiceArrList.add(noteToPlay);
break;
case "fa":
noteToPlay = Double.parseDouble(context.getString(R.string.note_f5));
voiceArrList.add(noteToPlay);
break;
case "so":
noteToPlay = Double.parseDouble(context.getString(R.string.note_g5));
voiceArrList.add(noteToPlay);
break;
case "la":
noteToPlay = Double.parseDouble(context.getString(R.string.note_a5));
voiceArrList.add(noteToPlay);
break;
case "ti":
noteToPlay = Double.parseDouble(context.getString(R.string.note_b5));
voiceArrList.add(noteToPlay);
break;
default:
Log.e(TAG, "convertStringToIntArray: Unknown note");
}
}
return voiceArrList;
}
}
|
package com.cmu.edu.enterprisewebdevelopment.domain;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Data
@NoArgsConstructor
public class Tag {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String tagName;
private int count;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "tagId")
private List<User> userList;
public Tag(String tagName) {
this.userList = new ArrayList<>();
this.tagName = tagName;
}
@Override
public boolean equals(Object o) {
if (o instanceof Tag) {
return this.tagName.equals(((Tag) o).tagName);
}
return false;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.