text
stringlengths 10
2.72M
|
|---|
package com.zubiri.geometria;
/*
* Clase para obtener resultados de distintas operaciones aritméticas.
*/
public class Circulo {
private double radio;
//Método que calcula el area de un circulo.
public double area () {
double result = 0;
result = this.getRadio()*this.getRadio()* Math.PI;
return result;
}
//Metodo que calcula la circunferencia de un circulo.
public double circunferencia () {
double result = 0;
result = 2 * this.getRadio() * Math.PI ;
return result;
}
public double getRadio(){
return radio;
}
public void setRadio(double rad){
radio=rad;
}
}
|
package cn.edu.ncu.collegesecondhand.ui.my.login;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import cn.edu.ncu.collegesecondhand.R;
import cn.edu.ncu.collegesecondhand.util.MD5Util;
import es.dmoral.toasty.Toasty;
public class SignInActivity extends AppCompatActivity {
private EditText editText_account;
private EditText editText_password;
private EditText getEditText_password_confirm;
private Button button_signIn;
private void init() {
editText_account = findViewById(R.id.register_account);
editText_password = findViewById(R.id.register_password);
button_signIn = findViewById(R.id.register_button);
getEditText_password_confirm = findViewById(R.id.register_password_confirm);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
init();
final RequestQueue requestQueue = Volley.newRequestQueue(getBaseContext());
button_signIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String account = editText_account.getText().toString();
String originPassword = editText_password.getText().toString();
String originPasswordConfirm = getEditText_password_confirm.getText().toString();
String password;
//账号密码判空
if (account.length() < 6) {
Toasty.error(getBaseContext(), "账号不能少于6位,请重试!", Toast.LENGTH_SHORT).show();
return;
} else if (account.length() > 20) {
Toasty.error(getBaseContext(), "账号不能超过20位,请重试!", Toast.LENGTH_SHORT).show();
return;
}
//非法字符判断
if (isContainChinese(account)) {
Toasty.info(getBaseContext(), "包含中文字符,请重试!", Toast.LENGTH_SHORT).show();
return;
}
//密码判空
if (originPassword.length() < 6 && originPasswordConfirm.length() < 6) {
Toasty.error(getBaseContext(), "密码不能少于6位,请重试!", Toast.LENGTH_SHORT).show();
return;
}
if (!originPassword.equals(originPasswordConfirm)) {
Toasty.error(getBaseContext(), "两次输入密码不一致,请重试!", Toast.LENGTH_SHORT).show();
return;
}
//非法字符判断
if (isContainChinese(originPassword)) {
Toasty.info(getBaseContext(), "密码包含中文字符,请重试!", Toast.LENGTH_SHORT).show();
return;
}
//将明文密码转换成MD5字符串;
password = MD5Util.toMD5(originPassword);
String url = getResources().getString(R.string.ip_address) + "/user/signIn?account=" + account
+ "&password=" + password;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
if (response.contains("0")) {
//注册成功,返回登录界面,给出提示
Toasty.success(getBaseContext(),
"恭喜注册成功!", Toast.LENGTH_LONG).show();
// Log.d("register: ", "success");
finish();
} else if (response.contains("1")) {
Toasty.error(getBaseContext(),
"该用户未已存在,\n请直接登录或者重新注册新用户!", Toast.LENGTH_SHORT).show();
// Log.d("register: ", "Already existed!");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toasty.error(getBaseContext(), "网络连接错误,请稍后重试!:\n" +
error.toString(), Toast.LENGTH_SHORT).show();
// Log.d("register: ", "网络连接错误:" + error.toString());
}
});
requestQueue.add(stringRequest);
}
});
}
//Chinese chars;
public static boolean isContainChinese(String str) {
Pattern p = Pattern.compile("[\u4E00-\u9FA5|\\!|\\,|\\。|\\(|\\)|\\《|\\》|\\“|\\”|\\?|\\:|\\;|\\【|\\】]");
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
}
|
package xdroid.adapter;
import android.view.View;
public interface IAdapter<D, V extends View> {
void setBinder(ViewBinder<D, V> binder);
void setViewTypeResolver(ViewTypeResolver<D> viewTypeResolver);
void setLayoutId(int layoutId);
void putLayoutId(int viewType, int layoutId);
}
|
package com.pykj.design.principle.dependenceinversion.example;
/**
* @description: TODO
* @author: zhangpengxiang
* @time: 2020/4/19 19:49
*/
public class Tom {
public void studyJavaCourse() {
System.out.println("Tom 在学习Java的课程");
}
public void studyPythonCourse() {
System.out.println("Tom 在学习Python的课程");
}
}
|
package com.awstechguide.cms.springjpah2.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.awstechguide.cms.springjpah2.entity.Role;
public interface RoleRepository extends JpaRepository<Role, Integer>{
Role findByRoleName(String name);
Role findByRoleCd(String role);
}
|
package lyrth.makanism.bot.commands.owner;
import discord4j.core.object.entity.channel.MessageChannel;
import lyrth.makanism.api.BotCommand;
import lyrth.makanism.api.GuildModule;
import lyrth.makanism.api.annotation.CommandInfo;
import lyrth.makanism.api.object.AccessLevel;
import lyrth.makanism.api.object.CommandCtx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ServiceLoader;
import java.util.stream.Stream;
@CommandInfo(
accessLevel = AccessLevel.OWNER,
desc = "Prints out visible modules.",
aliases = {"loadedmodules"}
)
public class Loaded extends BotCommand {
private static final Logger log = LoggerFactory.getLogger(Loaded.class);
@Override
public Mono<?> execute(CommandCtx ctx) {
return ctx.getChannel().flatMap(MessageChannel::type).then(Mono.fromCallable(() -> {
//URLClassLoader loader = new URLClassLoader(new URL[0]);
File[] jars = new File("hotmodules/").listFiles(s -> s.getName().endsWith(".jar"));
for (File f : jars) {
URLClassLoader loader = new URLClassLoader(new URL[]{ f.toURI().toURL() });
Stream<GuildModule> modules = ServiceLoader.load(GuildModule.class, loader).stream().map(m->m.get()).filter(m->m.getClass().getClassLoader().equals(loader));
modules.forEach(m -> log.info("Seen class: {}", m.getName()));
loader.close();
//loader = null;
//finder = null;
//classes.removeIf(a -> true);
//classes = null;
}
//jars = null;
return "Doniea";
}))
.flatMap(ctx::sendReply);
}
}
|
package com.examples.mockito;
public class MyClass {
private int uniqueId;
private String thisString;
int getUniqueId() {
return uniqueId;
}
void setUniqueId(int uniqueId) {
this.uniqueId = uniqueId;
}
void testing(int uniqueId) {
this.uniqueId = uniqueId;
}
void someMethod(String str) {
this.thisString = thisString;
}
}
|
package com.eshop.exception;
public class NoProductInBasketException extends RuntimeException {
}
|
package pl.dopiatku.byle.api;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class FrydayApplicationTests {
@Test
void contextLoads() {
}
}
|
package state;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;
/**
* @author douglas
* @create 2021-03-03 23:01
*/
public class Flink01_State_Operator_3 {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(3);
DataStreamSource<String> dataStream = env.socketTextStream("hadoop102", 9999);
DataStreamSource<String> controlStream = env.socketTextStream("hadoop102", 8888);
MapStateDescriptor<String, String> stateDescriptor = new MapStateDescriptor<>("state", String.class, String.class);
//广播流
BroadcastStream<String> broadcastStream = controlStream.broadcast(stateDescriptor);
dataStream
.connect(broadcastStream)
.process(new BroadcastProcessFunction<String, String, String>() {
@Override
public void processElement(String value, ReadOnlyContext ctx, Collector<String> out) throws Exception {
//从广播状态中取值,不同的制作不同的业务
ReadOnlyBroadcastState<String, String> state = ctx.getBroadcastState(stateDescriptor);
if("1".equals(state.get("switch"))){
out.collect("切换到1号配置" );
}else if("0".equals(state.get("switch"))){
out.collect("切换到0号配置");
}else {
out.collect("切换到其他配置");
}
}
@Override
public void processBroadcastElement(String value, Context ctx, Collector<String> out) throws Exception {
BroadcastState<String, String> state = ctx.getBroadcastState(stateDescriptor);
//把值放入广播状态
state.put("switch",value);
}
})
.print();
env.execute();
}
}
|
package com.giladkz.verticalEnsemble.Operators.UnaryOperators;
import com.giladkz.verticalEnsemble.Data.ColumnInfo;
import com.giladkz.verticalEnsemble.Data.Dataset;
import com.giladkz.verticalEnsemble.Operators.Operator;
import java.util.List;
/**
* Created by giladkatz on 20/02/2016.
*/
public abstract class UnaryOperator extends Operator {
public boolean isApplicable(Dataset dataset, List<ColumnInfo> sourceColumns, List<ColumnInfo> targetColumns) {
//if there are any target columns or if there is more than one source column, return false
if (sourceColumns.size() != 1 || (targetColumns != null && targetColumns.size() != 0)) {
return false;
}
else {
return true;
}
}
public Operator.operatorType getType() {
return Operator.operatorType.Unary;
}
public abstract Operator.outputType requiredInputType();
public abstract int getNumOfBins();
}
|
package com.esum.backup.vo;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
/**
* Copyright(c) eSum Technologies., Inc. All rights reserved.
*/
public class IgnoreCaseMap extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 347848922148419058L;
@Override
public Object put(String key, Object value) {
return super.put(convertKey(key), value);
}
@Override
public void putAll(Map<? extends String, ? extends Object> map) {
if (map.isEmpty()) {
return;
}
for (Map.Entry<? extends String, ? extends Object> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public boolean containsKey(Object key) {
return (key instanceof String && super.containsKey(convertKey((String) key)));
}
@Override
public Object get(Object key) {
if (key instanceof String) {
return super.get(convertKey((String) key));
}
else {
return null;
}
}
@Override
public Object remove(Object key) {
if (key instanceof String) {
return super.remove(convertKey((String) key));
}
else {
return null;
}
}
public String getString(String key) {
Object obj = get(key);
if (obj != null) {
return String.valueOf(obj);
} else {
return "";
}
}
public String getString(String key, String defaultValue) {
String value = getString(key);
return StringUtils.isEmpty(value)?defaultValue:value;
}
public int getInteger(String key) {
return getInteger(key, 0);
}
public int getInteger(String key, int defaultValue) {
Object value = get(key);
if (value == null) {
return defaultValue;
} else {
return Integer.parseInt(String.valueOf(value).trim());
}
}
public long getLong(String key) {
return getLong(key, 0);
}
public long getLong(String key, long defaultValue) {
Object value = get(key);
if (value == null) {
return defaultValue;
} else {
return Long.parseLong(String.valueOf(value).trim());
}
}
protected String convertKey(String key) {
return key.toLowerCase();
}
}
|
package com.fearefull.dotaanalyser;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
/**
* Created by A.Hosseini on 2016-09-06.
*/
public class TabFragmentDetailOverview extends Fragment {
DetailMatchActivity myDetailActivity;
boolean isSetData = false;
boolean isCreate = true;
ImageView loading_image;
ScrollView scrollView;
Animation loading_animation;
View my_overview_view;
LayoutInflater inflater;
LinearLayout no_connection_layout;
Button no_connection_button;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myDetailActivity = (DetailMatchActivity) getActivity();
my_overview_view = inflater.inflate(R.layout.detail_match_tab_overview, container, false);
this.inflater = inflater;
no_connection_layout = (LinearLayout) my_overview_view.findViewById(R.id.no_connection_layout);
no_connection_button = (Button) my_overview_view.findViewById(R.id.no_connection_button);
no_connection_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myDetailActivity.refreshFunction();
}
});
scrollView = (ScrollView) my_overview_view.findViewById(R.id.scrollView);
loading_image = (ImageView) my_overview_view.findViewById(R.id.loading_image);
loading_animation = AnimationUtils.loadAnimation(myDetailActivity.getBaseContext(), R.anim.rotate_loading);
loading_image.startAnimation(loading_animation);
return my_overview_view;
}
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isCreate && isVisibleToUser) {
setHandlerData();
isCreate = false;
}
}
public void setRefresh() {
if (!isCreate) {
scrollView.setVisibility(View.GONE);
no_connection_layout.setVisibility(View.GONE);
loading_image.startAnimation(loading_animation);
loading_image.setVisibility(View.VISIBLE);
isSetData = false;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
setHandlerData();
}
}, 500);
}
}
public void setData() throws JSONException {
loading_image.clearAnimation();
loading_image.setVisibility(View.GONE);
scrollView.setVisibility(View.VISIBLE);
isSetData = true;
TextView result_match_game = (TextView) my_overview_view.findViewById(R.id.resultMatchDetail);
TextView game_mode_game = (TextView) my_overview_view.findViewById(R.id.gameModeDetail);
TextView lobby_type_game = (TextView) my_overview_view.findViewById(R.id.lobbyTypeDetail);
TextView region_game = (TextView) my_overview_view.findViewById(R.id.regionDetail);
TextView start_time_game = (TextView) my_overview_view.findViewById(R.id.startTimeDetail);
TextView duration_game = (TextView) my_overview_view.findViewById(R.id.durationDetail);
game_mode_game.setText(myDetailActivity.game_mode);
lobby_type_game.setText(myDetailActivity.lobby_type);
region_game.setText(myDetailActivity.region);
start_time_game.setText(myDetailActivity.start_time);
duration_game.setText(myDetailActivity.duration);
if (myDetailActivity.radiant_win == 1) {
result_match_game.setText("RADIANT VICTORY");
result_match_game.setTextColor(getResources().getColor(R.color.colorWin));
}
else {
result_match_game.setText("DIRE VICTORY");
result_match_game.setTextColor(getResources().getColor(R.color.colorLose));
}
LinearLayout tableOverviewRadiantLayout = (LinearLayout) my_overview_view.findViewById(R.id.tableOverviewRadiantLayout);
LinearLayout tableOverviewDireLayout = (LinearLayout) my_overview_view.findViewById(R.id.tableOverviewDireLayout);
String hero_image_url;
for (int i = 0; i < 5; i++) {
try {
View player_row = inflater.inflate(R.layout.layout_overview_row, tableOverviewRadiantLayout, false);
ImageView hero_image_player = (ImageView) player_row.findViewById(R.id.hero_image_player);
TextView person_name_player = (TextView) player_row.findViewById(R.id.person_name_player);
TextView level_player = (TextView) player_row.findViewById(R.id.level_player);
TextView kills_player = (TextView) player_row.findViewById(R.id.kills_player);
TextView deaths_player = (TextView) player_row.findViewById(R.id.deaths_player);
TextView assists_player = (TextView) player_row.findViewById(R.id.assists_player);
TextView kda_player = (TextView) player_row.findViewById(R.id.kda_player);
person_name_player.setText(myDetailActivity.players.getJSONObject(i).getString("person_name"));
level_player.setText(myDetailActivity.players.getJSONObject(i).getString("level"));
kills_player.setText(myDetailActivity.players.getJSONObject(i).getString("kills"));
deaths_player.setText(myDetailActivity.players.getJSONObject(i).getString("deaths"));
assists_player.setText(myDetailActivity.players.getJSONObject(i).getString("assists"));
kda_player.setText(myDetailActivity.players.getJSONObject(i).getString("kda"));
String hero_name = myDetailActivity.players.getJSONObject(i).getString("hero_name").replace("npc_dota_hero_", "");
hero_image_url = "http://cdn.dota2.com/apps/dota2/images/heroes/" + hero_name + "_lg.png";
Picasso.with(myDetailActivity.getApplicationContext()).load(hero_image_url).into(hero_image_player);
tableOverviewRadiantLayout.addView(player_row);
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
View team_row = inflater.inflate(R.layout.layout_overview_total_row, tableOverviewRadiantLayout, false);
TextView level_team = (TextView) team_row.findViewById(R.id.level_team);
TextView kills_team = (TextView) team_row.findViewById(R.id.kills_team);
TextView deaths_team = (TextView) team_row.findViewById(R.id.deaths_team);
TextView assists_team = (TextView) team_row.findViewById(R.id.assists_team);
TextView kda_team= (TextView) team_row.findViewById(R.id.kda_team);
level_team.setText(myDetailActivity.resultJson.getString("radiant_level"));
kills_team.setText(myDetailActivity.resultJson.getString("radiant_kills"));
deaths_team.setText(myDetailActivity.resultJson.getString("radiant_deaths"));
assists_team.setText(myDetailActivity.resultJson.getString("radiant_assists"));
kda_team.setText(myDetailActivity.resultJson.getString("radiant_kda"));
tableOverviewRadiantLayout.addView(team_row);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 5; i < 10; i++) {
try {
View player_row = inflater.inflate(R.layout.layout_overview_row, tableOverviewDireLayout, false);
ImageView hero_image_player = (ImageView) player_row.findViewById(R.id.hero_image_player);
TextView person_name_player = (TextView) player_row.findViewById(R.id.person_name_player);
TextView level_player = (TextView) player_row.findViewById(R.id.level_player);
TextView kills_player = (TextView) player_row.findViewById(R.id.kills_player);
TextView deaths_player = (TextView) player_row.findViewById(R.id.deaths_player);
TextView assists_player = (TextView) player_row.findViewById(R.id.assists_player);
TextView kda_player = (TextView) player_row.findViewById(R.id.kda_player);
person_name_player.setText(myDetailActivity.players.getJSONObject(i).getString("person_name"));
level_player.setText(myDetailActivity.players.getJSONObject(i).getString("level"));
kills_player.setText(myDetailActivity.players.getJSONObject(i).getString("kills"));
deaths_player.setText(myDetailActivity.players.getJSONObject(i).getString("deaths"));
assists_player.setText(myDetailActivity.players.getJSONObject(i).getString("assists"));
kda_player.setText(myDetailActivity.players.getJSONObject(i).getString("kda"));
String hero_name = myDetailActivity.players.getJSONObject(i).getString("hero_name").replace("npc_dota_hero_", "");
hero_image_url = "http://cdn.dota2.com/apps/dota2/images/heroes/" + hero_name + "_lg.png";
Picasso.with(myDetailActivity.getApplicationContext()).load(hero_image_url).into(hero_image_player);
tableOverviewDireLayout.addView(player_row);
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
View team_row = inflater.inflate(R.layout.layout_overview_total_row, tableOverviewDireLayout, false);
TextView level_team = (TextView) team_row.findViewById(R.id.level_team);
TextView kills_team = (TextView) team_row.findViewById(R.id.kills_team);
TextView deaths_team = (TextView) team_row.findViewById(R.id.deaths_team);
TextView assists_team = (TextView) team_row.findViewById(R.id.assists_team);
TextView kda_team= (TextView) team_row.findViewById(R.id.kda_team);
level_team.setText(myDetailActivity.resultJson.getString("dire_level"));
kills_team.setText(myDetailActivity.resultJson.getString("dire_kills"));
deaths_team.setText(myDetailActivity.resultJson.getString("dire_deaths"));
assists_team.setText(myDetailActivity.resultJson.getString("dire_assists"));
kda_team.setText(myDetailActivity.resultJson.getString("dire_kda"));
tableOverviewDireLayout.addView(team_row);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void setNetworkError() {
scrollView.setVisibility(View.GONE);
loading_image.clearAnimation();
loading_image.setVisibility(View.GONE);
no_connection_layout.setVisibility(View.VISIBLE);
isSetData = false;
}
public void setHandlerData() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (myDetailActivity.isReceivingData) {
if (myDetailActivity.isNetworkError) { setNetworkError(); }
else {
if (! isSetData) {
try {
setData();
} catch (JSONException e) {
e.printStackTrace();
setNetworkError();
}
}
}
}
else {
setHandlerData();
}
}
}, 200);
}
}
|
package com.cs.administration.player;
import com.cs.persistence.Country;
import com.cs.player.Address;
import com.cs.player.BasicAddressDto;
import org.hibernate.validator.constraints.NotEmpty;
import javax.annotation.Nonnull;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import static javax.xml.bind.annotation.XmlAccessType.FIELD;
/**
* @author Joakim Gottzén
*/
@XmlRootElement
@XmlAccessorType(FIELD)
public class BackOfficeAddressDto extends BasicAddressDto {
@XmlElement
@Nonnull
@NotEmpty
private Country country;
@SuppressWarnings("UnusedDeclaration")
public BackOfficeAddressDto() {
}
public BackOfficeAddressDto(final Address address) {
super(address);
country = address.getCountry();
}
@Override
protected Address asAddress() {
final Address address = super.asAddress();
address.setCountry(country);
return address;
}
}
|
package org.yxm.modules.ting;
import org.yxm.modules.ting.entity.ting.SongBillListEntity;
public interface IMusicView {
void onInitMusicListSuccess(SongBillListEntity songBillListEntity);
}
|
package com.citibank.ods.entity.pl;
import com.citibank.ods.common.entity.BaseODSEntity;
import com.citibank.ods.entity.pl.valueobject.BaseTbgOfficerEntityVO;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* [Class description]
*
*@see package com.citibank.ods.entity.pl;
*@version 1.0
*@author gerson.a.rodrigues,Mar 26, 2007
*
*<PRE>
*<U>Updated by:</U>
*<U>Description:</U>
*</PRE>
*/
public class BaseTbgOfficerEntity extends BaseODSEntity
{
protected BaseTbgOfficerEntityVO m_data;
public static final String C_OFFCR_CAT_CODE_INTERNAL = "Interna";
public static final String C_OFFCR_CAT_CODE_EXTERNAL = "Externa";
public static final String C_OFFCR_CAT_CODE_TELEMARK = "Telemark";
public static final String C_OFFCR_STAT_CODE_INCLUDED = "Incluído";
public static final String C_OFFCR_STAT_CODE_ACTIVE = "Ativo";
public static final int C_OFFCR_NBR_SRC_SIZE = 6;
public static final int C_OFFCR_NAME_TEXT_SRC_SIZE = 40;
public static final int C_OFFCR_REAL_NBR_SRC_SIZE = 6;
public static final String C_OFFCR_NAME_TEXT = "OFFCR_NAME_TEXT";
public BaseTbgOfficerEntityVO getData()
{
return m_data;
}
}
|
/**
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
*/
class Solution {
public int leastInterval(char[] tasks, int n) {
HashMap<Character, Integer> map = new HashMap<>();
for(char c : tasks){
map.put(c, map.getOrDefault(c,0) + 1);
}
//use priority queue to sort frequency
PriorityQueue<Integer> queue = new PriorityQueue<>((a,b) -> b - a);
queue.addAll(map.values());
//arrage tasks
int cycle = 0;
while(!queue.isEmpty()){
List<Integer> temp = new ArrayList<Integer>();//store each valid groups
for(int i = 0; i <= n; i++){
if(!queue.isEmpty()){
temp.add(queue.remove());
}
}
// 3,3 -> 2 2 -> 1 1
for(int i : temp){
if(--i > 0){
queue.add(i);
}
}
cycle += queue.isEmpty() ? temp.size() : n + 1;
}
return cycle;
}
}
|
package br.com.mixfiscal.prodspedxnfe.gui.backbean;
import br.com.mixfiscal.prodspedxnfe.gui.util.Constantes;
import br.com.mixfiscal.prodspedxnfe.gui.util.Utils;
import br.com.mixfiscal.prodspedxnfe.services.relatorio.ImportarExcelParaAtualizarBase;
import br.com.mixfiscal.prodspedxnfe.services.relatorio.RelatorioDebitoCredito;
import br.com.mixfiscal.prodspedxnfe.services.relatorio.RelatorioDebitoCredito.Fornecedor;
import br.com.mixfiscal.prodspedxnfe.services.relatorio.Relatorio;
import java.math.BigDecimal;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
@ManagedBean(name = "relCredDebBackBean")
@SessionScoped
public class RelatorioCreditoDebitoBackBean {
// <editor-fold desc="Membros Privados" defaultstate="collapsed">
@ManagedProperty(value = "#{indexBackBean}")
private IndexBackBean indexBackBean;
private HtmlInputText tfCaminhoArquivoSPED;
private HtmlInputText tfCaminhoDirXMLsNFes;
private HtmlInputText tfCaminhoDirXMLsNFCes;
private HtmlInputText tfCaminhoDirXMLsCFes;
private HtmlInputText tfCaminhoExel;
private TipoRelatorio tipoRelatorio;
private String mensagem;
private List<Fornecedor> relatorio;
private List<Relatorio> listaRelatorio;
private int qtdItem;
private BigDecimal valorTotalCreditoIndevido;
private BigDecimal valorTotalCreditoAproveitar;
private BigDecimal totalDebitoindevido;
private BigDecimal totalDebitoNaoDeclarado;
private boolean ckeckUpdate;
private RelatorioDebitoCredito relatorioDebitoCredito;
private ImportarExcelParaAtualizarBase importarExelParaAtualizarBase;
// </editor-fold>
@PostConstruct
public void init() {
this.relatorioDebitoCredito = new RelatorioDebitoCredito();
this.setImportarExelParaAtualizarBase(new ImportarExcelParaAtualizarBase());
}
public IndexBackBean getIndexBackBean() {
return indexBackBean;
}
public void setIndexBackBean(IndexBackBean indexBackBean) {
this.indexBackBean = indexBackBean;
}
public HtmlInputText getTfCaminhoArquivoSPED(){
return tfCaminhoArquivoSPED;
}
public void setTfCaminhoArquivoSPED(HtmlInputText tfCaminhoArquivoSPED) {
this.tfCaminhoArquivoSPED = tfCaminhoArquivoSPED;
}
public HtmlInputText getTfCaminhoDirXMLsNFes() {
return tfCaminhoDirXMLsNFes;
}
public void setTfCaminhoDirXMLsNFes(HtmlInputText tfCaminhoDirXMLsNFes) {
this.tfCaminhoDirXMLsNFes = tfCaminhoDirXMLsNFes;
}
public HtmlInputText getTfCaminhoDirXMLsNFCes() {
return tfCaminhoDirXMLsNFCes;
}
public void setTfCaminhoDirXMLsNFCes(HtmlInputText tfCaminhoDirXMLsNFCes) {
this.tfCaminhoDirXMLsNFCes = tfCaminhoDirXMLsNFCes;
}
public HtmlInputText getTfCaminhoDirXMLsCFes() {
return tfCaminhoDirXMLsCFes;
}
public void setTfCaminhoDirXMLsCFes(HtmlInputText tfCaminhoDirXMLsCFes) {
this.tfCaminhoDirXMLsCFes = tfCaminhoDirXMLsCFes;
}
public String getCaminhoExel(){
return this.indexBackBean.getCaminhoExel();
}
public void setCaminhoExel (String caminhoExel){
this.indexBackBean.setCaminhoExel(caminhoExel);
}
public String getCaminhoArquivoSPED() {
return this.indexBackBean.getCaminhoArquivoSPED();
}
public void setCaminhoArquivoSPED(String caminhoArquivoSPED) {
this.indexBackBean.setCaminhoArquivoSPED(caminhoArquivoSPED);
}
public String getCaminhoDirXMLsNFes() {
return this.indexBackBean.getCaminhoDirXMLsNFes();
}
public void setCaminhoDirXMLsNFes(String caminhoDirXMLsNFes) {
this.indexBackBean.setCaminhoDirXMLsNFes(caminhoDirXMLsNFes);
}
public void setCaminhoDirXMLsNFCe(String caminhoDirXMLsNFCes){
this.indexBackBean.setCaminhoDirXMLsNFCes(caminhoDirXMLsNFCes);
}
public String getCaminhoDirXMLsNFCe(){
return this.indexBackBean.getCaminhoDirXMLsNFCes();
}
public void setCaminhoDirXmlsCFes(String caminhoDirXMLsCFes){
this.indexBackBean.setCaminhoDirXMLsCFes(caminhoDirXMLsCFes);
}
public String getCaminhoDirXmlsCFes(){
return this.indexBackBean.getCaminhoDirXMLsCFes();
}
public TipoRelatorio getTipoRelatorio() {
return tipoRelatorio;
}
public void setTipoRelatorio(TipoRelatorio tipoRelatorio) {
this.tipoRelatorio = tipoRelatorio;
}
public String getMensagem() {
return mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
public List<Fornecedor> getRelatorio() {
return relatorio;
}
public void setRelatorio(List<Fornecedor> relatorio) {
this.relatorio = relatorio;
}
public List<Relatorio> getRelatorioGeral() {
return listaRelatorio;
}
public void setRelatorioGeral(List<Relatorio> relatorio) {
this.listaRelatorio = relatorio;
}
public int getQtdItem() {
return qtdItem;
}
public void setQtdItem(int qtdItem) {
this.qtdItem = qtdItem;
}
public BigDecimal getValorTotalCreditoIndevido() {
return valorTotalCreditoIndevido;
}
public void setValorTotalCreditoIndevido(BigDecimal valorTotalCreditoIndevido) {
this.valorTotalCreditoIndevido = valorTotalCreditoIndevido;
}
public BigDecimal getValorTotalCreditoAproveitar() {
return valorTotalCreditoAproveitar;
}
public void setValorTotalCreditoAproveitar(BigDecimal valorTotalCreditoAproveitar) {
this.valorTotalCreditoAproveitar = valorTotalCreditoAproveitar;
}
public BigDecimal getTotalDebitoindevido() {
return totalDebitoindevido;
}
public void setTotalDebitoindevido(BigDecimal totalDebitoindevido) {
this.totalDebitoindevido = totalDebitoindevido;
}
public BigDecimal getTotalDebitoNaoDeclarado() {
return totalDebitoNaoDeclarado;
}
public void setTotalDebitoNaoDeclarado(BigDecimal totalDebitoNaoDeclarado) {
this.totalDebitoNaoDeclarado = totalDebitoNaoDeclarado;
}
public boolean isCkeckUpdate() {
return ckeckUpdate;
}
public void setCkeckUpdate(boolean ckeckUpdate) {
this.ckeckUpdate = ckeckUpdate;
}
public RelatorioDebitoCredito getRelatorioDebitoCredito() {
return relatorioDebitoCredito;
}
public void setRelatorioDebitoCredito(RelatorioDebitoCredito relatorioDebitoCredito) {
this.relatorioDebitoCredito = relatorioDebitoCredito;
}
/**
* @return the tfCaminhoExel
*/
public HtmlInputText getTfCaminhoExel() {
return tfCaminhoExel;
}
/**
* @param tfCaminhoExel the tfCaminhoExel to set
*/
public void setTfCaminhoExel(HtmlInputText tfCaminhoExel) {
this.tfCaminhoExel = tfCaminhoExel;
}
/**
* @return the importarExelParaAtualizarBase
*/
public ImportarExcelParaAtualizarBase getImportarExelParaAtualizarBase() {
return importarExelParaAtualizarBase;
}
/**
* @param importarExelParaAtualizarBase the importarExelParaAtualizarBase to set
*/
public void setImportarExelParaAtualizarBase(ImportarExcelParaAtualizarBase importarExelParaAtualizarBase) {
this.importarExelParaAtualizarBase = importarExelParaAtualizarBase;
}
// <editor-fold desc="Métodos Públicos" defaultstate="collapsed">
// public void btGerarRelatorio() {
//
// if (StringUtil.isNullOrEmpty(this.indexBackBean.getCaminhoArquivoSPED())) {
// this.mensagem = "Por favor, informe o caminho do arquivo SPED Modificado";
// return;
// }
// try {
// RelatorioDebitoCredito rel = new RelatorioDebitoCredito();
// rel.setCaminhoArquivoSped(Utils.retornarCaminhoServidor(this.getCaminhoArquivoSPED()));
// if(this.tipoRelatorio == TipoRelatorio.DivergenciaEntrada){
// this.mensagem ="Gerando relatório de Divengencia de Entrada, aguarde...";
// this.setValorTotalCreditoIndevido(rel.getValorTotalCreditoIndevido());
// this.setValorTotalCreditoAproveitar(rel.getValorTotalCreditonaoAproveitado());
// this.mensagem ="relatório finalizado";
// }
// if(this.tipoRelatorio == TipoRelatorio.DivergenciaSaida){
//
// rel.setCaminhoDirXMLsNFes(Utils.retornarCaminhoServidor(this.getCaminhoDirXMLsNFes()));
// rel.setCaminhoDirXMLsNFCes(Utils.retornarCaminhoServidor(this.getCaminhoDirXMLsNFCe()));
// rel.setCaminhoDirXMLsCFes(Utils.retornarCaminhoServidor(this.getCaminhoDirXmlsCFes()));
// if(this.isCkeckUpdate()){
// this.btnGerarListaWs();
// }
// this.setTotalDebitoNaoDeclarado(rel.getTotalDebitoNaoDeclarado());
// this.setTotalDebitoindevido(rel.getTotalDebitoIndevido());
// this.mensagem ="relatório finalizado";
// }
// } catch(Exception ex) {
// this.mensagem = "Houve um erro na geração do Relatório. Mensagem: " + ex.getMessage();
// System.err.println(ex);
// }
// }
public void btnGerarListaWs(){
RelatorioDebitoCredito rel = new RelatorioDebitoCredito();
try{
rel.setCaminhoArquivoSped(Utils.retornarCaminhoServidor(this.getCaminhoArquivoSPED()));
rel.atualizarTributacaoMix();
}catch(Exception ex){
this.mensagem = "Houve um erro na geração do Relatório. Mensagem: " + ex.getMessage();
//System.err.println(ex);
}
}
private void somarValorRelatorio(){
// for(RelatorioGeral rl: this.relatorioGeral){
// this.valorTotalCreditoAproveitar.add(rl.getValorCreditoNaoAproveitado());
// this.valorTotalCreditoIndevido.add(rl.getValorCreditoIndevido());
// }
}
public TipoRelatorio[] retornarTiposRelatorio() {
return TipoRelatorio.values();
}
public void exportarParaCsv(){
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
StringBuilder sbCsv = new StringBuilder();
List<RelatorioDebitoCredito> lista = (List<RelatorioDebitoCredito>)request.getSession().getAttribute(Constantes.SESSION_LISTA_REL_CFOP_FILTRADA);
//RelatorioCFOPWS.CarregarSPEDRetorno header = (RelatorioCFOPWS.CarregarSPEDRetorno)request.getSession().getAttribute(Constantes.SESSION_LEITOR_SPD);
}
// </editor-fold>
// <editor-fold desc="Enum TipoRelatorio" defaultstate="collapsed">
public enum TipoRelatorio {
DivergenciaEntrada("Divergencia Entrada"),
DivergenciaSaida("Divergencia Saida");
private String nome;
private TipoRelatorio(String nome) {
this.nome = nome;
}
public String getNome() {
return this.nome;
}
}
// </editor-fold>
}
|
package cat_tests.trash;
import cat_tests.model.SectionData;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class MongoTest {
public static void main(String[] args) {
MongoClient mongo = new MongoClient("cm-mongo01x-t.test.cardsmobile.ru", 27017);
MongoCollection<Document> sectionsCollection =
mongo.getDatabase("gogol").getCollection("market_section");
Document section = sectionsCollection.find(Filters.eq("name", "Транспорт")).first();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
String json = gson.toJson(section);
System.out.println(json);
/**
* {
* "_id": {},
* "_class": "ru.cardsmobile.market.entity.Section",
* "uid": "transport",
* "priority": 8,
* "name": "?????????",
* "hidden": false,
* "segments": []
* }
*/
SectionData jsonSection = gson.fromJson(json, SectionData.class);
System.out.println(jsonSection); // SectionData{title='null'}
String sectionUid = jsonSection.getUid();
System.out.println(sectionUid); // transport
}
public static void saveAsJson(List<SectionData> section, File file) throws IOException {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
String json = gson.toJson(section);
Writer writer = new FileWriter(file);
writer.write(json);
writer.close();
}
}
|
package com.ibisek.outlanded.components;
import android.view.View;
public abstract class LayoutableDialogFragmentController {
protected LayoutableDialogFragment dialog;
/**
* @param dialog
*/
public void init(LayoutableDialogFragment dialog) {
this.dialog = dialog;
}
/**
* @param view
*/
public abstract void onCreateView(View view);
}
|
<<<<<<< HEAD
package com.example.sieunhan.github_client.api;
=======
package com.example.sieunhan.github_client.api;
>>>>>>> rebuilt-version
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
<<<<<<< HEAD
/**
* Created by dannyle on 03/12/2016.
*/
public abstract class PageIterator<V> implements Iterator<Collection<V>> {
private final int itemsPerPage;
private int nextPage;
=======
public abstract class PageIterator<V> implements Iterator<Collection<V>> {
private final int itemsPerPage;
private int nextPage;
>>>>>>> rebuilt-version
public PageIterator(int initialPage, int itemsPerPage) {
this.itemsPerPage = itemsPerPage;
this.nextPage = initialPage;
}
<<<<<<< HEAD
=======
>>>>>>> rebuilt-version
@Override
public boolean hasNext() {
return this.nextPage != -1;
}
<<<<<<< HEAD
=======
>>>>>>> rebuilt-version
@Override
public Collection<V> next() {
if (!this.hasNext()) {
throw new NoSuchElementException();
}
<<<<<<< HEAD
Collection<V> resources = getPage(nextPage, itemsPerPage);
=======
Collection<V> resources = getPage(nextPage, itemsPerPage);
>>>>>>> rebuilt-version
if (resources.size() == 0) {
nextPage = -1;
} else {
++nextPage;
}
<<<<<<< HEAD
return resources;
}
=======
return resources;
}
>>>>>>> rebuilt-version
@Override
public void remove() {
throw new UnsupportedOperationException("Remove not supported");
}
<<<<<<< HEAD
protected abstract Collection<V> getPage(int page, int itemsPerPage);
}
=======
protected abstract Collection<V> getPage(int page, int itemsPerPage);
}
>>>>>>> rebuilt-version
|
/* RepeatableReader.java
Purpose:
Description:
History:
Fri Mar 14 11:47:38 2008, Created by tomyeh
Copyright (C) 2008 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.io;
import java.io.Reader;
import java.io.StringReader;
import java.io.CharArrayReader;
import java.io.Writer;
import java.io.StringWriter;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.net.URL;
import org.zkoss.lang.Library;
import org.zkoss.util.logging.Log;
/**
* {@link RepeatableReader} adds functionality to another reader,
* the ability to read repeatedly.
* By repeatable-read we meaen, after {@link #close}, the next invocation of
* {@link #read} will re-open the reader.
*
* <p>{@link RepeatableInputStream} actually creates a temporary space
* to buffer the content, so it can be re-opened again after closed.
* Notice that the temporary space (aka., the buffered reader)
* is never closed until garbage-collected.
*
* <p>If the content size of the given reader is smaller than
* the value specified in the system property called
* "org.zkoss.io.memoryLimitSize", the content will be buffered in
* the memory. If the size exceeds, the content will be buffered in
* a temporary file. By default, it is 512KB.
* Note: the maximal value is {@link Integer#MAX_VALUE}
*
* <p>If the content size of the given reader is larger than
* the value specified in the system property called
* "org.zkoss.io.bufferLimitSize", the content won't be buffered,
* and it means the read is not repeatable. By default, it is 20MB.
* Note: the maximal value is {@link Integer#MAX_VALUE}
*
* @author tomyeh
* @since 3.0.4
*/
public class RepeatableReader extends Reader implements Repeatable {
private static final Log log = Log.lookup(RepeatableReader.class);
private Reader _org;
private Writer _out;
private Reader _in;
private File _f;
/** The content size. It is meaningful only if !_nobuf.
* Note: int is enough (since long makes no sense for buffering)
*/
private int _cntsz;
private final int _bufmaxsz, _memmaxsz;
private boolean _nobuf;
private RepeatableReader(Reader is) {
_org = is;
_bufmaxsz = Library.getIntProperty(
RepeatableInputStream.BUFFER_LIMIT_SIZE, 20 * 1024 * 1024);
_memmaxsz = Library.getIntProperty(
RepeatableInputStream.MEMORY_LIMIT_SIZE, 512 * 1024);
}
/**
* Returns a reader that can be read repeatedly, or null if the given
* reader is null.
* Note: the returned reader encapsulates the given reader, rd
* (aka., the buffered reader) to adds the functionality to
* re-opens the reader once {@link #close} is called.
*
* <p>By repeatable-read we meaen, after {@link #close}, the next
* invocation of {@link #read} will re-open the reader.
*
* <p>Use this method instead of instantiating {@link RepeatableReader}
* with the constructor.
*
* @see #getInstance(File)
*/
public static Reader getInstance(Reader rd) {
if ((rd instanceof CharArrayReader) || (rd instanceof StringReader))
return new ResetableReader(rd);
else if (rd != null && !(rd instanceof Repeatable))
return new RepeatableReader(rd);
return rd;
}
/**
* Returns a reader to read a file that can be read repeatedly.
* Note: it assumes the file is text (rather than binary).
*
* <p>By repeatable-read we meaen, after {@link #close}, the next
* invocation of {@link #read} will re-open the reader.
*
* <p>Note: it is effecient since we don't have to buffer the
* content of the file to make it repeatable-read.
*
* @param charset the charset. If null, "UTF-8" is assumed.
* @exception IllegalArgumentException if file is null.
* @see #getInstance(Reader)
* @see #getInstance(String, String)
* @since 3.0.8
*/
public static Reader getInstance(File file, String charset)
throws FileNotFoundException {
if (file == null)
throw new IllegalArgumentException("null");
if (!file.exists())
throw new FileNotFoundException(file.toString());
return new RepeatableFileReader(file, charset);
}
/**
* Returns a reader to read a file, encoded in UTF-8,
* that can be read repeatedly.
* Note: it assumes the file is text (rather than binary).
*
* <p>By repeatable-read we meaen, after {@link #close}, the next
* invocation of {@link #read} will re-open the reader.
*
* <p>Note: it is effecient since we don't have to buffer the
* content of the file to make it repeatable-read.
*
* @exception IllegalArgumentException if file is null.
* @see #getInstance(Reader)
* @see #getInstance(String)
*/
public static Reader getInstance(File file)
throws FileNotFoundException {
return getInstance(file, "UTF-8");
}
/**
* Returns a reader to read a file that can be read repeatedly.
* Note: it assumes the file is text (rather than binary).
*
* <p>By repeatable-read we meaen, after {@link #close}, the next
* invocation of {@link #read} will re-open the reader.
*
* <p>Note: it is effecient since we don't have to buffer the
* content of the file to make it repeatable-read.
*
* @param filename the file name
* @param charset the charset. If null, "UTF-8" is assumed.
* @exception IllegalArgumentException if file is null.
* @exception FileNotFoundException if file is not found.
* @see #getInstance(Reader)
* @see #getInstance(File, String)
* @since 3.0.8
*/
public static Reader getInstance(String filename, String charset)
throws FileNotFoundException {
return getInstance(new File(filename));
}
/**
* Returns a reader to read a file, encoded in UTF-8,
* that can be read repeatedly.
* Note: it assumes the file is text (rather than binary).
*
* <p>By repeatable-read we meaen, after {@link #close}, the next
* invocation of {@link #read} will re-open the reader.
*
* <p>Note: it is effecient since we don't have to buffer the
* content of the file to make it repeatable-read.
*
* @param filename the file name
* @exception IllegalArgumentException if file is null.
* @exception FileNotFoundException if file is not found.
* @see #getInstance(Reader)
* @see #getInstance(File)
*/
public static Reader getInstance(String filename)
throws FileNotFoundException {
return getInstance(new File(filename), "UTF-8");
}
/**
* Returns a reader to read the resource of the specified URL.
* The reader can be read repeatedly.
* Note: it assumes the resource is text (rather than binary).
*
* <p>By repeatable-read we meaen, after {@link #close}, the next
* invocation of {@link #read} will re-open the reader.
*
* <p>Note: it is effecient since we don't have to buffer the
* content of the file to make it repeatable-read.
*
* @param charset the charset. If null, "UTF-8" is assumed.
* @exception IllegalArgumentException if file is null.
* @see #getInstance(Reader)
* @see #getInstance(String, String)
* @since 3.0.8
*/
public static Reader getInstance(URL url, String charset) {
if (url == null)
throw new IllegalArgumentException("null");
return new RepeatableURLReader(url, charset);
}
/**
* Returns a reader to read the resource of the specified URL,
* encoded in UTF-8.
* The reader can be read repeatedly.
* Note: it assumes the resource is text (rather than binary).
*
* <p>By repeatable-read we mean, after {@link #close}, the next
* invocation of {@link #read} will re-open the reader.
*
* <p>Note: it is efficient since we don't have to buffer the
* content of the file to make it repeatable-read.
*
* @exception IllegalArgumentException if file is null.
* @see #getInstance(Reader)
* @see #getInstance(String)
*/
public static Reader getInstance(URL url) {
return getInstance(url, "UTF-8");
}
private Writer getWriter() throws IOException {
if (_out == null)
return _nobuf ? null: (_out = new StringWriter());
//it is possible _membufsz <= 0, but OK to use memory first
if (_cntsz >= _bufmaxsz) { //too large to buffer
disableBuffering();
return null;
}
if (_f == null && _cntsz >= _memmaxsz) { //memory to file
try {
final File f =
new File(System.getProperty("java.io.tmpdir"), "zk");
if (!f.isDirectory())
f.mkdir();
_f = File.createTempFile("zk.io", ".zk.io", f);
final String cnt = ((StringWriter)_out).toString();
_out = new FileWriter(_f, "UTF-8");
_out.write(cnt);
} catch (Throwable ex) {
log.warning("Ignored: failed to buffer to a file, "+_f+"\nCause: "+ex.getMessage());
disableBuffering();
}
}
return _out;
}
private void disableBuffering() {
_nobuf = true;
if (_out != null) {
try {
_out.close();
} catch (Throwable ex) { //ignore
}
_out = null;
}
if (_f != null) {
try {
_f.delete();
} catch (Throwable ex) { //ignore
}
_f = null;
}
}
public int read(char cbuf[], int off, int len) throws IOException {
if (_org != null) {
final int cnt = _org.read(cbuf, off, len);
if (!_nobuf)
if (cnt >= 0) {
final Writer out = getWriter();
if (out != null) out.write(cbuf, off, cnt);
_cntsz += cnt;
}
return cnt;
} else {
if (_in == null)
_in = new FileReader(_f, "UTF-8"); //_f must be non-null
return _in.read(cbuf, off, len);
}
}
/** Closes the current access, and the next call of {@link #read}
* re-opens the buffered reader.
*/
public void close() throws IOException {
_cntsz = 0;
if (_org != null) {
_org.close();
if (_out != null) {
try {
_out.close();
} catch (Throwable ex) {
log.warning("Ignored: failed to close the buffer.\nCause: "+ex.getMessage());
disableBuffering();
return;
}
if (_f == null)
_in = new StringReader(
((StringWriter)_out).toString());
//we don't initilize _in if _f is not null
//to reduce memory use (after all, read might not be called)
_out = null;
_org = null;
}
} else if (_in != null) {
if (_f != null) {
_in.close();
_in = null;
} else {
_in.reset();
}
}
}
//Object//
protected void finalize() throws Throwable {
disableBuffering();
if (_org != null)
_org.close();
if (_in != null) {
_in.close();
_in = null;
}
super.finalize();
}
}
/*package*/ class ResetableReader extends Reader implements Repeatable {
private final Reader _org;
ResetableReader(Reader bais) {
_org = bais;
}
public int read(char cbuf[], int off, int len) throws IOException {
return _org.read(cbuf, off, len);
}
/** Closes the current access and the next call of {@link #read}
* re-opens the buffered reader.
*/
public void close() throws IOException {
_org.reset();
}
//Object//
protected void finalize() throws Throwable {
_org.close();
super.finalize();
}
}
/*package*/ class RepeatableFileReader extends Reader implements Repeatable {
private final File _file;
private Reader _in;
private final String _charset;
RepeatableFileReader(File file, String charset) {
_file = file;
_charset = charset != null ? charset: "UTF-8";
}
public int read(char cbuf[], int off, int len) throws IOException {
if (_in == null)
_in = new FileReader(_file, _charset);
return _in.read(cbuf, off, len);
}
/** Closes the current access and the next call of {@link #read}
* re-opens the buffered reader.
*/
public void close() throws IOException {
if (_in != null) {
_in.close();
_in = null;
}
}
//Object//
protected void finalize() throws Throwable {
close();
super.finalize();
}
}
/*package*/ class RepeatableURLReader extends Reader implements Repeatable {
private final URL _url;
private Reader _in;
private final String _charset;
RepeatableURLReader(URL url, String charset) {
_url = url;
_charset = charset != null ? charset: "UTF-8";
}
public int read(char cbuf[], int off, int len) throws IOException {
if (_in == null)
_in = new URLReader(_url, _charset);
return _in.read(cbuf, off, len);
}
/** Closes the current access and the next call of {@link #read}
* re-opens the buffered reader.
*/
public void close() throws IOException {
if (_in != null) {
_in.close();
_in = null;
}
}
//Object//
protected void finalize() throws Throwable {
close();
super.finalize();
}
}
|
package com.raymon.api.demo.leetcodedemo;
import java.util.ArrayList;
import java.util.List;
/**
* @author :raymon
* @date :Created in 2019/7/12 11:23
* @description:给定两个数组,编写一个函数来计算它们的交集。
* @modified By:
* @version: 1.0$
*/
public class Intersect {
public static int[] intersect(int[] nums1, int[] nums2) {
List list = new ArrayList();
for (int i = 0; i < nums1.length; i++){
for (int j = 0; j < nums2.length; j++){
if (nums1[i] == nums2[j]){
System.out.println(i);
list.add(nums1[i]);
break;
}
}
}
System.out.println(list);
int[] o = new int[list.size()];
for(int i = 0; i < list.size(); i++){
o[i] = (int)list.get(i);
}
return o;
}
public static void main(String[] args) {
int[] nums1 = new int[]{1,2,2,1};
int[] nums2 = new int[]{2,2};
intersect(nums1, nums2);
}
}
|
/**
* project name:saas
* file name:CorsConfiguration
* package name:com.cdkj.product.config
* date:2018/3/25 下午2:45
* author:bovine
* Copyright (c) CD Technology Co.,Ltd. All rights reserved.
*/
package com.cdkj.config;
import com.cdkj.common.interceptor.CommonInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* description: 公共配置,跨域问题处理<br>
* date: 2018/3/25 下午2:45
*
* @author bovine
* @version 1.0
* @since JDK 1.8
*/
@Configuration
public class ConfigurerAdapter extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*")
.allowedOrigins("*").allowedHeaders("*")
.allowCredentials(true);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CommonInterceptor());
}
}
|
package com.vipvideo.util.web.mahua;
import android.app.Application;
import com.alibaba.fastjson.JSON;
import com.lixh.app.BaseApplication;
import java.io.InputStream;
/**
* Created by LIXH on 2018/12/26.
* email lixhVip9@163.com
* des
*/
public class MhSdk {
static MhSdk sdk;
Application application;
AppInfo appInfo;
public MhSdk(Application application) {
this.application = application;
}
public static MhSdk init() {
if (sdk == null) {
sdk = new MhSdk(BaseApplication.getAppContext());
sdk.initAppInfo();
try {
sdk.initPackInfo();
} catch (Exception e) {
e.printStackTrace();
}
}
return sdk;
}
private void initAppInfo() {
appInfo = new AppInfo(application);
}
public AppInfo getAppInfo() {
return this.appInfo;
}
private void initPackInfo() throws Exception {
InputStream open = application.getAssets().open("pack_info");
byte[] bArr = new byte[open.available()];
open.read(bArr);
open.close();
String str = new String(bArr, "utf8");
String decryptHex = AesUtil.decryptHex(str, AesUtil.getKey(true));
if (decryptHex != null) {
str = decryptHex;
}
PackInfo packInfo = JSON.parseObject(str, PackInfo.class);
RHelp.initInfo(packInfo);
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.aot.hint.JdkProxyHint;
import org.springframework.aot.hint.ProxyHints;
/**
* Write {@link JdkProxyHint}s contained in a {@link ProxyHints} to the JSON
* output expected by the GraalVM {@code native-image} compiler, typically named
* {@code proxy-config.json}.
*
* @author Sebastien Deleuze
* @author Stephane Nicoll
* @author Brian Clozel
* @since 6.0
* @see <a href="https://www.graalvm.org/22.1/reference-manual/native-image/DynamicProxy/">Dynamic Proxy in Native Image</a>
* @see <a href="https://www.graalvm.org/22.1/reference-manual/native-image/BuildConfiguration/">Native Image Build Configuration</a>
*/
class ProxyHintsWriter {
public static final ProxyHintsWriter INSTANCE = new ProxyHintsWriter();
public void write(BasicJsonWriter writer, ProxyHints hints) {
writer.writeArray(hints.jdkProxyHints().map(this::toAttributes).toList());
}
private Map<String, Object> toAttributes(JdkProxyHint hint) {
Map<String, Object> attributes = new LinkedHashMap<>();
handleCondition(attributes, hint);
attributes.put("interfaces", hint.getProxiedInterfaces());
return attributes;
}
private void handleCondition(Map<String, Object> attributes, JdkProxyHint hint) {
if (hint.getReachableType() != null) {
Map<String, Object> conditionAttributes = new LinkedHashMap<>();
conditionAttributes.put("typeReachable", hint.getReachableType());
attributes.put("condition", conditionAttributes);
}
}
}
|
package com.git.cloud.resmgt.network.model.vo;
import com.git.cloud.resmgt.network.model.po.RmNwConvergePo;
/**
* @Description
* @author make
* @version v1.0 2015-3-6
*/
public class RmNwConvergeVo extends RmNwConvergePo implements java.io.Serializable{
/**
* 数据中心名称(中文)
*/
private String datacenterName;
/** default constructor */
public RmNwConvergeVo() {
}
/** minimal constructor */
public RmNwConvergeVo(String convergeId) {
super(convergeId);
}
/** full constructor */
public RmNwConvergeVo(String convergeId, String convergeName, String dataCenter,
String isActive) {
super(convergeId, convergeName, dataCenter, isActive);
}
public String getDatacenterName() {
return datacenterName;
}
public void setDatacenterName(String datacenterName) {
this.datacenterName = datacenterName;
}
}
|
package com.test.promanage.po;
import java.util.Date;
public class TableFile {
private Integer fileid;
private String filename;
private String filepath;
private String proid;
private String userid;
private Integer taskid;
private Date createtime;
private String intro;
public Integer getFileid() {
return fileid;
}
public void setFileid(Integer fileid) {
this.fileid = fileid;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename == null ? null : filename.trim();
}
public String getFilepath() {
return filepath;
}
public void setFilepath(String filepath) {
this.filepath = filepath == null ? null : filepath.trim();
}
public String getProid() {
return proid;
}
public void setProid(String proid) {
this.proid = proid == null ? null : proid.trim();
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid == null ? null : userid.trim();
}
public Integer getTaskid() {
return taskid;
}
public void setTaskid(Integer taskid) {
this.taskid = taskid;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro == null ? null : intro.trim();
}
}
|
package com.icanit.app_v2.service.factory;
import android.content.Context;
import com.icanit.app_v2.exception.AppException;
import com.icanit.app_v2.service.DataService;
import com.icanit.app_v2.service.UserService;
import com.icanit.app_v2.sqlite.ShoppingCartDao;
import com.icanit.app_v2.sqlite.ShoppingCartService;
import com.icanit.app_v2.sqlite.UserBrowsingDao;
import com.icanit.app_v2.sqlite.UserCollectionDao;
import com.icanit.app_v2.sqlite.UserContactDao;
public interface ServiceFactory {
DataService getDataServiceInstance(Context context) throws AppException;
ShoppingCartDao getShoppingCartDaoInstance(Context context) throws AppException;
UserService getUserServiceInstance(Context context)throws AppException;
ShoppingCartService getShoppingCartServiceInstance(Context context)throws AppException;
UserContactDao getUserContactDaoInstance(Context context) throws AppException;
UserCollectionDao getUserCollectionDaoInstance(Context context)throws AppException;
UserBrowsingDao getUserBrowsingDaoInstance(Context context) throws AppException;
}
|
package nh.automation.tools.serviceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import nh.automation.tools.common.BeanUtil;
import nh.automation.tools.common.JsonPluginsUtil;
import nh.automation.tools.common.PageResult;
import nh.automation.tools.dao.OutlookMenuMapper;
import nh.automation.tools.dto.Result;
import nh.automation.tools.entity.OutlookMenu;
import nh.automation.tools.service.OutlookMenuService;
/**
* 项目 :UI自动化测试 SSM 类描述:
*
* @author Eric
* @date 2017年3月9日 nh.automation.tools.ervice
*/
@Service
@Transactional
public class OutlookMenuServiceImp implements OutlookMenuService {
@Autowired
private OutlookMenuMapper mapper;
/*
* @see nh.automation.tools.dao.OutlookMenuMapper#outlookMenus()
*/
public List<OutlookMenu> outlookMenus() {
return mapper.getAll();
}
public PageResult<OutlookMenu> queryByPage(String key, Integer pageNo, Integer pageSize,String sortField, String sortOrder) {
pageNo = pageNo == null ? 0 : pageNo;
pageSize = pageSize == null ? 10 : pageSize;
// startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
PageHelper.startPage(pageNo+1, pageSize);
// 用PageInfo对结果进行包装
return BeanUtil.toPageResult(mapper.selectMenuByText(key));
}
/*
* @see
* nh.automation.tools.service.OutlookMenuService#saveOutlookMenus(java.lang
* .String)
*/
public Result<Object> saveOutlookMenus(String jsonString) {
JSONArray jsonArray = JSONArray.fromObject(jsonString);
List<OutlookMenu> jsonToBeanList = JsonPluginsUtil.jsonToBeanList(jsonString, OutlookMenu.class);
for (int i = 0; i < jsonToBeanList.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.get("id") != null ? jsonObject.get("id").toString() : "";
String state = jsonObject.get("_state") != null ? jsonObject.get("_state").toString() : "";
if (state.equals("added") || id.equals("")) // 新增:id为空,或_state为added
{
if (mapper.insert(jsonToBeanList.get(i)) > 0) {
return new Result<Object>(true, "保存成功");
}
} else if (state.equals("removed") || state.equals("deleted")) {
if (mapper.deleteByPrimaryKey(jsonToBeanList.get(i).getId()) > 0) {
return new Result<Object>(true, "删除成功");
}
} else if (state.equals("modified") || state.equals("")) // 更新:_state为空,或modified
{
if (mapper.updateByPrimaryKey(jsonToBeanList.get(i)) > 0) {
return new Result<Object>(true, "更新成功");
}
} else {
return new Result<Object>(true, "保存成功");
}
}
return new Result<Object>(false, "提交失败,返回异常,请处理");
}
}
|
package com.eshop.service.impl;
import com.eshop.dao.ProductDAO;
import com.eshop.domain.CategoryOfProduct;
import com.eshop.domain.Product;
import com.eshop.domain.ProductParameteres;
import com.eshop.jms.MessageSender;
import com.eshop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
/**
* Contains implementations of methods ProductService for working with the product.
*/
@Service
@Transactional
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductDAO dao;
@Autowired
private MessageSender sender;
@Override
public Product getProductByName(String name) {
return dao.getProductByName(name);
}
@Override
public Product getProductById(int id) {
return dao.getProductById(id);
}
@Override
public List<Product> getAllProducts() {
return dao.getAllProducts();
}
@Override
public List<Product> getAllProductsByPrice(double priceMin, double priceMax) {
return dao.getAllProductsByPrice(priceMin, priceMax);
}
@Override
public List<Product> getAllProductsByPrice(double priceMin, double priceMax, String type) {
return dao.getAllProductsByPrice(priceMin, priceMax, type);
}
@Override
public List<Product> getAllProductsByBrand(String brand) {
return dao.getAllProductsByBrand(brand);
}
@Override
public List<Product> getAllProductsByColour(String colour, String type) {
return dao.getAllProductsByColour(colour, type);
}
@Override
public void editProductByAdmin(int productId, String productName, String brand, double price, int amount, String category, String colour, int weight, String operatingSystem) {
CategoryOfProduct productCategory = getSingleCategoryByName(category);
ProductParameteres parameteres = new ProductParameteres(colour, brand, weight, operatingSystem);
Product product = getProductById(productId);
product.setProductName(productName);
product.setProductPrice(price);
product.setAmount(amount);
product.setProductCategory(productCategory);
product.setProductParameteres(parameteres);
saveProduct(product);
sender.sendMessage("Update");
}
@Override
public Set<CategoryOfProduct> getAllCategories() {
return dao.getAllCategories();
}
@Override
public void saveCategory(CategoryOfProduct category) {
dao.saveCategory(category);
}
@Override
public List<CategoryOfProduct> getCategoryByName(String categoryName) {
return dao.getCategoryByName(categoryName);
}
@Override
public int deleteCategoryByName(String categoryName) {
return dao.deleteCategoryByName(categoryName);
}
@Override
public CategoryOfProduct getSingleCategoryByName(String name) {
return dao.getSingleCategoryByName(name);
}
@Override
public void saveProduct(Product product) {
dao.saveProduct(product);
}
/**
* Decreases amount of a product in stock.
* @param product
* @param countOfItems
* @return
*/
@Override
public int decreaseProductAmountInStock(Product product, int countOfItems) {
int newAmount;
int amount = dao.getProductById(product.getId()).getAmount();
if (amount >= countOfItems) {
newAmount = amount - countOfItems;
} else throw new IllegalArgumentException("Not enough amount");
return newAmount;
}
@Override
public int saveNewAmountOfProduct(Product product, int amount) {
return dao.saveNewAmountOfProduct(product, amount);
}
@Override
public List<Product> getAllProductsByCategory(CategoryOfProduct category) {
return dao.getAllProductsByCategory(category);
}
@Override
public List<Product> getAllProductsByCategory(String category) {
return dao.getAllProductsByCategory(category);
}
@Override
public List<Product> getAllProductsByBrand(String brand, String type) {
return dao.getAllProductsByBrand(brand, type);
}
}
|
package pl.pionwit.android.server.db;
public class DBQuery {
public final static String QUERY_ID_NAMBERS = "SELECT * FROM pionwit_db.idnamber;";
public final static String QUERY_ID_NAMBERS_TO_CONTRAGENT = "SELECT * FROM pionwit_db.idnamber where contragent_id=";
public final static String QUERY_COUNTRYS = "SELECT * FROM pionwit_db.countrys;";
public final static String QUERY_COUNTRYS_TO_ID = "SELECT * FROM pionwit_db.countrys where id=";
public final static String QUERY_ADDRESSES = "SELECT * FROM pionwit_db.addresses";
public final static String QUERY_ADDRESSES_TO_CONTRAGENT = "SELECT * FROM pionwit_db.addresses where contragent_id=";
public final static String QUERY_VID_ADDRESSES = "SELECT * FROM pionwit_db.vidaddresses;";
public final static String QUERY_VID_ADDRESS_TO_ID = "SELECT * FROM pionwit_db.vidaddresses where id=";
public final static String QUERY_CONTRAGENTS = "SELECT * FROM pionwit_db.contragents;";
public final static String QUERY_STATUSES = "SELECT * FROM pionwit_db.statuses;";
public final static String QUERY_STATUSES_TO_ID = "SELECT * FROM pionwit_db.statuses where id=";
public final static String QUERY_USERS = "SELECT * FROM pionwit_db.users;";
public final static String QUERY_INSERT_STATUSES = "INSERT INTO pionwit_db.statuses (name, opis) value (?,?);";
public final static String QUERY_INSERT_USER = "INSERT INTO pionwit_db.users (name,email,password," +
"date_reg,date_last,statuses_id) value (?,?,?,?,?,?);";
public final static String QUERY_DELETE_BY_ID = "DELETE FROM pionwit_db.";
public final static String QUERY_DELETE_STATUS_BY_ID = "DELETE FROM pionwit_db.statuses where id=";
public final static String QUERY_UPDATE_USER_BY_ID = "UPDATE pionwit_db.users SET NAME = ?, EMAIL = ?, " +
"PASSWORD = ?, DATE_REG = ?, DATE_LAST = ?, STATUSES_ID = ? WHERE ID = ?;";
public final static String QUERY_UPDATE_STATUSES_BY_ID = "UPDATE pionwit_db.statuses " +
"SET NAME = ?, OPIS = ? WHERE ID = ?;";
}
|
package com.shwetansh.covid_19tracker;
public class ModelVaccinated {
private String country, timeline;
public ModelVaccinated() {
}
public ModelVaccinated(String country, String timeline) {
this.country = country;
this.timeline = timeline;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getTimeline() {
return timeline;
}
public void setTimeline(String timeline) {
this.timeline = timeline;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.expression.spel.standard;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
import org.springframework.expression.ParseException;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.TemplateAwareExpressionParser;
import org.springframework.expression.spel.InternalParseException;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.SpelMessage;
import org.springframework.expression.spel.SpelParseException;
import org.springframework.expression.spel.SpelParserConfiguration;
import org.springframework.expression.spel.ast.Assign;
import org.springframework.expression.spel.ast.BeanReference;
import org.springframework.expression.spel.ast.BooleanLiteral;
import org.springframework.expression.spel.ast.CompoundExpression;
import org.springframework.expression.spel.ast.ConstructorReference;
import org.springframework.expression.spel.ast.Elvis;
import org.springframework.expression.spel.ast.FunctionReference;
import org.springframework.expression.spel.ast.Identifier;
import org.springframework.expression.spel.ast.Indexer;
import org.springframework.expression.spel.ast.InlineList;
import org.springframework.expression.spel.ast.InlineMap;
import org.springframework.expression.spel.ast.Literal;
import org.springframework.expression.spel.ast.MethodReference;
import org.springframework.expression.spel.ast.NullLiteral;
import org.springframework.expression.spel.ast.OpAnd;
import org.springframework.expression.spel.ast.OpDec;
import org.springframework.expression.spel.ast.OpDivide;
import org.springframework.expression.spel.ast.OpEQ;
import org.springframework.expression.spel.ast.OpGE;
import org.springframework.expression.spel.ast.OpGT;
import org.springframework.expression.spel.ast.OpInc;
import org.springframework.expression.spel.ast.OpLE;
import org.springframework.expression.spel.ast.OpLT;
import org.springframework.expression.spel.ast.OpMinus;
import org.springframework.expression.spel.ast.OpModulus;
import org.springframework.expression.spel.ast.OpMultiply;
import org.springframework.expression.spel.ast.OpNE;
import org.springframework.expression.spel.ast.OpOr;
import org.springframework.expression.spel.ast.OpPlus;
import org.springframework.expression.spel.ast.OperatorBetween;
import org.springframework.expression.spel.ast.OperatorInstanceof;
import org.springframework.expression.spel.ast.OperatorMatches;
import org.springframework.expression.spel.ast.OperatorNot;
import org.springframework.expression.spel.ast.OperatorPower;
import org.springframework.expression.spel.ast.Projection;
import org.springframework.expression.spel.ast.PropertyOrFieldReference;
import org.springframework.expression.spel.ast.QualifiedIdentifier;
import org.springframework.expression.spel.ast.Selection;
import org.springframework.expression.spel.ast.SpelNodeImpl;
import org.springframework.expression.spel.ast.StringLiteral;
import org.springframework.expression.spel.ast.Ternary;
import org.springframework.expression.spel.ast.TypeReference;
import org.springframework.expression.spel.ast.VariableReference;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
/**
* Handwritten SpEL parser. Instances are reusable but are not thread-safe.
*
* @author Andy Clement
* @author Juergen Hoeller
* @author Phillip Webb
* @author Sam Brannen
* @since 3.0
*/
class InternalSpelExpressionParser extends TemplateAwareExpressionParser {
private static final Pattern VALID_QUALIFIED_ID_PATTERN = Pattern.compile("[\\p{L}\\p{N}_$]+");
private final SpelParserConfiguration configuration;
// For rules that build nodes, they are stacked here for return
private final Deque<SpelNodeImpl> constructedNodes = new ArrayDeque<>();
// Shared cache for compiled regex patterns
private final ConcurrentMap<String, Pattern> patternCache = new ConcurrentHashMap<>();
// The expression being parsed
private String expressionString = "";
// The token stream constructed from that expression string
private List<Token> tokenStream = Collections.emptyList();
// length of a populated token stream
private int tokenStreamLength;
// Current location in the token stream when processing tokens
private int tokenStreamPointer;
/**
* Create a parser with some configured behavior.
* @param configuration custom configuration options
*/
public InternalSpelExpressionParser(SpelParserConfiguration configuration) {
this.configuration = configuration;
}
@Override
protected SpelExpression doParseExpression(String expressionString, @Nullable ParserContext context)
throws ParseException {
checkExpressionLength(expressionString);
try {
this.expressionString = expressionString;
Tokenizer tokenizer = new Tokenizer(expressionString);
this.tokenStream = tokenizer.process();
this.tokenStreamLength = this.tokenStream.size();
this.tokenStreamPointer = 0;
this.constructedNodes.clear();
SpelNodeImpl ast = eatExpression();
if (ast == null) {
throw new SpelParseException(this.expressionString, 0, SpelMessage.OOD);
}
Token t = peekToken();
if (t != null) {
throw new SpelParseException(this.expressionString, t.startPos, SpelMessage.MORE_INPUT, toString(nextToken()));
}
return new SpelExpression(expressionString, ast, this.configuration);
}
catch (InternalParseException ex) {
throw ex.getCause();
}
}
private void checkExpressionLength(String string) {
int maxLength = this.configuration.getMaximumExpressionLength();
if (string.length() > maxLength) {
throw new SpelEvaluationException(SpelMessage.MAX_EXPRESSION_LENGTH_EXCEEDED, maxLength);
}
}
// expression
// : logicalOrExpression
// ( (ASSIGN^ logicalOrExpression)
// | (DEFAULT^ logicalOrExpression)
// | (QMARK^ expression COLON! expression)
// | (ELVIS^ expression))?;
@Nullable
private SpelNodeImpl eatExpression() {
SpelNodeImpl expr = eatLogicalOrExpression();
Token t = peekToken();
if (t != null) {
if (t.kind == TokenKind.ASSIGN) { // a=b
if (expr == null) {
expr = new NullLiteral(t.startPos - 1, t.endPos - 1);
}
nextToken();
SpelNodeImpl assignedValue = eatLogicalOrExpression();
return new Assign(t.startPos, t.endPos, expr, assignedValue);
}
if (t.kind == TokenKind.ELVIS) { // a?:b (a if it isn't null, otherwise b)
if (expr == null) {
expr = new NullLiteral(t.startPos - 1, t.endPos - 2);
}
nextToken(); // elvis has left the building
SpelNodeImpl valueIfNull = eatExpression();
if (valueIfNull == null) {
valueIfNull = new NullLiteral(t.startPos + 1, t.endPos + 1);
}
return new Elvis(t.startPos, t.endPos, expr, valueIfNull);
}
if (t.kind == TokenKind.QMARK) { // a?b:c
if (expr == null) {
expr = new NullLiteral(t.startPos - 1, t.endPos - 1);
}
nextToken();
SpelNodeImpl ifTrueExprValue = eatExpression();
eatToken(TokenKind.COLON);
SpelNodeImpl ifFalseExprValue = eatExpression();
return new Ternary(t.startPos, t.endPos, expr, ifTrueExprValue, ifFalseExprValue);
}
}
return expr;
}
//logicalOrExpression : logicalAndExpression (OR^ logicalAndExpression)*;
@Nullable
private SpelNodeImpl eatLogicalOrExpression() {
SpelNodeImpl expr = eatLogicalAndExpression();
while (peekIdentifierToken("or") || peekToken(TokenKind.SYMBOLIC_OR)) {
Token t = takeToken(); //consume OR
SpelNodeImpl rhExpr = eatLogicalAndExpression();
checkOperands(t, expr, rhExpr);
expr = new OpOr(t.startPos, t.endPos, expr, rhExpr);
}
return expr;
}
// logicalAndExpression : relationalExpression (AND^ relationalExpression)*;
@Nullable
private SpelNodeImpl eatLogicalAndExpression() {
SpelNodeImpl expr = eatRelationalExpression();
while (peekIdentifierToken("and") || peekToken(TokenKind.SYMBOLIC_AND)) {
Token t = takeToken(); // consume 'AND'
SpelNodeImpl rhExpr = eatRelationalExpression();
checkOperands(t, expr, rhExpr);
expr = new OpAnd(t.startPos, t.endPos, expr, rhExpr);
}
return expr;
}
// relationalExpression : sumExpression (relationalOperator^ sumExpression)?;
@Nullable
private SpelNodeImpl eatRelationalExpression() {
SpelNodeImpl expr = eatSumExpression();
Token relationalOperatorToken = maybeEatRelationalOperator();
if (relationalOperatorToken != null) {
Token t = takeToken(); // consume relational operator token
SpelNodeImpl rhExpr = eatSumExpression();
checkOperands(t, expr, rhExpr);
TokenKind tk = relationalOperatorToken.kind;
if (relationalOperatorToken.isNumericRelationalOperator()) {
if (tk == TokenKind.GT) {
return new OpGT(t.startPos, t.endPos, expr, rhExpr);
}
if (tk == TokenKind.LT) {
return new OpLT(t.startPos, t.endPos, expr, rhExpr);
}
if (tk == TokenKind.LE) {
return new OpLE(t.startPos, t.endPos, expr, rhExpr);
}
if (tk == TokenKind.GE) {
return new OpGE(t.startPos, t.endPos, expr, rhExpr);
}
if (tk == TokenKind.EQ) {
return new OpEQ(t.startPos, t.endPos, expr, rhExpr);
}
if (tk == TokenKind.NE) {
return new OpNE(t.startPos, t.endPos, expr, rhExpr);
}
}
if (tk == TokenKind.INSTANCEOF) {
return new OperatorInstanceof(t.startPos, t.endPos, expr, rhExpr);
}
if (tk == TokenKind.MATCHES) {
return new OperatorMatches(this.patternCache, t.startPos, t.endPos, expr, rhExpr);
}
if (tk == TokenKind.BETWEEN) {
return new OperatorBetween(t.startPos, t.endPos, expr, rhExpr);
}
}
return expr;
}
//sumExpression: productExpression ( (PLUS^ | MINUS^) productExpression)*;
@Nullable
private SpelNodeImpl eatSumExpression() {
SpelNodeImpl expr = eatProductExpression();
while (peekToken(TokenKind.PLUS, TokenKind.MINUS, TokenKind.INC)) {
Token t = takeToken(); //consume PLUS or MINUS or INC
SpelNodeImpl rhExpr = eatProductExpression();
checkRightOperand(t, rhExpr);
if (t.kind == TokenKind.PLUS) {
expr = new OpPlus(t.startPos, t.endPos, expr, rhExpr);
}
else if (t.kind == TokenKind.MINUS) {
expr = new OpMinus(t.startPos, t.endPos, expr, rhExpr);
}
}
return expr;
}
// productExpression: powerExpr ((STAR^ | DIV^| MOD^) powerExpr)* ;
@Nullable
private SpelNodeImpl eatProductExpression() {
SpelNodeImpl expr = eatPowerIncDecExpression();
while (peekToken(TokenKind.STAR, TokenKind.DIV, TokenKind.MOD)) {
Token t = takeToken(); // consume STAR/DIV/MOD
SpelNodeImpl rhExpr = eatPowerIncDecExpression();
checkOperands(t, expr, rhExpr);
if (t.kind == TokenKind.STAR) {
expr = new OpMultiply(t.startPos, t.endPos, expr, rhExpr);
}
else if (t.kind == TokenKind.DIV) {
expr = new OpDivide(t.startPos, t.endPos, expr, rhExpr);
}
else if (t.kind == TokenKind.MOD) {
expr = new OpModulus(t.startPos, t.endPos, expr, rhExpr);
}
}
return expr;
}
// powerExpr : unaryExpression (POWER^ unaryExpression)? (INC || DEC) ;
@Nullable
private SpelNodeImpl eatPowerIncDecExpression() {
SpelNodeImpl expr = eatUnaryExpression();
if (peekToken(TokenKind.POWER)) {
Token t = takeToken(); //consume POWER
SpelNodeImpl rhExpr = eatUnaryExpression();
checkRightOperand(t, rhExpr);
return new OperatorPower(t.startPos, t.endPos, expr, rhExpr);
}
if (expr != null && peekToken(TokenKind.INC, TokenKind.DEC)) {
Token t = takeToken(); //consume INC/DEC
if (t.getKind() == TokenKind.INC) {
return new OpInc(t.startPos, t.endPos, true, expr);
}
return new OpDec(t.startPos, t.endPos, true, expr);
}
return expr;
}
// unaryExpression: (PLUS^ | MINUS^ | BANG^ | INC^ | DEC^) unaryExpression | primaryExpression ;
@Nullable
private SpelNodeImpl eatUnaryExpression() {
if (peekToken(TokenKind.NOT, TokenKind.PLUS, TokenKind.MINUS)) {
Token t = takeToken();
SpelNodeImpl expr = eatUnaryExpression();
if (expr == null) {
throw internalException(t.startPos, SpelMessage.OOD);
}
if (t.kind == TokenKind.NOT) {
return new OperatorNot(t.startPos, t.endPos, expr);
}
if (t.kind == TokenKind.PLUS) {
return new OpPlus(t.startPos, t.endPos, expr);
}
if (t.kind == TokenKind.MINUS) {
return new OpMinus(t.startPos, t.endPos, expr);
}
}
if (peekToken(TokenKind.INC, TokenKind.DEC)) {
Token t = takeToken();
SpelNodeImpl expr = eatUnaryExpression();
if (t.getKind() == TokenKind.INC) {
return new OpInc(t.startPos, t.endPos, false, expr);
}
if (t.kind == TokenKind.DEC) {
return new OpDec(t.startPos, t.endPos, false, expr);
}
}
return eatPrimaryExpression();
}
// primaryExpression : startNode (node)? -> ^(EXPRESSION startNode (node)?);
@Nullable
private SpelNodeImpl eatPrimaryExpression() {
SpelNodeImpl start = eatStartNode(); // always a start node
List<SpelNodeImpl> nodes = null;
SpelNodeImpl node = eatNode();
while (node != null) {
if (nodes == null) {
nodes = new ArrayList<>(4);
nodes.add(start);
}
nodes.add(node);
node = eatNode();
}
if (start == null || nodes == null) {
return start;
}
return new CompoundExpression(start.getStartPosition(), nodes.get(nodes.size() - 1).getEndPosition(),
nodes.toArray(new SpelNodeImpl[0]));
}
// node : ((DOT dottedNode) | (SAFE_NAVI dottedNode) | nonDottedNode)+;
@Nullable
private SpelNodeImpl eatNode() {
return (peekToken(TokenKind.DOT, TokenKind.SAFE_NAVI) ? eatDottedNode() : eatNonDottedNode());
}
// nonDottedNode: indexer;
@Nullable
private SpelNodeImpl eatNonDottedNode() {
if (peekToken(TokenKind.LSQUARE)) {
if (maybeEatIndexer()) {
return pop();
}
}
return null;
}
//dottedNode
// : ((methodOrProperty
// | functionOrVar
// | projection
// | selection
// | firstSelection
// | lastSelection
// ))
// ;
private SpelNodeImpl eatDottedNode() {
Token t = takeToken(); // it was a '.' or a '?.'
boolean nullSafeNavigation = (t.kind == TokenKind.SAFE_NAVI);
if (maybeEatMethodOrProperty(nullSafeNavigation) || maybeEatFunctionOrVar() ||
maybeEatProjection(nullSafeNavigation) || maybeEatSelection(nullSafeNavigation)) {
return pop();
}
if (peekToken() == null) {
throw internalException(t.startPos, SpelMessage.OOD);
}
else {
throw internalException(t.startPos, SpelMessage.UNEXPECTED_DATA_AFTER_DOT, toString(peekToken()));
}
}
// functionOrVar
// : (POUND ID LPAREN) => function
// | var
//
// function : POUND id=ID methodArgs -> ^(FUNCTIONREF[$id] methodArgs);
// var : POUND id=ID -> ^(VARIABLEREF[$id]);
private boolean maybeEatFunctionOrVar() {
if (!peekToken(TokenKind.HASH)) {
return false;
}
Token t = takeToken();
Token functionOrVariableName = eatToken(TokenKind.IDENTIFIER);
SpelNodeImpl[] args = maybeEatMethodArgs();
if (args == null) {
push(new VariableReference(functionOrVariableName.stringValue(),
t.startPos, functionOrVariableName.endPos));
return true;
}
push(new FunctionReference(functionOrVariableName.stringValue(),
t.startPos, functionOrVariableName.endPos, args));
return true;
}
// methodArgs : LPAREN! (argument (COMMA! argument)* (COMMA!)?)? RPAREN!;
@Nullable
private SpelNodeImpl[] maybeEatMethodArgs() {
if (!peekToken(TokenKind.LPAREN)) {
return null;
}
List<SpelNodeImpl> args = new ArrayList<>();
consumeArguments(args);
eatToken(TokenKind.RPAREN);
return args.toArray(new SpelNodeImpl[0]);
}
private void eatConstructorArgs(List<SpelNodeImpl> accumulatedArguments) {
if (!peekToken(TokenKind.LPAREN)) {
throw internalException(positionOf(peekToken()), SpelMessage.MISSING_CONSTRUCTOR_ARGS);
}
consumeArguments(accumulatedArguments);
eatToken(TokenKind.RPAREN);
}
/**
* Used for consuming arguments for either a method or a constructor call.
*/
private void consumeArguments(List<SpelNodeImpl> accumulatedArguments) {
Token t = peekToken();
if (t == null) {
return;
}
int pos = t.startPos;
Token next;
do {
nextToken(); // consume (first time through) or comma (subsequent times)
t = peekToken();
if (t == null) {
throw internalException(pos, SpelMessage.RUN_OUT_OF_ARGUMENTS);
}
if (t.kind != TokenKind.RPAREN) {
accumulatedArguments.add(eatExpression());
}
next = peekToken();
}
while (next != null && next.kind == TokenKind.COMMA);
if (next == null) {
throw internalException(pos, SpelMessage.RUN_OUT_OF_ARGUMENTS);
}
}
private int positionOf(@Nullable Token t) {
if (t == null) {
// if null assume the problem is because the right token was
// not found at the end of the expression
return this.expressionString.length();
}
return t.startPos;
}
//startNode
// : parenExpr | literal
// | type
// | methodOrProperty
// | functionOrVar
// | projection
// | selection
// | firstSelection
// | lastSelection
// | indexer
// | constructor
@Nullable
private SpelNodeImpl eatStartNode() {
if (maybeEatLiteral()) {
return pop();
}
else if (maybeEatParenExpression()) {
return pop();
}
else if (maybeEatTypeReference() || maybeEatNullReference() || maybeEatConstructorReference() ||
maybeEatMethodOrProperty(false) || maybeEatFunctionOrVar()) {
return pop();
}
else if (maybeEatBeanReference()) {
return pop();
}
else if (maybeEatProjection(false) || maybeEatSelection(false) || maybeEatIndexer()) {
return pop();
}
else if (maybeEatInlineListOrMap()) {
return pop();
}
else {
return null;
}
}
// parse: @beanname @'bean.name'
// quoted if dotted
private boolean maybeEatBeanReference() {
if (peekToken(TokenKind.BEAN_REF) || peekToken(TokenKind.FACTORY_BEAN_REF)) {
Token beanRefToken = takeToken();
Token beanNameToken = null;
String beanName = null;
if (peekToken(TokenKind.IDENTIFIER)) {
beanNameToken = eatToken(TokenKind.IDENTIFIER);
beanName = beanNameToken.stringValue();
}
else if (peekToken(TokenKind.LITERAL_STRING)) {
beanNameToken = eatToken(TokenKind.LITERAL_STRING);
beanName = beanNameToken.stringValue();
beanName = beanName.substring(1, beanName.length() - 1);
}
else {
throw internalException(beanRefToken.startPos, SpelMessage.INVALID_BEAN_REFERENCE);
}
BeanReference beanReference;
if (beanRefToken.getKind() == TokenKind.FACTORY_BEAN_REF) {
String beanNameString = String.valueOf(TokenKind.FACTORY_BEAN_REF.tokenChars) + beanName;
beanReference = new BeanReference(beanRefToken.startPos, beanNameToken.endPos, beanNameString);
}
else {
beanReference = new BeanReference(beanNameToken.startPos, beanNameToken.endPos, beanName);
}
this.constructedNodes.push(beanReference);
return true;
}
return false;
}
private boolean maybeEatTypeReference() {
if (peekToken(TokenKind.IDENTIFIER)) {
Token typeName = peekToken();
if (typeName == null || !"T".equals(typeName.stringValue())) {
return false;
}
// It looks like a type reference but is T being used as a map key?
Token t = takeToken();
if (peekToken(TokenKind.RSQUARE)) {
// looks like 'T]' (T is map key)
push(new PropertyOrFieldReference(false, t.stringValue(), t.startPos, t.endPos));
return true;
}
eatToken(TokenKind.LPAREN);
SpelNodeImpl node = eatPossiblyQualifiedId();
// dotted qualified id
// Are there array dimensions?
int dims = 0;
while (peekToken(TokenKind.LSQUARE, true)) {
eatToken(TokenKind.RSQUARE);
dims++;
}
eatToken(TokenKind.RPAREN);
this.constructedNodes.push(new TypeReference(typeName.startPos, typeName.endPos, node, dims));
return true;
}
return false;
}
private boolean maybeEatNullReference() {
if (peekToken(TokenKind.IDENTIFIER)) {
Token nullToken = peekToken();
if (nullToken == null || !"null".equalsIgnoreCase(nullToken.stringValue())) {
return false;
}
nextToken();
this.constructedNodes.push(new NullLiteral(nullToken.startPos, nullToken.endPos));
return true;
}
return false;
}
//projection: PROJECT^ expression RCURLY!;
private boolean maybeEatProjection(boolean nullSafeNavigation) {
Token t = peekToken();
if (t == null || !peekToken(TokenKind.PROJECT, true)) {
return false;
}
SpelNodeImpl expr = eatExpression();
if (expr == null) {
throw internalException(t.startPos, SpelMessage.OOD);
}
eatToken(TokenKind.RSQUARE);
this.constructedNodes.push(new Projection(nullSafeNavigation, t.startPos, t.endPos, expr));
return true;
}
// list = LCURLY (element (COMMA element)*) RCURLY
// map = LCURLY (key ':' value (COMMA key ':' value)*) RCURLY
private boolean maybeEatInlineListOrMap() {
Token t = peekToken();
if (t == null || !peekToken(TokenKind.LCURLY, true)) {
return false;
}
SpelNodeImpl expr = null;
Token closingCurly = peekToken();
if (closingCurly != null && peekToken(TokenKind.RCURLY, true)) {
// empty list '{}'
expr = new InlineList(t.startPos, closingCurly.endPos);
}
else if (peekToken(TokenKind.COLON, true)) {
closingCurly = eatToken(TokenKind.RCURLY);
// empty map '{:}'
expr = new InlineMap(t.startPos, closingCurly.endPos);
}
else {
SpelNodeImpl firstExpression = eatExpression();
// Next is either:
// '}' - end of list
// ',' - more expressions in this list
// ':' - this is a map!
if (peekToken(TokenKind.RCURLY)) { // list with one item in it
List<SpelNodeImpl> elements = new ArrayList<>();
elements.add(firstExpression);
closingCurly = eatToken(TokenKind.RCURLY);
expr = new InlineList(t.startPos, closingCurly.endPos, elements.toArray(new SpelNodeImpl[0]));
}
else if (peekToken(TokenKind.COMMA, true)) { // multi-item list
List<SpelNodeImpl> elements = new ArrayList<>();
elements.add(firstExpression);
do {
elements.add(eatExpression());
}
while (peekToken(TokenKind.COMMA, true));
closingCurly = eatToken(TokenKind.RCURLY);
expr = new InlineList(t.startPos, closingCurly.endPos, elements.toArray(new SpelNodeImpl[0]));
}
else if (peekToken(TokenKind.COLON, true)) { // map!
List<SpelNodeImpl> elements = new ArrayList<>();
elements.add(firstExpression);
elements.add(eatExpression());
while (peekToken(TokenKind.COMMA, true)) {
elements.add(eatExpression());
eatToken(TokenKind.COLON);
elements.add(eatExpression());
}
closingCurly = eatToken(TokenKind.RCURLY);
expr = new InlineMap(t.startPos, closingCurly.endPos, elements.toArray(new SpelNodeImpl[0]));
}
else {
throw internalException(t.startPos, SpelMessage.OOD);
}
}
this.constructedNodes.push(expr);
return true;
}
private boolean maybeEatIndexer() {
Token t = peekToken();
if (t == null || !peekToken(TokenKind.LSQUARE, true)) {
return false;
}
SpelNodeImpl expr = eatExpression();
if (expr == null) {
throw internalException(t.startPos, SpelMessage.MISSING_SELECTION_EXPRESSION);
}
eatToken(TokenKind.RSQUARE);
this.constructedNodes.push(new Indexer(t.startPos, t.endPos, expr));
return true;
}
private boolean maybeEatSelection(boolean nullSafeNavigation) {
Token t = peekToken();
if (t == null || !peekSelectToken()) {
return false;
}
nextToken();
SpelNodeImpl expr = eatExpression();
if (expr == null) {
throw internalException(t.startPos, SpelMessage.MISSING_SELECTION_EXPRESSION);
}
eatToken(TokenKind.RSQUARE);
if (t.kind == TokenKind.SELECT_FIRST) {
this.constructedNodes.push(new Selection(nullSafeNavigation, Selection.FIRST, t.startPos, t.endPos, expr));
}
else if (t.kind == TokenKind.SELECT_LAST) {
this.constructedNodes.push(new Selection(nullSafeNavigation, Selection.LAST, t.startPos, t.endPos, expr));
}
else {
this.constructedNodes.push(new Selection(nullSafeNavigation, Selection.ALL, t.startPos, t.endPos, expr));
}
return true;
}
/**
* Eat an identifier, possibly qualified (meaning that it is dotted).
* TODO AndyC Could create complete identifiers (a.b.c) here rather than a sequence of them? (a, b, c)
*/
private SpelNodeImpl eatPossiblyQualifiedId() {
Deque<SpelNodeImpl> qualifiedIdPieces = new ArrayDeque<>();
Token node = peekToken();
while (isValidQualifiedId(node)) {
nextToken();
if (node.kind != TokenKind.DOT) {
qualifiedIdPieces.add(new Identifier(node.stringValue(), node.startPos, node.endPos));
}
node = peekToken();
}
if (qualifiedIdPieces.isEmpty()) {
if (node == null) {
throw internalException( this.expressionString.length(), SpelMessage.OOD);
}
throw internalException(node.startPos, SpelMessage.NOT_EXPECTED_TOKEN,
"qualified ID", node.getKind().toString().toLowerCase());
}
return new QualifiedIdentifier(qualifiedIdPieces.getFirst().getStartPosition(),
qualifiedIdPieces.getLast().getEndPosition(), qualifiedIdPieces.toArray(new SpelNodeImpl[0]));
}
private boolean isValidQualifiedId(@Nullable Token node) {
if (node == null || node.kind == TokenKind.LITERAL_STRING) {
return false;
}
if (node.kind == TokenKind.DOT || node.kind == TokenKind.IDENTIFIER) {
return true;
}
String value = node.stringValue();
return (StringUtils.hasLength(value) && VALID_QUALIFIED_ID_PATTERN.matcher(value).matches());
}
// This is complicated due to the support for dollars in identifiers.
// Dollars are normally separate tokens but there we want to combine
// a series of identifiers and dollars into a single identifier.
private boolean maybeEatMethodOrProperty(boolean nullSafeNavigation) {
if (peekToken(TokenKind.IDENTIFIER)) {
Token methodOrPropertyName = takeToken();
SpelNodeImpl[] args = maybeEatMethodArgs();
if (args == null) {
// property
push(new PropertyOrFieldReference(nullSafeNavigation, methodOrPropertyName.stringValue(),
methodOrPropertyName.startPos, methodOrPropertyName.endPos));
return true;
}
// method reference
push(new MethodReference(nullSafeNavigation, methodOrPropertyName.stringValue(),
methodOrPropertyName.startPos, methodOrPropertyName.endPos, args));
// TODO what is the end position for a method reference? the name or the last arg?
return true;
}
return false;
}
//constructor
//: ('new' qualifiedId LPAREN) => 'new' qualifiedId ctorArgs -> ^(CONSTRUCTOR qualifiedId ctorArgs)
private boolean maybeEatConstructorReference() {
if (peekIdentifierToken("new")) {
Token newToken = takeToken();
// It looks like a constructor reference but is NEW being used as a map key?
if (peekToken(TokenKind.RSQUARE)) {
// looks like 'NEW]' (so NEW used as map key)
push(new PropertyOrFieldReference(false, newToken.stringValue(), newToken.startPos, newToken.endPos));
return true;
}
SpelNodeImpl possiblyQualifiedConstructorName = eatPossiblyQualifiedId();
List<SpelNodeImpl> nodes = new ArrayList<>();
nodes.add(possiblyQualifiedConstructorName);
if (peekToken(TokenKind.LSQUARE)) {
// array initializer
List<SpelNodeImpl> dimensions = new ArrayList<>();
while (peekToken(TokenKind.LSQUARE, true)) {
if (!peekToken(TokenKind.RSQUARE)) {
dimensions.add(eatExpression());
}
else {
dimensions.add(null);
}
eatToken(TokenKind.RSQUARE);
}
if (maybeEatInlineListOrMap()) {
nodes.add(pop());
}
push(new ConstructorReference(newToken.startPos, newToken.endPos,
dimensions.toArray(new SpelNodeImpl[0]), nodes.toArray(new SpelNodeImpl[0])));
}
else {
// regular constructor invocation
eatConstructorArgs(nodes);
// TODO correct end position?
push(new ConstructorReference(newToken.startPos, newToken.endPos, nodes.toArray(new SpelNodeImpl[0])));
}
return true;
}
return false;
}
private void push(SpelNodeImpl newNode) {
this.constructedNodes.push(newNode);
}
private SpelNodeImpl pop() {
return this.constructedNodes.pop();
}
// literal
// : INTEGER_LITERAL
// | boolLiteral
// | STRING_LITERAL
// | HEXADECIMAL_INTEGER_LITERAL
// | REAL_LITERAL
// | DQ_STRING_LITERAL
// | NULL_LITERAL
private boolean maybeEatLiteral() {
Token t = peekToken();
if (t == null) {
return false;
}
if (t.kind == TokenKind.LITERAL_INT) {
push(Literal.getIntLiteral(t.stringValue(), t.startPos, t.endPos, 10));
}
else if (t.kind == TokenKind.LITERAL_LONG) {
push(Literal.getLongLiteral(t.stringValue(), t.startPos, t.endPos, 10));
}
else if (t.kind == TokenKind.LITERAL_HEXINT) {
push(Literal.getIntLiteral(t.stringValue(), t.startPos, t.endPos, 16));
}
else if (t.kind == TokenKind.LITERAL_HEXLONG) {
push(Literal.getLongLiteral(t.stringValue(), t.startPos, t.endPos, 16));
}
else if (t.kind == TokenKind.LITERAL_REAL) {
push(Literal.getRealLiteral(t.stringValue(), t.startPos, t.endPos, false));
}
else if (t.kind == TokenKind.LITERAL_REAL_FLOAT) {
push(Literal.getRealLiteral(t.stringValue(), t.startPos, t.endPos, true));
}
else if (peekIdentifierToken("true")) {
push(new BooleanLiteral(t.stringValue(), t.startPos, t.endPos, true));
}
else if (peekIdentifierToken("false")) {
push(new BooleanLiteral(t.stringValue(), t.startPos, t.endPos, false));
}
else if (t.kind == TokenKind.LITERAL_STRING) {
push(new StringLiteral(t.stringValue(), t.startPos, t.endPos, t.stringValue()));
}
else {
return false;
}
nextToken();
return true;
}
//parenExpr : LPAREN! expression RPAREN!;
private boolean maybeEatParenExpression() {
if (peekToken(TokenKind.LPAREN)) {
Token t = nextToken();
if (t == null) {
return false;
}
SpelNodeImpl expr = eatExpression();
if (expr == null) {
throw internalException(t.startPos, SpelMessage.OOD);
}
eatToken(TokenKind.RPAREN);
push(expr);
return true;
}
else {
return false;
}
}
// relationalOperator
// : EQUAL | NOT_EQUAL | LESS_THAN | LESS_THAN_OR_EQUAL | GREATER_THAN
// | GREATER_THAN_OR_EQUAL | INSTANCEOF | BETWEEN | MATCHES
@Nullable
private Token maybeEatRelationalOperator() {
Token t = peekToken();
if (t == null) {
return null;
}
if (t.isNumericRelationalOperator()) {
return t;
}
if (t.isIdentifier()) {
String idString = t.stringValue();
if (idString.equalsIgnoreCase("instanceof")) {
return t.asInstanceOfToken();
}
if (idString.equalsIgnoreCase("matches")) {
return t.asMatchesToken();
}
if (idString.equalsIgnoreCase("between")) {
return t.asBetweenToken();
}
}
return null;
}
private Token eatToken(TokenKind expectedKind) {
Token t = nextToken();
if (t == null) {
int pos = this.expressionString.length();
throw internalException(pos, SpelMessage.OOD);
}
if (t.kind != expectedKind) {
throw internalException(t.startPos, SpelMessage.NOT_EXPECTED_TOKEN,
expectedKind.toString().toLowerCase(), t.getKind().toString().toLowerCase());
}
return t;
}
private boolean peekToken(TokenKind desiredTokenKind) {
return peekToken(desiredTokenKind, false);
}
private boolean peekToken(TokenKind desiredTokenKind, boolean consumeIfMatched) {
Token t = peekToken();
if (t == null) {
return false;
}
if (t.kind == desiredTokenKind) {
if (consumeIfMatched) {
this.tokenStreamPointer++;
}
return true;
}
if (desiredTokenKind == TokenKind.IDENTIFIER) {
// Might be one of the textual forms of the operators (e.g. NE for != ) -
// in which case we can treat it as an identifier. The list is represented here:
// Tokenizer.alternativeOperatorNames and those ones are in order in the TokenKind enum.
if (t.kind.ordinal() >= TokenKind.DIV.ordinal() && t.kind.ordinal() <= TokenKind.NOT.ordinal() &&
t.data != null) {
// if t.data were null, we'd know it wasn't the textual form, it was the symbol form
return true;
}
}
return false;
}
private boolean peekToken(TokenKind possible1, TokenKind possible2) {
Token t = peekToken();
if (t == null) {
return false;
}
return (t.kind == possible1 || t.kind == possible2);
}
private boolean peekToken(TokenKind possible1, TokenKind possible2, TokenKind possible3) {
Token t = peekToken();
if (t == null) {
return false;
}
return (t.kind == possible1 || t.kind == possible2 || t.kind == possible3);
}
private boolean peekIdentifierToken(String identifierString) {
Token t = peekToken();
if (t == null) {
return false;
}
return (t.kind == TokenKind.IDENTIFIER && identifierString.equalsIgnoreCase(t.stringValue()));
}
private boolean peekSelectToken() {
Token t = peekToken();
if (t == null) {
return false;
}
return (t.kind == TokenKind.SELECT || t.kind == TokenKind.SELECT_FIRST || t.kind == TokenKind.SELECT_LAST);
}
private Token takeToken() {
if (this.tokenStreamPointer >= this.tokenStreamLength) {
throw new IllegalStateException("No token");
}
return this.tokenStream.get(this.tokenStreamPointer++);
}
@Nullable
private Token nextToken() {
if (this.tokenStreamPointer >= this.tokenStreamLength) {
return null;
}
return this.tokenStream.get(this.tokenStreamPointer++);
}
@Nullable
private Token peekToken() {
if (this.tokenStreamPointer >= this.tokenStreamLength) {
return null;
}
return this.tokenStream.get(this.tokenStreamPointer);
}
public String toString(@Nullable Token t) {
if (t == null) {
return "";
}
if (t.getKind().hasPayload()) {
return t.stringValue();
}
return t.kind.toString().toLowerCase();
}
private void checkOperands(Token token, @Nullable SpelNodeImpl left, @Nullable SpelNodeImpl right) {
checkLeftOperand(token, left);
checkRightOperand(token, right);
}
private void checkLeftOperand(Token token, @Nullable SpelNodeImpl operandExpression) {
if (operandExpression == null) {
throw internalException(token.startPos, SpelMessage.LEFT_OPERAND_PROBLEM);
}
}
private void checkRightOperand(Token token, @Nullable SpelNodeImpl operandExpression) {
if (operandExpression == null) {
throw internalException(token.startPos, SpelMessage.RIGHT_OPERAND_PROBLEM);
}
}
private InternalParseException internalException(int startPos, SpelMessage message, Object... inserts) {
return new InternalParseException(new SpelParseException(this.expressionString, startPos, message, inserts));
}
}
|
package com.lti.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.lti.model.Admin;
import com.lti.model.Customer_Details;
import com.lti.model.Registration;
@Repository("dao")
@Scope(scopeName = "singleton")
public class CustomerDaoImpl implements CustomerDao{
@PersistenceContext
private EntityManager entityManager;
@Transactional(propagation = Propagation.MANDATORY)
public void addRegistration(Registration reg) {
entityManager.persist(reg);
}
public Registration getRegistrationDetailsbyEmail(String email) {
Query query = entityManager.createQuery("Select r From Registration r Where emailId = :email");
query.setParameter("email", email);
Registration reg = (Registration) query.getSingleResult();
return reg;
}
public Admin getAdminDetailsbyEmail(String email) {
Query query = entityManager.createQuery("Select a From Admin a Where ademail = :email");
query.setParameter("email", email);
Admin adm = (Admin)query.getSingleResult();
return adm;
}
public List<Registration> getAllRegistrations() {
Query query = entityManager.createQuery("Select r From Registration r");
List<Registration> reg = query.getResultList();
return reg;
}
public List<Admin> getAllAdmins() {
Query query = entityManager.createQuery("Select a From Admin a");
List<Admin> admlist = query.getResultList();
return admlist;
}
public Customer_Details getCustomerDetailsbyEmail(String email) {
Query query = entityManager.createQuery("Select c From Customer_Details c Where c.registration.emailId = :email");
query.setParameter("email", email);
Customer_Details cd = (Customer_Details) query.getSingleResult();
return cd;
}
/*
public List<Application> getAllApplicationsbyEmail(String email) {
Query query = entityManager.createQuery("Select a From Application a where a.cdetails2.registration.emailId = :email");
query.setParameter("email", email);
return query.getResultList();
}
*/
public List<Customer_Details> getAllCustomerDetails() {
Query query = entityManager.createQuery("Select c From Customer_Details c");
return query.getResultList();
}
/*
public List<Application> getAllApplications() {
Query query = entityManager.createQuery("Select a From Application a ");
return query.getResultList();
}
*/
}
|
package com.example.jordi.printerpartner.activities;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.jordi.printerpartner.adapters.PrinterAdapter;
import com.example.jordi.printerpartner.R;
import com.example.jordi.printerpartner.component.PrintPartner;
import com.unforce.imagen.collection.Part;
import com.unforce.imagen.collection.PartStatus;
import com.unforce.imagen.collection.PrintJob;
import com.unforce.imagen.collection.Printer;
import com.unforce.imagen.collection.PrinterStatus;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Random;
public class PrinterListActivity extends AppCompatActivity {
// HAMBURGER MENU //
private static String TAG = PrinterListActivity.class.getSimpleName();
ListView mDrawerList;
RelativeLayout mDrawerPane;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
PrinterAdapter adapter;
ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();
// END OF HAMBURGER MENU //
ArrayList<Printer> printerList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_printer_list);
// HAMBURGER MENU //
mNavItems.add(new NavItem("Reset Printers", ""));
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Populate the Navigtion Drawer with options
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter drawerListAdapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(drawerListAdapter);
// Drawer Item click listeners
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItemFromDrawer(position);
}
});
// END OF HAMBURGER MENU //
final ListView printerView = (ListView)findViewById(R.id.lvPrinter);
PrintPartner printPartner = PrintPartner.getInstance();
printPartner.setContext(PrinterListActivity.this);
printPartner.getConnection().getHandler().initialize(1);
final PrinterAdapter adapter = new PrinterAdapter(PrinterListActivity.this, printerList);
printerView.setAdapter(adapter);
if(LoginActivity.demo == true) {
for (int i = 0; i < 5; i++) {
Printer printer = new Printer(i, "printer 0" + i, PrinterStatus.IDLE);
printer.addPart(new Part("Printerkop", Calendar.getInstance().getTime(), printer));
printer.addPart(new Part("Toner", Calendar.getInstance().getTime(), printer));
printer.addPart(new Part("Papier", Calendar.getInstance().getTime(), printer));
printer.setCurrentTask(new PrintJob("printjob "+i, "copyshop "+i, Calendar.getInstance()));
printerList.add(printer);
}
}
final Thread thread = new Thread(new Runnable() {
PartStatus[] statuses = PartStatus.values();
@Override
public void run() {
for(;;) {
if(printerList.size() < 1)
continue;
Random random = new Random();
Printer selectedPrinter = printerList.get(random.nextInt(printerList.size()));
Part selectedPart = selectedPrinter.getParts().get(random.nextInt(selectedPrinter.getParts().size()));
PartStatus partStatus = selectedPart.getStatus();
do {
PartStatus newStatus = statuses[random.nextInt(PartStatus.values().length)];
selectedPart.setStatus(newStatus);
if(newStatus == PartStatus.BROKEN)
{
notifyUser(selectedPrinter, newStatus.toString());
}
} while(partStatus == selectedPart.getStatus());
Collections.sort(printerList, new Comparator<Printer>() {
@Override
public int compare(Printer printer1, Printer printer2) {
if (printer1.getStatus() == printer2.getStatus()) {
return printer1.getName().compareTo(printer2.getName());
} else {
return printer1.getStatus().compareTo(printer2.getStatus());
}
}
});
final Handler UIHandler = new Handler(Looper.getMainLooper());
UIHandler.post(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.setDaemon(true);
thread.start();
}
public void notifyUser(Printer printer, String warning)
{
Intent intent = new Intent(this, TabviewPrinterDetailActivity.class);
intent.putExtra("printer", printer);
// use System.currentTimeMillis() to have a unique ID for the pending intent
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setContentTitle(warning + " " + printer.getName())
.setContentText(printer.getName() + " encountered an "+ warning+ " and needs attention!")
.setSmallIcon(R.drawable.error)
.setContentIntent(pIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(200);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle
// If it returns true, then it has handled
// the nav drawer indicator touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
/*
* Called when a particular item from the navigation drawer
* is selected.
* */
private void selectItemFromDrawer(int position) {
Fragment fragment = new PreferencesFragment();
if(position == 0) {
for (Printer p : printerList) {
for (Part prt : p.getParts()) {
prt.setStatus(PartStatus.WORKING);
}
}
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.commit();
mDrawerList.setItemChecked(position, true);
// Close the drawer
mDrawerLayout.closeDrawer(mDrawerPane);
}
// END HAMBURGER MENU //
public void setPrinterList(ArrayList<Printer> printers) {
Collections.sort(printerList, new Comparator<Printer>() {
@Override
public int compare(Printer printer1, Printer printer2) {
if (printer1.getStatus() == printer2.getStatus()) {
return printer1.getName().compareTo(printer2.getName());
} else {
return printer1.getStatus().compareTo(printer2.getStatus());
}
}
});
printerList.addAll(printers);
}
}
class NavItem {
String mTitle;
String mSubtitle;
public NavItem(String title, String subtitle) {
mTitle = title;
mSubtitle = subtitle;
}
}
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
@Override
public int getCount() {
return mNavItems.size();
}
@Override
public Object getItem(int position) {
return mNavItems.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, null);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
TextView subtitleView = (TextView) view.findViewById(R.id.subTitle);
titleView.setText(mNavItems.get(position).mTitle);
subtitleView.setText(mNavItems.get(position).mSubtitle);
return view;
}
}
|
package com.gome.manager.domain;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
public class ObjectBean {
private int oid;
private String title;
private String discribe;
private Timestamp createTime;
private String remark;
private int state;
private String anonymousFlag;
private String meetingId;
List<Question> questionList = new ArrayList<Question>();
public List<Question> getQuestionList() {
return questionList;
}
public void setQuestionList(List<Question> questionList) {
this.questionList = questionList;
}
public String getMeetingId() {
return meetingId;
}
public void setMeetingId(String meetingId) {
this.meetingId = meetingId;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public ObjectBean() {
}
public int getOid() {
return oid;
}
public void setOid(int oid) {
this.oid = oid;
}
public void setTitle(String title) {
this.title = title;
}
public void setDiscribe(String discribe) {
this.discribe = discribe;
}
public String getTitle() {
return title;
}
public String getDiscribe() {
return discribe;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getAnonymousFlag() {
return anonymousFlag;
}
public void setAnonymousFlag(String anonymousFlag) {
this.anonymousFlag = anonymousFlag;
}
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
}
|
package viewGraphic;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import model.Model;
public class PlayerMenu extends Menu {
public PlayerMenu() {
this.addTitle("Combien de joueurs ?", 250);
Button deux = new Button("2 Joueurs");
deux.setPrefWidth(200);
deux.setPrefHeight(75);
deux.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
PlayerSetupMenu a = new PlayerSetupMenu(2);
a.show(Main.primaryStage);
}
});
Button trois = new Button("3 Joueurs");
trois.setPrefWidth(200);
trois.setPrefHeight(75);
trois.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
PlayerSetupMenu a = new PlayerSetupMenu(3);
a.show(Main.primaryStage);
}
});
Button quatre = new Button("4 Joueurs");
quatre.setPrefWidth(200);
quatre.setPrefHeight(75);
quatre.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
PlayerSetupMenu a = new PlayerSetupMenu(4);
a.show(Main.primaryStage);
}
});
VBox vBox = new VBox();
vBox.getChildren().add(deux);
vBox.getChildren().add(trois);
vBox.getChildren().add(quatre);
vBox.setTranslateX(445);
vBox.setTranslateY(400);
this.root.getChildren().add(vBox);
}
}
|
package com.codingchili.instance.model.spells;
import com.codingchili.instance.scripting.Scripted;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.codingchili.core.configuration.Configurable;
import com.codingchili.core.configuration.CoreStrings;
import com.codingchili.core.storage.Storable;
/**
* @author Robin Duda
* <p>
* A spell item from the spell DB.
*/
public class Spell implements Storable, Configurable {
private SpellAnimation animation = new SpellAnimation();
private String id = "no_id";
private String name = "no name";
private String description = "no description";
private Boolean mobile = true; // can move and cast?
private Boolean skill = false; // indicates if skill or spell.
private Target target = Target.caster; // spell target: caster, area etc.
private Integer charges = 0; // number of times the spell can be cast in a sequence without recharge.
private Integer range = 100; // how far away the target may be.
private Integer radius = 64; // the size of the affected player area.
private Float interval = 0.5f; // how often to call onProgress and onActive.
private Float cooldown = 1.0f; // minimum time between casting the spell.
private Float recharge = 1.0f; // time taken to generate one charge.
private Float casttime = 0.0f; // the time taken to cast the spell.
private Float active = 0.0f; // how long the spell is active after casting is completed.
private Scripted onCastBegin; // check pre-requisites - must check result.
private Scripted onCastProgress; // implement for channeled abilities.
private Scripted onCastComplete; // implement casted spell logic here.
private Scripted onSpellActive; // for spells that are active longer than the casting period.
@Override
public String getPath() {
return "conf/game/classes/" + id + CoreStrings.EXT_YAML;
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getSkill() {
return skill;
}
public void setSkill(Boolean skill) {
this.skill = skill;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getMobile() {
return mobile;
}
public void setMobile(Boolean mobile) {
this.mobile = mobile;
}
public Target getTarget() {
return target;
}
public void setTarget(Target target) {
this.target = target;
}
public Integer getCharges() {
return charges;
}
public void setCharges(Integer charges) {
this.charges = charges;
}
public Float getCooldown() {
return cooldown;
}
public void setCooldown(Float cooldown) {
this.cooldown = cooldown;
}
public Float getCasttime() {
return casttime;
}
public void setCasttime(Float casttime) {
this.casttime = casttime;
}
public Integer getRange() {
return range;
}
public void setRange(Integer range) {
this.range = range;
}
public Integer getRadius() {
return radius;
}
public void setRadius(Integer radius) {
this.radius = radius;
}
public Float getActive() {
return active;
}
public void setActive(Float active) {
this.active = active;
}
public Float getInterval() {
return interval;
}
public void setInterval(Float interval) {
this.interval = interval;
}
public Float getRecharge() {
return recharge;
}
public void setRecharge(Float recharge) {
this.recharge = recharge;
}
public SpellAnimation getAnimation() {
return animation;
}
public void setAnimation(SpellAnimation animation) {
this.animation = animation;
}
@JsonIgnore
public Scripted getOnCastBegin() {
return onCastBegin;
}
@JsonProperty("onCastBegin")
public void setOnCastBegin(Scripted onCastBegin) {
this.onCastBegin = onCastBegin;
}
@JsonIgnore
public Scripted getOnCastProgress() {
return onCastProgress;
}
@JsonProperty("onCastProgress")
public void setOnCastProgress(Scripted onCastProgress) {
this.onCastProgress = onCastProgress;
}
@JsonIgnore
public Scripted getOnCastComplete() {
return onCastComplete;
}
@JsonProperty("onCastComplete")
public void setOnCastComplete(Scripted onCastComplete) {
this.onCastComplete = onCastComplete;
}
@JsonIgnore
public Scripted getOnSpellActive() {
return onSpellActive;
}
@JsonProperty("onSpellActive")
public void setOnSpellActive(Scripted onSpellActive) {
this.onSpellActive = onSpellActive;
}
}
|
package com.dbs.portal.database.to.common;
public enum YesNoType {
Yes("Y","common.yes"), No("N","common.no");
private String yesOrNo;
private String messageKey;
private YesNoType(String yesOrNo, String messageKey){
this.yesOrNo = yesOrNo;
this.messageKey = messageKey;
}
public String getMessageKey(){
return this.messageKey;
}
public String getYesNo(){
return this.yesOrNo;
}
public static YesNoType convert(String yesOrNo) {
for (YesNoType type : values()) {
if (type.getYesNo().equals(yesOrNo))
return type;
}
return null;
}
}
|
package modelo;
import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
public class Enemy {
private int x, y, dx, dy, height, width;
private Image imageEnemy;
private boolean isVisible;
private static final int VELOCITY = 2;
public Enemy(int x, int y) {
this.x = x;
this.y = y;
isVisible = true;
}
public void loadEnemy() {
ImageIcon ref = new ImageIcon("img\\enemy1.png");
imageEnemy = ref.getImage();
height = imageEnemy.getHeight(null);
width = imageEnemy.getWidth(null);
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
public void updateEnemy() {
this.x -= VELOCITY;
}
public void setVisible(boolean isVisible) {
this.isVisible = isVisible;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public static int getVelocity() {
return VELOCITY;
}
public boolean isVisible() {
return isVisible;
}
public Image getImageEnemy() {
return imageEnemy;
}
}
|
package ir.shayandaneshvar.jottery.models;
import lombok.*;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
import javax.validation.constraints.Size;
import java.time.LocalDate;
import java.util.List;
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString(exclude = {"level","prize"})
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NonNull
// @Column(unique = true)
@Basic(fetch = FetchType.EAGER)
private Long nationalCode;
@NonNull
@NotBlank
private String firstName;
@NonNull
@NotBlank
private String lastName;
@NonNull
@Positive
private Integer score;
// @PastOrPresent
private LocalDate birthDate;
@NonNull
@Enumerated(EnumType.STRING)
private Gender gender;
@NotBlank
@Size(min = 3, max = 12)
@Basic(fetch = FetchType.LAZY)
private String mobile;
@ManyToOne
private Level level;
@OneToOne/*(mappedBy = "customer",cascade = CascadeType.ALL)*/
private Prize prize;
public Customer(Long nationalCode, String firstName, String lastName,
Integer score, LocalDate birthDate, Gender gender,
String mobile) {
this.nationalCode = nationalCode;
this.firstName = firstName;
this.birthDate = birthDate;
this.lastName = lastName;
this.gender = gender;
this.mobile = mobile;
this.score = score;
}
}
|
/**
* Copyright 2017 伊永飞
*
* 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.yea.remote.netty.server.handle;
import java.util.Date;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import com.yea.core.base.act.AbstractAct;
import com.yea.core.base.act.reflect.ReflectAct;
import com.yea.core.base.id.UUIDGenerator;
import com.yea.core.remote.constants.RemoteConstants;
import com.yea.core.remote.exception.RemoteException;
import com.yea.core.remote.struct.CallReflect;
import com.yea.core.remote.struct.Header;
import com.yea.core.remote.struct.Message;
import com.yea.remote.netty.constants.NettyConstants;
import com.yea.remote.netty.handle.AbstractServiceHandler;
import com.yea.remote.netty.handle.NettyChannelHandler;
import com.yea.remote.netty.send.SendHelper;
import com.yea.remote.netty.send.SendHelperRegister;
/**
* 服务端对客户端发送过来的请求进行处理
*
* @author yiyongfei
*
*/
public class ServiceServerHandler extends AbstractServiceHandler implements NettyChannelHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceServerHandler.class);
private int availableProcessors = 0;
private ForkJoinPool pool = null;
public ServiceServerHandler() {
availableProcessors = Runtime.getRuntime().availableProcessors();
if (((int) Math.floor(availableProcessors * 1.5)) == availableProcessors) {
//当CPU核心是一核时,workerGroup的线程数为2
availableProcessors = availableProcessors + 1;
} else {
availableProcessors = (int) Math.floor(availableProcessors * 1.5);
}
pool = new ForkJoinPool(availableProcessors);
}
@Override
protected void execute(ChannelHandlerContext ctx, Message message) throws Exception {
// TODO Auto-generated method stub
if (message.getHeader().getType() == RemoteConstants.MessageType.SERVICE_REQ.value()) {
long times = new Date().getTime() - ((Date) message.getHeader().getAttachment()
.get(NettyConstants.MessageHeaderAttachment.HEADER_DATE.value())).getTime();
if (times > 1500) {
LOGGER.warn("{}从{}接收到请求[标识:{}]" + ",共用时:{}(传输用时:{})(耗时久),消息长度:{}", ctx.channel().localAddress(),
ctx.channel().remoteAddress(), UUIDGenerator.restore(message.getHeader().getSessionID()), times,
new Date().getTime() - ((Date) message.getHeader().getAttachment()
.get(NettyConstants.MessageHeaderAttachment.SEND_DATE.value())).getTime(),
message.getHeader().getLength());
} else {
LOGGER.info("{}从{}接收到请求[标识:{}]" + ",共用时:{}(传输用时:{}),消息长度:{}", ctx.channel().localAddress(),
ctx.channel().remoteAddress(), UUIDGenerator.restore(message.getHeader().getSessionID()), times,
new Date().getTime() - ((Date) message.getHeader().getAttachment()
.get(NettyConstants.MessageHeaderAttachment.SEND_DATE.value())).getTime(),
message.getHeader().getLength());
}
pool.execute(new InnerTask(this.getApplicationContext(), ctx, message));
} else {
ctx.fireChannelRead(message);
}
}
public ChannelHandler clone() throws CloneNotSupportedException {
ServiceServerHandler obj = null;
obj = (ServiceServerHandler) super.clone();
return obj;
}
class InnerTask extends RecursiveAction {
private static final long serialVersionUID = 1L;
private ApplicationContext springContext;
private ChannelHandlerContext nettyContext;
private Message message;
public InnerTask(ApplicationContext springContext, ChannelHandlerContext nettyContext, Message message) {
this.springContext = springContext;
this.nettyContext = nettyContext;
this.message = message;
}
@Override
protected void compute() {
// TODO Auto-generated method stub
Message serviceResp = null;
String actName = (String) message.getHeader().getAttachment()
.get(NettyConstants.MessageHeaderAttachment.CALL_ACT.value());
AbstractAct<?> cloneAct;
Object act = null;
if (!StringUtils.isEmpty(actName)) {
act = springContext.getBean(actName);
}
try {
if (act != null && act instanceof AbstractAct) {
cloneAct = ((AbstractAct<?>) act).clone();
} else {
CallReflect reflect = (CallReflect) message.getHeader().getAttachment()
.get(NettyConstants.MessageHeaderAttachment.CALL_REFLECT.value());
if (reflect != null) {
cloneAct = new ReflectAct();
((ReflectAct) cloneAct).setMethodName(reflect.getMethodName());
if (act != null) {
((ReflectAct) cloneAct).setTarget(act);
} else {
((ReflectAct) cloneAct)
.setTarget(springContext.getBean(Class.forName(reflect.getClassName())));
}
} else {
throw new RemoteException("未发现Act[" + actName + "]被注册成Act类型,同时也未指定具体的Method,不能执行!");
}
}
cloneAct.setApplicationContext(springContext);
cloneAct.setMessages((Object[]) message.getBody());
cloneAct.fork();
Object result = cloneAct.join();
serviceResp = buildServiceResp(RemoteConstants.MessageResult.SUCCESS.value(), message, result);
} catch (Exception ex) {
LOGGER.error("处理" + actName + "服务[标识:" + UUIDGenerator.restore(message.getHeader().getSessionID())
+ "]时出现异常:", ex);
serviceResp = buildServiceResp(RemoteConstants.MessageResult.FAILURE.value(), message, ex);
} finally {
cloneAct = null;
}
try {
SendHelper nettySend = SendHelperRegister.getInstance(nettyContext.channel());
nettySend.send(serviceResp, null);
} catch (Exception ex) {
LOGGER.error("批量发送出现异常,采取逐一发送策略,异常原因:" + ex);
nettyContext.writeAndFlush(serviceResp);
}
}
private Message buildServiceResp(byte result, Message serviceReq, Object body) {
Message message = new Message();
Header header = new Header();
header.setType(RemoteConstants.MessageType.SERVICE_RESP.value());
header.setSessionID(serviceReq.getHeader().getSessionID());
header.setResult(result);
if (!StringUtils.isEmpty(serviceReq.getHeader().getAttachment()
.get(NettyConstants.MessageHeaderAttachment.CALLBACK_ACT.value()))) {
header.addAttachment(NettyConstants.MessageHeaderAttachment.CALL_ACT.value(), serviceReq
.getHeader().getAttachment().get(NettyConstants.MessageHeaderAttachment.CALLBACK_ACT.value()));
}
header.addAttachment(NettyConstants.MessageHeaderAttachment.REQUEST_DATE.value(), serviceReq
.getHeader().getAttachment().get(NettyConstants.MessageHeaderAttachment.HEADER_DATE.value()));
header.addAttachment(NettyConstants.MessageHeaderAttachment.REQUEST_SEND_DATE.value(), serviceReq
.getHeader().getAttachment().get(NettyConstants.MessageHeaderAttachment.SEND_DATE.value()));
header.addAttachment(NettyConstants.MessageHeaderAttachment.REQUEST_RECIEVE_DATE.value(), serviceReq
.getHeader().getAttachment().get(NettyConstants.MessageHeaderAttachment.RECIEVE_DATE.value()));
header.addAttachment(NettyConstants.MessageHeaderAttachment.HEADER_DATE.value(), new Date());
message.setHeader(header);
message.setBody(body);
return message;
}
}
}
|
package peace.developer.serj.photoloader.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import peace.developer.serj.photoloader.Api.NetworkProvider;
import peace.developer.serj.photoloader.MainActivity;
import peace.developer.serj.photoloader.R;
import peace.developer.serj.photoloader.interfaces.ApiCallback;
import peace.developer.serj.photoloader.models.User;
public class UsersFragment extends Fragment implements ApiCallback {
private final String TAG = "UsersFragment";
LinearLayout container_ll;
MainActivity mActivity;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.users_fragment, container, false);
return v;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
NetworkProvider.getmInstance().getUsers(this);
mActivity = (MainActivity) getActivity();
initViews(view);
}
private void initViews(View view) {
container_ll = view.findViewById(R.id.items_container);
}
@Override
public void onResponse(String response) {
try {
List<User> list = new ArrayList<>();
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
list.add(new User(object.getInt("id"), object.getString("name")));
}
fillUsers(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onError() {
Toast.makeText(mActivity, "Some error", Toast.LENGTH_SHORT).show();
}
private void fillUsers(final List<User> list) {
for (int i = 0; i < list.size(); i++) {
View v = LayoutInflater.from(mActivity).inflate(R.layout.item_view, null);
((TextView) v.findViewById(R.id.user_name)).setText(list.get(i).getName());
container_ll.addView(v);
v.setTag(i + 1);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction().hide(UsersFragment.this).commit();
PhotosFragment fragment;
if (mActivity.photosFragment != null) {
fragment = mActivity.photosFragment;
getFragmentManager().beginTransaction().show(fragment).commit();
} else {
fragment = new PhotosFragment();
mActivity.photosFragment = fragment;
getFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
fragment.setCurrentUser(list.get((int) v.getTag() - 1));
}
});
}
}
}
|
package com.citibank.ods.modules.client.curacctprmntinstr.functionality.valueobject;
import java.math.BigInteger;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
*
* @see package
* com.citibank.ods.modules.client.curacctprmntinstr.functionality.valueobject;
* @version 1.0
* @author michele.monteiro,18/06/2007
*/
public class BaseCurAcctPrmntInstrListFncVO extends BaseODSFncVO
{
// Data Set para popular o grid.
private DataSet m_results = null;
//Variável de controle - Buscar
private boolean m_isFromSearch = false;
//Tela destino do botão buscar
private String m_clickedSearch = "";
//Número do cliente
private BigInteger m_custNbrSrc = null;
//Código da instrução permanente
private BigInteger m_prmntInstrCodeSrc = null;
//Indicador de Conta CCI - Combo.
private DataSet m_prmntInstrInvstCurAcctIndDomain = null;
//Indicador de Conta CCI.
private String m_prmntInstrInvstCurAcctIndSrc = "";
//Número da conta
private BigInteger m_curAcctNbrSrc = null;
// Codigo da Conta Produto. Informacao gerada pela ODS Private para
// identificar uma operacao ou um contrato
private BigInteger m_selectedProdAcctCode = null;
// Codigo da sub conta produto. Codigo gerado pela ODS para identificar
// produtos que tenham subcontas ou subcontratos
private BigInteger m_selectedProdUnderAcctCode = null;
//Número do cliente selecionado no grid
private BigInteger m_selectedCustNbr = null;
//Código da instrução permanente selecionada no grid.
private BigInteger m_selectedPrmntInstrCode = null;
//Nome do cliente
private String m_custFullNameSrc = "";
//Descrição da instrução permanente
private String m_prmntInstrTextSrc = "";
/**
* @return Returns clickedSearch.
*/
public String getClickedSearch()
{
return m_clickedSearch;
}
/**
* @param clickedSearch_ Field clickedSearch to be setted.
*/
public void setClickedSearch( String clickedSearch_ )
{
m_clickedSearch = clickedSearch_;
}
/**
* @return Returns curAcctNbrSrc.
*/
public BigInteger getCurAcctNbrSrc()
{
return m_curAcctNbrSrc;
}
/**
* @param curAcctNbrSrc_ Field curAcctNbrSrc to be setted.
*/
public void setCurAcctNbrSrc( BigInteger curAcctNbrSrc_ )
{
m_curAcctNbrSrc = curAcctNbrSrc_;
}
/**
* @return Returns custFullNameSrc.
*/
public String getCustFullNameSrc()
{
return m_custFullNameSrc;
}
/**
* @param custFullNameSrc_ Field custFullNameSrc to be setted.
*/
public void setCustFullNameSrc( String custFullNameSrc_ )
{
m_custFullNameSrc = custFullNameSrc_;
}
/**
* @return Returns custNbrSrc.
*/
public BigInteger getCustNbrSrc()
{
return m_custNbrSrc;
}
/**
* @param custNbrSrc_ Field custNbrSrc to be setted.
*/
public void setCustNbrSrc( BigInteger custNbrSrc_ )
{
m_custNbrSrc = custNbrSrc_;
}
/**
* @return Returns isFromSearch.
*/
public boolean isFromSearch()
{
return m_isFromSearch;
}
/**
* @param isFromSearch_ Field isFromSearch to be setted.
*/
public void setFromSearch( boolean isFromSearch_ )
{
m_isFromSearch = isFromSearch_;
}
/**
* @return Returns prmntInstrCodeSrc.
*/
public BigInteger getPrmntInstrCodeSrc()
{
return m_prmntInstrCodeSrc;
}
/**
* @param prmntInstrCodeSrc_ Field prmntInstrCodeSrc to be setted.
*/
public void setPrmntInstrCodeSrc( BigInteger prmntInstrCodeSrc_ )
{
m_prmntInstrCodeSrc = prmntInstrCodeSrc_;
}
/**
* @return Returns prmntInstrInvstCurAcctIndDomain.
*/
public DataSet getPrmntInstrInvstCurAcctIndDomain()
{
return m_prmntInstrInvstCurAcctIndDomain;
}
/**
* @param prmntInstrInvstCurAcctIndDomain_ Field prmntInstrInvstCurAcctIndDomain to be setted.
*/
public void setPrmntInstrInvstCurAcctIndDomain(
DataSet prmntInstrInvstCurAcctIndDomain_ )
{
m_prmntInstrInvstCurAcctIndDomain = prmntInstrInvstCurAcctIndDomain_;
}
/**
* @return Returns prmntInstrInvstCurAcctIndSrc.
*/
public String getPrmntInstrInvstCurAcctIndSrc()
{
return m_prmntInstrInvstCurAcctIndSrc;
}
/**
* @param prmntInstrInvstCurAcctIndSrc_ Field prmntInstrInvstCurAcctIndSrc to be setted.
*/
public void setPrmntInstrInvstCurAcctIndSrc(
String prmntInstrInvstCurAcctIndSrc_ )
{
m_prmntInstrInvstCurAcctIndSrc = prmntInstrInvstCurAcctIndSrc_;
}
/**
* @return Returns selectedCustNbr.
*/
public BigInteger getSelectedCustNbr()
{
return m_selectedCustNbr;
}
/**
* @param selectedCustNbr_ Field selectedCustNbr to be setted.
*/
public void setSelectedCustNbr( BigInteger selectedCustNbr_ )
{
m_selectedCustNbr = selectedCustNbr_;
}
/**
* @return Returns selectedPrmntInstrCode.
*/
public BigInteger getSelectedPrmntInstrCode()
{
return m_selectedPrmntInstrCode;
}
/**
* @param selectedPrmntInstrCode_ Field selectedPrmntInstrCode to be setted.
*/
public void setSelectedPrmntInstrCode( BigInteger selectedPrmntInstrCode_ )
{
m_selectedPrmntInstrCode = selectedPrmntInstrCode_;
}
/**
* @return Returns selectedProdAcctCode.
*/
public BigInteger getSelectedProdAcctCode()
{
return m_selectedProdAcctCode;
}
/**
* @param selectedProdAcctCode_ Field selectedProdAcctCode to be setted.
*/
public void setSelectedProdAcctCode( BigInteger selectedProdAcctCode_ )
{
m_selectedProdAcctCode = selectedProdAcctCode_;
}
/**
* @return Returns selectedProdUnderAcctCode.
*/
public BigInteger getSelectedProdUnderAcctCode()
{
return m_selectedProdUnderAcctCode;
}
/**
* @param selectedProdUnderAcctCode_ Field selectedProdUnderAcctCode to be setted.
*/
public void setSelectedProdUnderAcctCode(
BigInteger selectedProdUnderAcctCode_ )
{
m_selectedProdUnderAcctCode = selectedProdUnderAcctCode_;
}
/**
* @return Returns prmntInstrTextSrc.
*/
public String getPrmntInstrTextSrc()
{
return m_prmntInstrTextSrc;
}
/**
* @param prmntInstrTextSrc_ Field prmntInstrTextSrc to be setted.
*/
public void setPrmntInstrTextSrc( String prmntInstrTextSrc_ )
{
m_prmntInstrTextSrc = prmntInstrTextSrc_;
}
/**
* @return Returns results.
*/
public DataSet getResults()
{
return m_results;
}
/**
* @param results_ Field results to be setted.
*/
public void setResults( DataSet results_ )
{
m_results = results_;
}
}
|
package beans;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import dao.MakalelerDao;
import varliklar.Makaleler;
@ManagedBean
@SessionScoped
public class MakalelerBean implements Serializable, MakalelerDao {
/**
*
*/
private static final long serialVersionUID = 1L;
ArrayList<Makaleler> makalelerListesi;
@Override
public ArrayList<Makaleler> butunMakaleleriGetir() {
makalelerListesi = new ArrayList<Makaleler>();
Connection con;
try {
con = ConnectionManager.getConnection();
String sorgu = "Select * from makaleler";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sorgu);
while (rs.next()) {
Makaleler yenimakale = new Makaleler(rs.getInt("idmakaleler"),
rs.getInt("makale_konu_id"),
rs.getString("makale_baslik"),
rs.getString("makale_icerik"),
rs.getInt("makale_sahip_id"),
rs.getDate("makale_tarih"), rs.getString("makale_link"));
makalelerListesi.add(yenimakale);
}
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Hata: " + e.getMessage());
}
return makalelerListesi;
}
@Override
public String makaleKimeAitseGetir(int idmakaleler) {
String k_adi = null;
try {
Statement statement = ConnectionManager.getConnection()
.createStatement();
String sorgu = "select k_adi from kullanicilar where idkullanicilar = (select makale_sahip_id from makaleler where idmakaleler='"
+ idmakaleler + "')";
ResultSet rs = statement.executeQuery(sorgu);
while (rs.next()) {
k_adi = rs.getString("k_adi");
}
ConnectionManager.getConnection().close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return k_adi;
}
@Override
public Makaleler idliMakaleyiGetir(int idmakaleler) {
Makaleler makale = null;
ConnectionManager.getConnection();
try {
Statement statement = ConnectionManager.getConnection()
.createStatement();
String sorgu = "select * from makaleler where idmakaleler='"
+ idmakaleler + "'";
ResultSet rs = statement.executeQuery(sorgu);
while (rs.next()) {
makale = new Makaleler(rs.getInt("idmakaleler"),
rs.getInt("makale_konu_id"), rs.getString(
"makale_baslik").toUpperCase(),
rs.getString("makale_icerik"),
rs.getInt("makale_sahip_id"),
rs.getDate("makale_tarih"), rs.getString("makale_link"));
}
ConnectionManager.getConnection().close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return makale;
}
}
|
/**
*
*/
package de.mapsmodule.maps.client.model;
import de.smartmirror.smf.client.model.Model;
/**
* @author julianschultehullern
*
*/
public interface MapsModel extends Model {
String getDefaultLocation();
void setDefaultLocation(String defaultLocation);
void setCurrentPlace(String currentPlace);
String getCurrentPlace();
void setNavPlace(String navPlace);
String getNavPlace();
void setZoom(int zoom);
int getZoom();
}
|
package me.bayanov.shapes;
public class Square implements Shape {
private double side;
public Square(double side) {
this.side = side;
}
@Override
public double getWidth() {
return side;
}
@Override
public double getHeight() {
return side;
}
@Override
public double getArea() {
return Math.pow(side, 2);
}
@Override
public double getPerimeter() {
return side * 4;
}
@Override
public String toString() {
return "Square {" + System.lineSeparator() + " side = " + side + System.lineSeparator() + "}";
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Square square = (Square) obj;
return this.side == square.side;
}
@Override
public int hashCode() {
return Double.hashCode(side);
}
}
|
package org.carpark.barrier;
import java.util.Date;
/**
* The test class EntryBarrierTest.
*
* @author Sian Turner
* @version 12/04/05
*/
public class EntryBarrierTest extends junit.framework.TestCase {
private EntryBarrier ent1;
/**
* Default constructor for test class EntryBarrierTest
*/
public EntryBarrierTest() {
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
protected void setUp(){
ent1 = BarrierFactory.getNewEntryBarrier("1");
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
protected void tearDown() {
}
public void testenableBarrier() {
ent1.enableBarrier();
assertEquals(true, ent1.isEnabled());
}
public void testdisableBarrier() {
ent1.disableBarrier();
assertEquals(false, ent1.isEnabled());
}
public void testrequestTicket() {
try {
assertNotNull(ent1.requestTicket());
} catch (BarrierException e) {
e.getMessage();
}
}
public void testRemoveTicket() {
try {
ent1.requestTicket();
ent1.removeTicket();
} catch (BarrierException e) {
e.getMessage();
}
assertEquals(true, ent1.isRaised());
}
public void testpassBarrier() {
try{
ent1.passBarrier();
} catch (BarrierException e) {
e.getMessage();
}
assertEquals(false, ent1.isRaised());
}
public void testGetEnabled() {
assertNotNull(ent1.isEnabled());
}
public void testSetTime() {
Date currtime = new Date();
currtime.setTime(System.currentTimeMillis());
ent1.setTime(currtime);
assertEquals(ent1.getTime(), currtime);
}
public void testGetTime() {
Date currtime = new Date();
currtime.setTime(System.currentTimeMillis());
ent1.setTime(currtime);
assertEquals(currtime, ent1.getTime());
}
public void testGetName() {
assertEquals("1", ent1.getName());
}
}
|
package org.jaxws.util.lang;
import org.apache.commons.lang.StringUtils;
/**
*
* @author chenjianjx
*
*/
public class ClassNameUtils {
/**
* com.sun.Hello => com/sun
*
* @param className
* @return
*/
public static String getRelativeDir(String className) {
int lastIndexOfPoint = className.lastIndexOf(".");
if (lastIndexOfPoint < 0) {
return "";
}
String packageName = className.substring(0, lastIndexOfPoint);
return toRelativeDir(packageName);
}
/**
* com/sun => com.sun
*/
public static String toRelativeDir(String packageName) {
return StringUtils.replace(packageName, ".", "/");
}
/**
* com.sun.Hello => Hello.class
*
* @param className
* @return
*/
public static String toSimpleFileName(String className) {
String simpleClassName = className.substring(className.lastIndexOf(".") + 1);
return simpleClassName + ".class";
}
/**
* com/sun => com.sun
*
* @param relativeDir
* @return
*/
public static String toPackageName(String relativeDir) {
return StringUtils.replace(relativeDir, "/", ".");
}
}
|
package com.lenovohit.hcp.finance.web.rest;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.lenovohit.core.dao.Page;
import com.lenovohit.core.manager.GenericManager;
import com.lenovohit.core.utils.JSONUtils;
import com.lenovohit.core.utils.StringUtils;
import com.lenovohit.core.web.MediaTypes;
import com.lenovohit.core.web.utils.Result;
import com.lenovohit.core.web.utils.ResultUtils;
import com.lenovohit.hcp.base.model.HcpUser;
import com.lenovohit.hcp.base.web.rest.HcpBaseRestController;
import com.lenovohit.hcp.finance.model.OutpatientChargeDetail;
/**
* 收费管理
*/
@RestController
@RequestMapping("/hcp/finance/chargeDetail")
public class OutpatientChargeDetailController extends HcpBaseRestController {
@Autowired
private GenericManager<OutpatientChargeDetail, String> outpatientChargeDetailManager;
/**
* 根据条件查询收费信息
*
* @param start
* @param limit
* @param data
* @return
*/
@RequestMapping(value = "/page/{start}/{limit}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result findPage(@PathVariable("start") String start, @PathVariable("limit") String limit,
@RequestParam(value = "data", defaultValue = "") String data) {
// 取当前用户
HcpUser user = this.getCurrentUser();
Page page = new Page();
page.setStart(start);
page.setPageSize(limit);
OutpatientChargeDetail query = JSONUtils.deserialize(data, OutpatientChargeDetail.class);
StringBuilder jql = new StringBuilder(" from OutpatientChargeDetail ocd where ocd.hosId=? and ocd.drugDept.id = ? ");
List<Object> values = new ArrayList<Object>();
// 医院id
values.add(user.getHosId());
// 取药药房id
values.add(user.getLoginDepartment().getId());
// 取药药房id
/*if (!StringUtils.isEmpty(query.getDrugDeptId())) {
jql.append("and ocd.drugDept.id = ? ");
values.add(query.getDrugDeptId());
}*/
// 申请单状态
if (!StringUtils.isEmpty(query.getApplyState())) {
jql.append("and ocd.applyState = ? ");
values.add(query.getApplyState());
}
// 发票号
if (!StringUtils.isEmpty(query.getInvoiceNo())) {
jql.append("and ocd.invoiceNo like ? ");
values.add("%" + query.getInvoiceNo() + "%");
}
// 患者id
if (!StringUtils.isEmpty(query.getPatientId())) {
jql.append("and ocd.patient.id like ? ");
values.add("%" + query.getPatientId() + "%");
}
// 诊疗卡或医保卡
if (!StringUtils.isEmpty(query.getMedicalCardNo()) || !StringUtils.isEmpty(query.getMiCardNo())
|| !StringUtils.isEmpty(query.getPatientName())) {
jql.append("and ocd.patient.id in (select id from Patient where hosId=? ");
values.add(user.getHosId());
// 诊疗卡
if (!StringUtils.isEmpty(query.getMedicalCardNo())) {
jql.append("and medicalCardNo like ? ");
values.add("%" + query.getMedicalCardNo() + "%");
}
// 医保卡
if (!StringUtils.isEmpty(query.getMiCardNo())) {
jql.append("and miCardNo like ? ");
values.add("%" + query.getMiCardNo() + "%");
}
// 患者姓名
if (!StringUtils.isEmpty(query.getPatientName())) {
jql.append("and name like ? ");
values.add("%" + query.getPatientName() + "%");
}
jql.append(")");
}
page.setQuery(jql.toString());
page.setValues(values.toArray());
outpatientChargeDetailManager.findPage(page);
return ResultUtils.renderPageResult(page);
}
/**
* 根据条件查询收费发票信息
*
* @param start
* @param limit
* @param data
* @return
*/
@RequestMapping(value = "/invoice/page/{start}/{limit}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result findInvoicePage(@PathVariable("start") String start, @PathVariable("limit") String limit,
@RequestParam(value = "data", defaultValue = "") String data) {
// 取当前用户
HcpUser user = this.getCurrentUser();
/*
* Page page = new Page(); page.setStart(start);
* page.setPageSize(limit);
*
* OutpatientChargeDetail query = JSONUtils.deserialize(data,
* OutpatientChargeDetail.class); StringBuilder jql = new StringBuilder(
* "select distinct ocd.invoiceNo, ocd.applyState, ocd.patient.id, " +
* "p.name, p.sex, p.birthday, " +
* "ocd.chargeOper, ocd.chargeTime, ocd.drugDept, " +
* "ri.seeDoc, ri.regTime, ri.feeType, hu.name " +
* "from OutpatientChargeDetail ocd, Patient p, RegInfo ri, HcpUser hu "
* +
* "where ocd.patient.id=p.id and ocd.regId=ri.id and ri.seeDoc=hu.id and ocd.hosId=? "
* ); List<Object> values = new ArrayList<Object>();
* values.add(user.getHosId());
*
* //取药药房id if(!StringUtils.isEmpty(query.getDrugDeptId())){
* jql.append("and ocd.drugDept.id = ? ");
* values.add(query.getDrugDeptId()); } //申请单状态
* if(!StringUtils.isEmpty(query.getApplyState())){
* jql.append("and ocd.applyState = ? ");
* values.add(query.getApplyState()); }
*
* //发票号 if(!StringUtils.isEmpty(query.getInvoiceNo())){
* jql.append("and ocd.invoiceNo like ? "); values.add("%" +
* query.getInvoiceNo() + "%"); }
*
* //患者id if(!StringUtils.isEmpty(query.getPatientId())){
* jql.append("and ocd.patient.id like ? "); values.add("%" +
* query.getPatientId() + "%"); }
*
* //诊疗卡或医保卡 if(!StringUtils.isEmpty(query.getMedicalCardNo()) ||
* !StringUtils.isEmpty(query.getMiCardNo()) ||
* !StringUtils.isEmpty(query.getPatientName())){ jql.
* append("and ocd.patient.id in (select id from Patient where hosId=? "
* ); values.add(user.getHosId()); //诊疗卡
* if(!StringUtils.isEmpty(query.getMedicalCardNo())){
* jql.append("and medicalCardNo like ? "); values.add("%" +
* query.getMedicalCardNo() + "%"); } //医保卡
* if(!StringUtils.isEmpty(query.getMiCardNo())){
* jql.append("and miCardNo like ? "); values.add("%" +
* query.getMiCardNo() + "%"); } //患者姓名
* if(!StringUtils.isEmpty(query.getPatientName())){
* jql.append("and name like ? "); values.add("%" +
* query.getPatientName() + "%"); } jql.append(")"); }
*
* page.setQuery(jql.toString()); page.setValues(values.toArray());
*
* outpatientChargeDetailManager.findPage(page); return
* ResultUtils.renderPageResult(page);
*/
OutpatientChargeDetail query = JSONUtils.deserialize(data, OutpatientChargeDetail.class);
StringBuilder sql = new StringBuilder(
"SELECT DISTINCT ocd.INVOICE_NO, ocd.APPLY_STATE, ocd.PATIENT_ID, p.NAME as PATIENT_NAME, p.SEX, p.BIRTHDAY, "
+ "ocd.CHARGE_OPER, ocd.CHARGE_TIME, ocd.DRUG_DEPT, ri.SEE_DOC, ri.REG_TIME, ri.FEE_TYPE, hu.NAME as DOC_NAME, ri.ID "
+ "FROM OC_CHARGEDETAIL ocd, B_PATIENTINFO p, REG_INFO ri, HCP_USER hu "
+ "WHERE ocd.PATIENT_ID = p.ID AND ocd.REG_ID = ri.ID AND ri.SEE_DOC = hu.ID "
+ "AND ocd.HOS_ID = ? ");
List<Object> values = new ArrayList<Object>();
values.add(user.getHosId());
// 取药药房id
if (!StringUtils.isEmpty(query.getDrugDeptId())) {
sql.append("and ocd.DRUG_DEPT = ? ");
values.add(query.getDrugDeptId().trim());
}
// 申请单状态
if (!StringUtils.isEmpty(query.getApplyState())) {
sql.append("and ocd.APPLY_STATE = ? ");
values.add(query.getApplyState().trim());
}
// 发票号
if (!StringUtils.isEmpty(query.getInvoiceNo())) {
sql.append("and ocd.INVOICE_NO like ? ");
values.add("%" + query.getInvoiceNo().trim() + "%");
}
// 患者id
if (!StringUtils.isEmpty(query.getPatientId())) {
sql.append("and ocd.PATIENT_ID like ? ");
values.add("%" + query.getPatientId().trim() + "%");
}
// 诊疗卡或医保卡
if (!StringUtils.isEmpty(query.getMedicalCardNo()) || !StringUtils.isEmpty(query.getMiCardNo())
|| !StringUtils.isEmpty(query.getPatientName())) {
sql.append("and ocd.PATIENT_ID in (select ID from B_PATIENTINFO where HOS_ID=? ");
values.add(user.getHosId().trim());
// 诊疗卡
if (!StringUtils.isEmpty(query.getMedicalCardNo())) {
sql.append("and MEDICAL_CARD_NO like ? ");
values.add("%" + query.getMedicalCardNo().trim() + "%");
}
// 医保卡
if (!StringUtils.isEmpty(query.getMiCardNo())) {
sql.append("and MI_CARD_NO like ? ");
values.add("%" + query.getMiCardNo().trim() + "%");
}
// 患者姓名
if (!StringUtils.isEmpty(query.getPatientName())) {
sql.append("and NAME like ? ");
values.add("%" + query.getPatientName().trim() + "%");
}
sql.append(") ");
}
sql.append(" ORDER BY ocd.CHARGE_TIME DESC ");
List<Object> result = (List<Object>) this.outpatientChargeDetailManager.findBySql(sql.toString(), values.toArray());
return ResultUtils.renderSuccessResult(result);
}
}
|
package strategydemo;
public interface DiscountStrategy {
public float applyDiscount(float price);
}
|
package dk.webbies.tscreate.analysis.methods.contextSensitive.combined;
import dk.webbies.tscreate.Options;
import dk.webbies.tscreate.analysis.HeapValueFactory;
import dk.webbies.tscreate.analysis.TypeAnalysis;
import dk.webbies.tscreate.analysis.TypeFactory;
import dk.webbies.tscreate.analysis.methods.contextSensitive.mixed.MixedContextSensitiveTypeAnalysis;
import dk.webbies.tscreate.analysis.methods.contextSensitive.pureSubsets.PureSubsetsContextSensitiveTypeAnalysis;
import dk.webbies.tscreate.analysis.unionFind.FunctionNode;
import dk.webbies.tscreate.analysis.unionFind.IncludeNode;
import dk.webbies.tscreate.analysis.unionFind.UnionFindSolver;
import dk.webbies.tscreate.declarationReader.DeclarationParser;
import dk.webbies.tscreate.jsnap.Snap;
import dk.webbies.tscreate.jsnap.classes.LibraryClass;
import dk.webbies.tscreate.paser.AST.AstNode;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by erik1 on 24-02-2016.
*/
@SuppressWarnings("Duplicates")
public class CombinedContextSensitiveTypeAnalysis implements TypeAnalysis {
private final MixedContextSensitiveTypeAnalysis mixed;
private final PureSubsetsContextSensitiveTypeAnalysis subset;
private final TypeFactory typeFactory;
public CombinedContextSensitiveTypeAnalysis(Map<Snap.Obj, LibraryClass> libraryClasses, Options options, Snap.Obj globalObject, DeclarationParser.NativeClassesMap nativeClasses, boolean upperBoundMethod, Map<AstNode, Set<Snap.Obj>> callsites) {
mixed = new MixedContextSensitiveTypeAnalysis(libraryClasses, options, globalObject, nativeClasses, upperBoundMethod, callsites);
subset = new PureSubsetsContextSensitiveTypeAnalysis(libraryClasses, options, globalObject, nativeClasses, callsites);
typeFactory = new CombinerTypeFactory(globalObject, libraryClasses, options, nativeClasses, this);
mixed.typeFactory = typeFactory;
subset.typeFactory = typeFactory;
}
@Override
public void analyseFunctions() {
System.out.println("Running combined, mixed");
mixed.analyseFunctions();
System.out.println("Running combined, subsets");
subset.analyseFunctions();
}
@Override
public TypeFactory getTypeFactory() {
return typeFactory;
}
@Override
public Options getOptions() {
return mixed.getOptions();
}
@Override
public Map<Snap.Obj, LibraryClass> getLibraryClasses() {
return mixed.getLibraryClasses();
}
@Override
public DeclarationParser.NativeClassesMap getNativeClasses() {
return mixed.getNativeClasses();
}
// Just used for getters and setters, not that important.
@Override
public FunctionNode getFunctionNode(Snap.Obj closure) {
FunctionNode mixed = this.mixed.getFunctionNode(closure);
FunctionNode subset = this.subset.getFunctionNode(closure);
if (mixed == null && subset == null) {
return null;
}
if (mixed == null) {
return subset;
}
if (subset == null) {
return mixed;
}
UnionFindSolver solver = this.mixed.solver;
FunctionNode result = FunctionNode.create(closure, solver);
solver.union(result.thisNode, new IncludeNode(solver, mixed.thisNode, subset.thisNode));
solver.union(result.returnNode, new IncludeNode(solver, mixed.returnNode, subset.returnNode));
for (int i = 0; i < result.arguments.size(); i++) {
solver.union(result.arguments.get(i), new IncludeNode(solver, mixed.arguments.get(i), subset.arguments.get(i)));
}
return result;
}
@Override
public HeapValueFactory getHeapFactory() {
return mixed.getHeapFactory();
}
@Override
public UnionFindSolver getSolver() {
return mixed.solver;
}
@Override
public Snap.Obj getGlobalObject() {
return mixed.getGlobalObject();
}
}
|
package yahoofinance;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import java.util.logging.Level;
/**
*
* @author Stijn Strickx
*/
public class Utils {
public static String join(String[] data, String d) {
if (data.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
int i;
for (i = 0; i < (data.length - 1); i++) {
sb.append(data[i]).append(d);
}
return sb.append(data[i]).toString();
}
private static String cleanNumberString(String data) {
return Utils.join(data.trim().split(","), "");
}
private static boolean isParseable(String data) {
return !(data == null || data.equals("N/A") || data.equals("-") || data.equals(""));
}
public static double getDouble(String data) {
double result = 0.00;
if (!Utils.isParseable(data)) {
return result;
}
try {
data = Utils.cleanNumberString(data);
char lastChar = data.charAt(data.length() - 1);
int multiplier = 1;
switch (lastChar) {
case 'B':
data = data.substring(0, data.length() - 1);
multiplier = 1000000000;
break;
case 'M':
data = data.substring(0, data.length() - 1);
multiplier = 1000000;
break;
}
result = Double.parseDouble(data) * multiplier;
} catch (NumberFormatException e) {
YahooFinance.logger.log(Level.INFO, "Failed to parse: " + data, e);
}
return result;
}
public static int getInt(String data) {
int result = 0;
if (!Utils.isParseable(data)) {
return result;
}
try {
data = Utils.cleanNumberString(data);
result = Integer.parseInt(data);
} catch (NumberFormatException e) {
YahooFinance.logger.log(Level.INFO, "Failed to parse: " + data, e);
}
return result;
}
public static long getLong(String data) {
long result = 0;
if (!Utils.isParseable(data)) {
return result;
}
try {
data = Utils.cleanNumberString(data);
result = Long.parseLong(data);
} catch (NumberFormatException e) {
YahooFinance.logger.log(Level.INFO, "Failed to parse: " + data, e);
}
return result;
}
public static double getPercent(double numerator, double denominator) {
if(denominator == 0) {
return 0;
}
return numerator / denominator;
}
private static String getDividendDateFormat(String date) {
if(date.matches("[0-9][0-9]-...-[0-9][0-9]")) {
return "dd-MMM-yy";
} else {
return "MMM d";
}
}
/**
* Used to parse the dividend dates.
* Returns null if the date cannot be parsed.
*
* @param date String received that represents the date
* @return Calendar object representing the parsed date
*/
public static Calendar parseDividendDate(String date) {
if (!Utils.isParseable(date)) {
return null;
}
SimpleDateFormat format = new SimpleDateFormat(Utils.getDividendDateFormat(date));
format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE));
try {
Calendar today = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));
Calendar parsedDate = Calendar.getInstance(TimeZone.getTimeZone(YahooFinance.TIMEZONE));
parsedDate.setTime(format.parse(date));
if(parsedDate.get(Calendar.YEAR) == 1970) {
parsedDate.set(Calendar.YEAR, today.get(Calendar.YEAR));
}
return parsedDate;
} catch(ParseException ex) {
YahooFinance.logger.log(Level.SEVERE, ex.getMessage(), ex);
return null;
}
}
/**
* Used to parse the last trade date / time.
* Returns null if the date / time cannot be parsed.
*
* @param date String received that represents the date
* @param time String received that represents the time
* @return Calendar object with the parsed datetime
*/
public static Calendar parseDateTime(String date, String time) {
String datetime = date + " " + time;
SimpleDateFormat format = new SimpleDateFormat("M/d/yyyy h:mma");
format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE));
try {
if(Utils.isParseable(date) && Utils.isParseable(time)) {
Calendar c = Calendar.getInstance();
c.setTime(format.parse(datetime));
return c;
}
} catch (ParseException ex) {
YahooFinance.logger.log(Level.SEVERE, ex.getMessage(), ex);
}
return null;
}
public static Calendar parseHistDate(String date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setTimeZone(TimeZone.getTimeZone(YahooFinance.TIMEZONE));
try {
if(Utils.isParseable(date)) {
Calendar c = Calendar.getInstance();
c.setTime(format.parse(date));
return c;
}
} catch (ParseException ex) {
YahooFinance.logger.log(Level.SEVERE, ex.getMessage(), ex);
}
return null;
}
public static String getURLParameters(Map<String, String> params) {
StringBuilder sb = new StringBuilder();
for(Entry<String, String> entry : params.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
String key = entry.getKey();
String value = entry.getValue();
try {
key = URLEncoder.encode(key, "UTF-8");
value = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException ex) {
YahooFinance.logger.log(Level.SEVERE, ex.getMessage(), ex);
// Still try to continue with unencoded values
}
sb.append(String.format("%s=%s", key, value));
}
return sb.toString();
}
/**
* Strips the unwanted chars from a line returned in the CSV
* Used for parsing the FX CSV lines
*
* @param line the original CSV line
* @return the stripped line
*/
public static String stripOverhead(String line) {
return line.replaceAll("\"", "");
}
public static String unescape(String data) {
StringBuilder buffer = new StringBuilder(data.length());
for (int i = 0; i < data.length(); i++) {
if ((int) data.charAt(i) > 256) {
buffer.append("\\u").append(Integer.toHexString((int) data.charAt(i)));
} else {
if (data.charAt(i) == '\n') {
buffer.append("\\n");
} else if (data.charAt(i) == '\t') {
buffer.append("\\t");
} else if (data.charAt(i) == '\r') {
buffer.append("\\r");
} else if (data.charAt(i) == '\b') {
buffer.append("\\b");
} else if (data.charAt(i) == '\f') {
buffer.append("\\f");
} else if (data.charAt(i) == '\'') {
buffer.append("\\'");
} else if (data.charAt(i) == '\"') {
buffer.append("\\\"");
} else if (data.charAt(i) == '\\') {
buffer.append("\\\\");
} else {
buffer.append(data.charAt(i));
}
}
}
return buffer.toString();
}
}
|
package com.wuqiushan.server.QSHttp;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
@WebServlet("/QSHttp/Upload")
public class UploadFileServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取输出流
// OutputStream os=new FileOutputStream("/Users/yyd-wlf/Desktop/"+new Date().getTime() + "1234.zip"); //+file.getOriginalFilename());
OutputStream os=new FileOutputStream("/root/QSHttp/"+new Date().getTime() + "1234.zip"); // 服务器
//获取输入流 CommonsMultipartFile 中可以直接得到文件的流
InputStream is=request.getInputStream();
//循环写入输出流
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) > 0) {
os.write(b, 0, length);
}
os.flush();
os.close();
is.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
|
package com.dmtrdev.monsters.sprites.enemies.golems;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.dmtrdev.monsters.DefenderOfNature;
import com.dmtrdev.monsters.consts.ConstArmor;
import com.dmtrdev.monsters.consts.ConstEnemies;
import com.dmtrdev.monsters.consts.ConstGame;
import com.dmtrdev.monsters.screens.PlayScreen;
import com.dmtrdev.monsters.sprites.armors.bombs.Bomb;
import com.dmtrdev.monsters.sprites.armors.bombs.Grenade;
import com.dmtrdev.monsters.sprites.armors.bombs.SpikeBomb;
import com.dmtrdev.monsters.sprites.armors.medieval.Arrow;
import com.dmtrdev.monsters.sprites.enemies.Enemy;
public class GolemMedium extends Enemy {
public GolemMedium(final PlayScreen pScreen, final float pX, final float pY, final boolean pDirection) {
super(pScreen, pX, pY, pDirection);
if(pScreen.getType().contains(ConstGame.SURVIVE_MODE)){
if(pScreen.getGameGui().getGenerates().getWaveIndex() % 5 == 0) {
hp = (ConstEnemies.GOLEM_MEDIUM_HP / 2) + ((pScreen.getGameGui().getGenerates().getWaveIndex() / 5) * 50);
} else if(pScreen.getGameGui().getGenerates().getWaveIndex() > 4 ){
hp = (ConstEnemies.GOLEM_MEDIUM_HP / 2) + ((int)Math.floor(Math.abs(pScreen.getGameGui().getGenerates().getWaveIndex()/5)) * 50);
} else {
hp = ConstEnemies.GOLEM_MEDIUM_HP / 2;
}
} else {
hp = ConstEnemies.GOLEM_MEDIUM_HP;
}
for (int i = 0; i < 7; i++) {
frames.add(new TextureRegion(DefenderOfNature.getGolemsAtlas().findRegion("golem_medium_run"), 0, i * 263, 339, 263));
runAnimation = new Animation<>(ConstEnemies.GOLEM_ANIM, frames, Animation.PlayMode.LOOP);
}
frames.clear();
for (int j = 0; j < 3; j++) {
for (int i = 0; i < 3; i++) {
if (j == 2 && i == 1) {
break;
}
frames.add(new TextureRegion(DefenderOfNature.getGolemsAtlas().findRegion("golem_medium_attack"), i * 315, j * 312, 315, 312));
attackAnimation = new Animation<>(ConstEnemies.GOLEM_ANIM, frames, Animation.PlayMode.LOOP);
}
}
frames.clear();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 3; j++) {
frames.add(new TextureRegion(DefenderOfNature.getEffectsAtlas().findRegion("skeleton_explode"), j * 233, i * 213, 233, 213));
deathAnimation = new Animation<>(ConstArmor.EFFECT_SPEED, frames, Animation.PlayMode.LOOP);
}
}
frames.clear();
}
@Override
public void damaged(final int pDamage, final String pData) {
hp -= pDamage;
if (hp <= 0) {
setToDestroy = true;
}
}
@Override
public void update(final float delta) {
super.update(delta);
switch (getState()) {
case DIE:
if (effects) {
if (!destroy) {
if (screen.getOptions().getSoundCheck()) {
DefenderOfNature.getDeathBigSound().play(screen.getOptions().getSoundVolume());
}
setPosition(body.getPosition().x - getWidth() / 2, body.getPosition().y + 0.5f);
world.destroyBody(body);
setSize(4.3f, 5);
destroy = true;
time = 0;
coinSpawn = true;
} else if (deathAnimation.isAnimationFinished(time)) {
destroyed = true;
}
setRegion(getFrame());
time += delta;
} else {
world.destroyBody(body);
destroyed = true;
coinSpawn = true;
}
break;
case DISABLE:
body.setLinearVelocity(0, ConstEnemies.VELOCITY_Y);
if (disableTime <= 0) {
disable = false;
}
disableTime -= delta;
if (direction) {
setPosition(body.getPosition().x - getWidth() / 2 - 0.5f, body.getPosition().y - ConstEnemies.GOLEM_HEAD_DIFF_SIZE);
} else {
setPosition(body.getPosition().x - getWidth() / 2 + 0.5f, body.getPosition().y - ConstEnemies.GOLEM_HEAD_DIFF_SIZE);
}
break;
case ATTACK:
setSize(ConstEnemies.GOLEM_SIZE - 1.3f, ConstEnemies.GOLEM_SIZE + 1.5f);
if (attackAnimation.isAnimationFinished(attackTime) && plantAttack) {
attackTime = 0;
} else if (attackAnimation.isAnimationFinished(attackTime) && attack) {
tree.setHp(ConstEnemies.GOLEM_MEDIUM_DAMAGE);
if (tree.getPlayer().getBody().getLinearVelocity().y == 0) {
tree.getPlayer().collision(direction, new Vector2(2, 4));
}
attackTime = 0;
}
if (direction) {
body.setLinearVelocity(0, ConstEnemies.VELOCITY_Y);
setPosition(body.getPosition().x - getWidth() / 2 + 0.4f, body.getPosition().y - ConstEnemies.GOLEM_HEAD_DIFF_SIZE);
} else {
body.setLinearVelocity(0, ConstEnemies.VELOCITY_Y);
setPosition(body.getPosition().x - getWidth() / 2 - 0.4f, body.getPosition().y - ConstEnemies.GOLEM_HEAD_DIFF_SIZE);
}
setRegion(getFrame());
attackTime += delta;
break;
default:
setSize(ConstEnemies.GOLEM_SIZE - 1, ConstEnemies.GOLEM_SIZE);
if (direction) {
body.setLinearVelocity(ConstEnemies.GOLEM_VELOCITY_X, ConstEnemies.VELOCITY_Y);
setPosition(body.getPosition().x - getWidth() / 2 - 0.5f, body.getPosition().y - ConstEnemies.GOLEM_HEAD_DIFF_SIZE);
} else {
body.setLinearVelocity(-ConstEnemies.GOLEM_VELOCITY_X, ConstEnemies.VELOCITY_Y);
setPosition(body.getPosition().x - getWidth() / 2 + 0.5f, body.getPosition().y - ConstEnemies.GOLEM_HEAD_DIFF_SIZE);
}
setRegion(getFrame());
time += delta;
break;
}
}
@Override
public int getEnemyDamage() {
return ConstEnemies.GOLEM_MEDIUM_DAMAGE;
}
@Override
public int getScore() {
return ConstEnemies.GOLEM_MEDIUM_SCORE;
}
@Override
protected void defineEnemy() {
final BodyDef bodyDef = new BodyDef();
bodyDef.position.set(getX(), getY());
bodyDef.type = BodyDef.BodyType.DynamicBody;
body = world.createBody(bodyDef);
final FixtureDef fixtureDef = new FixtureDef();
final CircleShape legs = new CircleShape();
legs.setRadius(ConstEnemies.LEGS_SIZE);
fixtureDef.filter.categoryBits = ConstGame.ENEMY_DOWN_BIT;
fixtureDef.filter.maskBits = ConstGame.DISABLE_BIT | ConstGame.ARMOR_ENEMY_BIT | ConstGame.GROUND_BIT;
fixtureDef.shape = legs;
fixtureDef.density = ConstEnemies.GOLEM_DENSITY;
body.createFixture(fixtureDef).setUserData(this);
final CircleShape corpus = new CircleShape();
corpus.setRadius(getSize(ConstEnemies.GOLEM_BODY_SIZE, ConstEnemies.GOLEM_BODY_DIFF_SIZE));
corpus.setPosition(new Vector2(0, corpus.getRadius() + ConstEnemies.LEGS_SIZE));
fixtureDef.filter.categoryBits = ConstGame.ENEMY_BIT;
fixtureDef.filter.maskBits = ConstGame.ARMOR_BIT | ConstGame.TREE_LOW_BIT | ConstGame.ARMOR_ENEMY_BIT;
fixtureDef.shape = corpus;
fixtureDef.density = ConstEnemies.GOLEM_DENSITY;
body.createFixture(fixtureDef).setUserData(this);
final CircleShape head = new CircleShape();
head.setRadius(getSize(ConstEnemies.GOLEM_HEAD_SIZE, ConstEnemies.GOLEM_HEAD_DIFF_SIZE));
head.setPosition(new Vector2(0, ConstEnemies.LEGS_SIZE + head.getRadius() + corpus.getRadius() * 2));
fixtureDef.filter.categoryBits = ConstGame.ENEMY_BIT;
fixtureDef.filter.maskBits = ConstGame.ARMOR_BIT;
fixtureDef.shape = head;
fixtureDef.density = ConstEnemies.GOLEM_DENSITY;
body.createFixture(fixtureDef).setUserData(this);
body.setFixedRotation(true);
}
}
|
package validation;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.event.EventType;
import javafx.scene.control.Control;
import validation.exceptions.ValidationException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
public abstract class FXAbstractValidator<T extends Control,A extends Annotation> {
protected T control;
protected A annotation;
public FXAbstractValidator(){
}
public FXAbstractValidator(T control,A annotation){
this.control = control;
this.annotation = annotation;
}
protected final BooleanProperty isValid = new SimpleBooleanProperty(false);
protected List<EventType> eventTypes = new ArrayList<>();
public abstract void validate(T control,A annotation) throws ValidationException;
public void validate() throws ValidationException{
this.validate(this.control, this.annotation);
}
public List<EventType> getEventTypes() {
return eventTypes;
}
public BooleanProperty isValidProperty() {
return isValid;
}
public T getControl() {
return control;
}
public void setControl(T control) {
this.control = control;
}
public A getAnnotation() {
return annotation;
}
public void setAnnotation(A annotation) {
this.annotation = annotation;
}
}
|
package cs3500.singleMoveModel;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Tests for APile abstract class.
*/
public class APileTest {
// Tests the toString method.
@Test
public void testToString01() {
Pile cascade = new CascadePile();
cascade.push(new Card(RankType.KING, SuitType.SPADE));
assertEquals("K♠", cascade.toString());
cascade.push(new Card(RankType.KING, SuitType.SPADE));
assertEquals("K♠, K♠", cascade.toString());
}
}
|
package lab7;
public class CS401StackArrayImpl<E> implements CS401StackInterface<E>
{
private int num_elements;
private int max_elements;
private E[] elements;
public CS401StackArrayImpl()
{
max_elements = 10;
num_elements = 0;
elements = (E[]) new Object[max_elements];
}
/**
* Push an element on the stack. If the stack is full, then allocate
* more memory to hold a new stack, copy existing elements to the new
* stack and add the new element to the newly enlarged stack.
* Do not use System.arraycopy(). You are essentially implementing
* what System.arraycopy() will do when you expand an existing array. **/
public void push(E e)
{
/** Add code here **/
if(is_full()) {
grow();
}
elements[num_elements] = e;
num_elements++;
return;
}
public E pop()
{
/** Add code here **/
num_elements--;
E out = elements[num_elements];
elements[num_elements] = null;
return out;
}
public int size()
{
/** Add code here **/
return num_elements;
}
public boolean is_full()
{
if (num_elements == max_elements)
return true;
return false;
}
private boolean grow() {
System.out.println("Growing stack by " + max_elements + " elements");
this.max_elements = max_elements * 2;
E[] temp = (E[])new Object[max_elements];
int i = 0;
for (E element : elements) {
temp[i] = element;
i++;
}
this.elements = temp;
return true;
}
} /* CS401StackArrayImpl<E> */
|
package chess.board;
public class BoardRow {
}
|
package week9.homework;
import week9.homework.classesforserialize.Adress;
import week9.homework.classesforserialize.Person;
import java.util.*;
public class Main {
public static void main(String[] args) {
Serializer jsonSerializerStrategy = new JSONSerializer();
Serializer xmlSerializerStrategy = new XMLSerializer();
SerializerImpl serializerXML = new SerializerImpl();
SerializerImpl serializerJSON = new SerializerImpl();
serializerJSON.setStrategy(jsonSerializerStrategy);
serializerXML.setStrategy(xmlSerializerStrategy);
Adress adress = new Adress("Moscow", 121212);
Person person = new Person("Bob", adress, new String[]{"12121213", "0099900", "77777"});
System.out.println(serializerJSON.serialize(person));
System.out.println(serializerXML.serialize(person));
}
}
|
package commands;
import menus.Menu;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.command.BasicCommand;
import actionEngines.ActionEngine;
import actionEngines.MenuActionEngine;
public class MenuOpenCommand extends BasicCommand implements GenericCommand{
private Menu menu;
public MenuOpenCommand(Menu menu) {
super("Open menu" + menu);
this.menu = menu;
}
@Override
public void execute(ActionEngine actionEngine) {
try {
((MenuActionEngine) actionEngine).openMenu(menu);
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.onightperson.hearken.ipc.messenger;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by liubaozhu on 17/9/3.
*/
public class MessengerService extends Service {
private static final String TAG = "MessengerService";
public static final int MSG_SAY_HELLO = 0;
private Handler messengerHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SAY_HELLO:
Log.i(TAG, "handleMessage: Hello");
break;
}
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new Messenger(messengerHandler).getBinder();
}
}
|
package com.gaoshin.cj.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.gaoshin.cj.dao.AdvertiserDao;
import com.gaoshin.cj.entity.Advertiser;
import com.gaoshin.cj.entity.Link;
@Repository("advertiserDao")
public class AdvertiserDaoImpl extends GenericDaoImpl implements AdvertiserDao {
@Override
public List<Advertiser> getUnfetchedAdvertisers(int size) {
String sql = "select * from Advertiser where status is null limit " + size;
return queryBySql(Advertiser.class, null, sql);
}
@Override
public List<Advertiser> getJoinedAdvertisers() {
String sql = "select * from Advertiser where joined='Yes'";
return queryBySql(Advertiser.class, null, sql);
}
@Override
public List<Link> getLinkList(int offset, int size) {
String sql = "select * from Link where relationshipStatus='joined' limit " + offset + "," + size;
return queryBySql(Link.class, null, sql);
}
}
|
package com.engeto.example;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class Homework2 {
public static void printHomework() {
// 2. Napište program, který přečte soubor (priklad2.txt) a spočítá počet znaků na každém řádku,
// který neobsahuje číslici.
// file loading
try (BufferedReader inputStream = new BufferedReader( new FileReader("resources\\priklad2.txt"));) {
System.out.println("Homework 2");
Stream<String> stream1 = inputStream.lines();
// filtering out lines with numbers and outputting the size of the string
stream1
.filter((value) -> !value.matches(".*\\d.*"))
.forEach((value) -> {
System.out.println(value);
System.out.println( "This line has " + value.length() + " symbols");
System.out.println();
});
System.out.println("-----------------------------------------------");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.qqq.stormy.activity;
import android.app.ListActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.qqq.stormy.R;
import com.qqq.stormy.adapter.DailyAdapter;
import com.qqq.stormy.model.day.DailyData;
import java.util.List;
public class DailyActivity extends ListActivity {
private List<DailyData> mDailyDataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily);
mDailyDataList = getIntent().getParcelableArrayListExtra(MainActivity.DAILY_FORECAST);
Log.v(MainActivity.TAG, "mDailyDataList was successfully received: " + mDailyDataList);
DailyAdapter dailyAdapter = new DailyAdapter(this, mDailyDataList);
setListAdapter(dailyAdapter);
}
}
|
package com.energytrade.app.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* The persistent class for the event_customer_devices database table.
*
*/
@Entity
@Table(name = "event_customer_devices")
@NamedQuery(name = "EventCustomerDevices.findAll", query = "SELECT a FROM EventCustomerDevices a")
public class EventCustomerDevices {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "event_customer_devices_id")
private int eventCustomerDevicesId;
// bi-directional many-to-one association to EventCustomerMapping
@ManyToOne
@JoinColumn(name = "event_customer_mapping")
private EventCustomerMapping eventCustomerMapping;
// bi-directional many-to-one association to UserDrDevice
@ManyToOne
@JoinColumn(name = "user_dr_device")
private UserDRDevices userDrDevice;
@Column(name = "created_by")
private String createdBy;
@Column(name = "updated_by")
private String updatedBy;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_ts")
private Date createdTs;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_ts")
private Date updatedTs;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "sync_ts")
private Date syncTs;
private byte softdeleteflag;
public int getEventCustomerDevicesId() {
return eventCustomerDevicesId;
}
public void setEventCustomerDevicesId(int eventCustomerDevicesId) {
this.eventCustomerDevicesId = eventCustomerDevicesId;
}
public EventCustomerMapping getEventCustomerMapping() {
return eventCustomerMapping;
}
public void setEventCustomerMapping(EventCustomerMapping eventCustomerMapping) {
this.eventCustomerMapping = eventCustomerMapping;
}
public UserDRDevices getUserDrDevice() {
return userDrDevice;
}
public void setUserDrDevice(UserDRDevices userDrDevice) {
this.userDrDevice = userDrDevice;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
public Date getCreatedTs() {
return createdTs;
}
public void setCreatedTs(Date createdTs) {
this.createdTs = createdTs;
}
public Date getUpdatedTs() {
return updatedTs;
}
public void setUpdatedTs(Date updatedTs) {
this.updatedTs = updatedTs;
}
public Date getSyncTs() {
return syncTs;
}
public void setSyncTs(Date syncTs) {
this.syncTs = syncTs;
}
public byte getSoftdeleteflag() {
return softdeleteflag;
}
public void setSoftdeleteflag(byte softdeleteflag) {
this.softdeleteflag = softdeleteflag;
}
}
|
public class Shorty extends Person implements SpecialAction{
public Shorty(String name){
this.setName(name);
System.out.println(this.getName() + " was created");
}
public String appeared(String how){
return this.getName() + " appeared " + how;
}
@Override
public String action() {
return "scattered, hid " + this.getLocation()+ " began to look out the windows";
}
public String heardSomeThing(String someThing){
return this.getName() + " " + someThing;
}
public String laugh(String how){
return this.getName() + " began to laugh " + how;
}
public String seeingSomeThing(String something){
return this.getName() + " are seeing " + something;
}
public String ranOut(){
return this.getName() + " ran out of the houses";
}
public String hug(String who){
return this.getName() + " hug " + who;
}
public String werePleasedWithSomeThing(String how, String something){
return this.getName() + " were " + how + " pleased with " + something;
}
public String presentedSomeBodySomeThing(String someBody, String someThing){
return this.getName() + " presented " + someBody + someThing;
}
}
|
package com.citibank.ods.persistence.pl.dao;
import java.math.BigInteger;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.entity.pl.BaseTplEntryInterColumnEntity;
import com.citibank.ods.entity.pl.BaseTplEntryInterEntity;
/**
* @author m.nakamura
*
* Interface para acesso ao banco de dados de Interface de Entrada.
*/
public interface BaseTplEntryInterDAO
{
/**
* Retorna Data Set com os campos do grid da consulta em lista.
*
* @param entryInterCode_ - Código da interface de entrada.
* @return DataSet - DataSet com os campos do grid da consulta em lista.
*/
public DataSet list( BigInteger entryInterCode_ );
/**
* Retorna o DataSet com os valores existentes de código de tipo de Interface
* de Entrada.
*
* @return DataSet - DataSet com os valores existentes de código de tipo de
* Interface de Entrada.
*/
public DataSet loadEntryTypeCodeDomain();
/**
* Retorna entidade com os valores da tela de detalhe.
*
* @param entryInterCode_ - Código da interface de entrada.
* @param entryTypeCode_ - Código do typo de atributo.
* @param entryInterColumnEntity_ - Entidade com os dados do atributo.
*
* @return BaseTplEntryInterEntity - Entidade com os valores da tela de
* detalhe.
*/
public BaseTplEntryInterEntity find(
BigInteger entryInterCode_,
BigInteger entryTypeCode_,
BaseTplEntryInterColumnEntity entryInterColumnEntity_ );
}
|
package com.classroom.services.domain.model.repositories;
import java.util.List;
import com.classroom.services.domain.model.ExamResults;
import com.classroom.services.domain.model.Exams;
public interface IExamResultsRepository extends IBaseRepository<ExamResults>{
ExamResults getExamResultDetails(Integer studentId);
}
|
package com.interview.microsoft.design.logger;
public interface Logger {
/**
* When a process starts, it calls 'start' with processId and startTime.
*/
void start(String processId, long startTime);
/**
* When the same process ends, it calls 'end' with processId and endTime.
*/
void end(String processId, long endTime);
/**
* Prints the logs of this system sorted by the start time of processes in the
* below format {processId} started at {startTime} and ended at {endTime}
*/
void print();
}
|
package com.example.mdt;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.text.TextUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* requires the permission READ_PHONE_STATE
*/
@SuppressLint("NewApi")
public class DualSimManager {
private String SIM_VARINT = "";
private String telephonyClassName = "";
private SharedPreferences pref;
private int slotNumber_1 = 0;
private int slotNumber_2 = 1;
private String slotName_1 = "null";
private String slotName_2 = "null";
private String[] listofClass;
private String IMEI_1, IMSI_1, NETWORK_TYPE_1, NETWORK_OPERATOR_NAME_1;
private String SIM_OPERATOR_CODE_1;
private String SIM_OPERATOR_NAME_1;
private String SIM_NETWORK_SIGNAL_STRENGTH_1;
private String IMEI_2, IMSI_2, NETWORK_TYPE_2, NETWORK_OPERATOR_NAME_2;
private String SIM_OPERATOR_CODE_2;
private String SIM_OPERATOR_NAME_2;
private String SIM_NETWORK_SIGNAL_STRENGTH_2;
private String NETWORK_OPERATOR_CODE_1, isGPRS_1;
private String NETWORK_OPERATOR_CODE_2, isGPRS_2;
private String SIMSerial_1, SIMSerial_2;
boolean isRoaming_1, isRoaming_2;
private int[] CELL_LOC_1;
private int[] CELL_LOC_2;
public final static String m_IMEI = "getDeviceId";
public final static String m_IMSI = "getSubscriberId";
public final static String m_SIM_OPERATOR_NAME = "getSimOperatorName";
public final static String m_NETWORK_OPERATOR = "getNetworkOperatorName";
public final static String m_NETWORK_OPERATOR_CODE = "getNetworkOperator";
public final static String m_NETWORK_TYPE_NAME = "getNetworkTypeName";
public final static String m_CELL_LOC = "getNeighboringCellInfo";
public final static String m_IS_ROAMING = "isNetworkRoaming";
public final static String m_SIM_SERIAL = "getSimSerialNumber";
public final static String m_SIM_SUBSCRIBER = "getSubscriberId";
public final static String m_SIM_OPERATOR_CODE = "getSimOperator";
public final static String m_DATA_STATE = "getDataNetworkType";
/*
* getDeviceIdGemini , may work for mtk chip
*
* getDeviceIdDs, work for Samsung Duos device
* getSimSerialNumberGemini, work for Lenovo A319
* */
private static String[] deviceIdMethods = {"getDeviceIdGemini", "getDeviceId", "getDeviceIdDs", "getDeviceIdExt"};
/*
* getSimStateGemini , may work for mtk chip
*
* getIccState, work for HTC device
*
* */
private static String[] networkTypeMethods = {"getSimStateGemini", "getSimState", "getIccState"};
/*
* getNetworkTypeGemini , may work for mtk chip
*
* getNetworkTypeExt, work for HTC device
*
* */
private static String[] simStatusMethods = {"getNetworkTypeGemini", "getNetworkType", "getNetworkTypeExt"};
/*
* getNetworkOperatorNameGemini , may work for mtk chip
*
* getNetworkOperatorNameExt, work for HTC device
*
* */
private static String[] networkOperatorNameMethods = {"getNetworkOperatorNameGemini", "getNetworkOperatorName", "getNetworkOperatorNameExt"};
protected static CustomTelephony customTelephony;
public DualSimManager(Context mContext) {
try {
if (IMEI_1 == null) {
customTelephony = new CustomTelephony(mContext);
} else {
customTelephony.getCurrentData();
}
if (customTelephony.getIMEIList().size() > 0) {
customTelephony.getDefaultSIMInfo();
}
updateOperatorDetails(mContext);
} catch (Exception e) {
}
}
private void updateOperatorDetails(Context mContext) {
Editor edit = pref.edit();
if (!TextUtils.isEmpty(this.getmSimOperatorName(0))) {
//MeterPreferences.setStringPrefrence(mContext, LocalConstants.SIM_OPERATOR_1, this.getmSimOperatorName(0));
edit.putString("SIM_OPERATOR_1", this.getmSimOperatorName(0));
}
if (!TextUtils.isEmpty(this.getmSimOperatorName(1))) {
//MeterPreferences.setStringPrefrence(mContext, LocalConstants.SIM_OPERATOR_2, this.getmSimOperatorName(1));
edit.putString("SIM_OPERATOR_2", this.getmSimOperatorName(1));
}
if (!TextUtils.isEmpty(this.getNETWORK_OPERATOR_NAME(0))) {
//MeterPreferences.setStringPrefrence(mContext, LocalConstants.NETWORK_OPERATOR_1, this.getNETWORK_OPERATOR_NAME(0));
edit.putString("NETWORK_OPERATOR_1", this.getNETWORK_OPERATOR_NAME(0));
}
if (!TextUtils.isEmpty(this.getNETWORK_OPERATOR_NAME(1))) {
//MeterPreferences.setStringPrefrence(mContext, LocalConstants.NETWORK_OPERATOR_2, this.getNETWORK_OPERATOR_NAME(1));
edit.putString("NETWORK_OPERATOR_2", this.getNETWORK_OPERATOR_NAME(1));
}
//MeterPreferences.putInt(mContext, LocalConstants.SIM_SUPPORTED_COUNT, this.getSupportedSimCount());
edit.putInt("SIM_SUPPORTED_COUNT", this.getSupportedSimCount());
}
public boolean isSIMSupported() {
if (!TextUtils.isEmpty(IMEI_1) || !TextUtils.isEmpty(IMEI_2)) {
return true;
} else {
return false;
}
}
public boolean isDualSIMSupported() {
if (!TextUtils.isEmpty(IMEI_1) && !TextUtils.isEmpty(IMEI_2) && !(IMEI_1.equals(IMEI_2))) {
return true;
} else {
return false;
}
}
public boolean isFirstSimActive() {
if (IMSI_1 == null || TextUtils.isEmpty(IMSI_1)) {
return false;
} else {
return true;
}
}
public boolean isSecondSimActive() {
if (IMSI_2 == null || TextUtils.isEmpty(IMSI_2)) {
return false;
} else if (IMSI_1 != null && IMSI_1.equalsIgnoreCase(IMSI_2)) {
return false;
} else {
return true;
}
}
public int getSupportedSimCount() {
if (isSIMSupported()) {
if (isDualSIMSupported()) {
return 2;
} else {
return 1;
}
} else {
return 0;
}
}
public String getIMEI(int slotnumber) {
if (slotnumber == 0)
return IMEI_1;
else
return IMEI_2;
}
public String getIMSI(int slotnumber) {
if (slotnumber == 0)
return IMSI_1;
else
return IMSI_2;
}
public String getNETWORK_OPERATOR_NAME(int slotnumber) {
//return NETWORK_OPERATOR_NAME_1;
if (slotnumber == 0)
return NETWORK_OPERATOR_NAME_1;
else {
return NETWORK_OPERATOR_NAME_2;
}
}
public String getmSimOperatorCode(int slotnumber) {
if (slotnumber == 0)
return SIM_OPERATOR_CODE_1;
else
return SIM_OPERATOR_CODE_2;
}
public String getmSimOperatorName(int slotnumber) {
if (slotnumber == 0)
return SIM_OPERATOR_NAME_1;
else
return SIM_OPERATOR_NAME_2;
}
public static String getmSimSubscriber() {
return m_SIM_SUBSCRIBER;
}
public static String getmSimSerial() {
return m_SIM_SERIAL;
}
public String getSIM_NETWORK_SIGNAL_STRENGTH(int slotnumber) {
if (slotnumber == 0)
return SIM_NETWORK_SIGNAL_STRENGTH_1;
else
return SIM_NETWORK_SIGNAL_STRENGTH_2;
}
public boolean isGPRS(int slotnumber) {
boolean isGPRS = false;
try {
String GPRS_FLAG = isGPRS_1;
if (slotnumber == 1) {
GPRS_FLAG = isGPRS_2;
}
int gprsInt = Integer.parseInt(GPRS_FLAG);
if (gprsInt == TelephonyManager.DATA_CONNECTING || gprsInt == TelephonyManager.DATA_CONNECTED) {
isGPRS = true;
}
} catch (Exception e) {
// TODO: handle exception
}
return isGPRS;
}
public void setSIM_NETWORK_SIGNAL_STRENGTH_1(
String sIM_NETWORK_SIGNAL_STRENGTH_1) {
SIM_NETWORK_SIGNAL_STRENGTH_1 = sIM_NETWORK_SIGNAL_STRENGTH_1;
}
public int getSIM_CELLID(int slotnumber) {
if (slotnumber == 0)
return CELL_LOC_1[0];
else
return CELL_LOC_2[0];
}
public int getSIM_LOCID(int slotnumber) {
if (slotnumber == 0)
return CELL_LOC_1[1];
else
return CELL_LOC_2[1];
}
public String getNETWORK_TYPE(int slotnumber) {
if (slotnumber == 0)
return NETWORK_TYPE_1;
else
return NETWORK_TYPE_2;
}
public int[] getNETWORK_OPERATOR_CODE(int slotnumber) {
int OperatorCode[] = new int[2];
String code = NETWORK_OPERATOR_CODE_1;
if (slotnumber == 0)
if (TextUtils.isEmpty(NETWORK_OPERATOR_CODE_1) && !TextUtils.isEmpty(SIM_OPERATOR_CODE_1)) {
code = SIM_OPERATOR_CODE_1;
} else {
code = NETWORK_OPERATOR_CODE_1;
}
else {
if (TextUtils.isEmpty(NETWORK_OPERATOR_CODE_2) && !TextUtils.isEmpty(SIM_OPERATOR_CODE_2)) {
code = SIM_OPERATOR_CODE_2;
} else {
code = NETWORK_OPERATOR_CODE_2;
}
}
/*if(slotnumber==1){
code = NETWORK_OPERATOR_CODE_2;
}*/
OperatorCode[0] = -1;
OperatorCode[1] = -1;
try {
if (code != null) {
OperatorCode[0] = Integer.parseInt(code.substring(0, 3));
OperatorCode[1] = Integer.parseInt(code.substring(3));
}
} catch (Exception e) {
}
return OperatorCode;
}
public boolean isRoaming(int slotnumber) {
if (slotnumber == 0) {
return isRoaming_1;
} else {
return isRoaming_2;
}
}
class CustomTelephony {
Context mContext;
TelephonyManager telephony;
public CustomTelephony(Context mContext) {
try {
this.mContext = mContext;
telephony = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
pref = PreferenceManager.getDefaultSharedPreferences(mContext);
telephonyClassName = pref.getString("dualsim_telephonycls", "");
SIM_VARINT = pref.getString("SIM_VARINT", "");
slotName_1 = pref.getString("SIM_SLOT_NAME_1", "");
slotName_2 = pref.getString("SIM_SLOT_NAME_2", "");
slotNumber_1 = pref.getInt("SIM_SLOT_NUMBER_1", 0);
slotNumber_2 = pref.getInt("SIM_SLOT_NUMBER_2", 1);
fetchClassInfo();
if (telephonyClassName.equalsIgnoreCase("")) {
fetchClassInfo();
} else if (!isValidMethod(telephonyClassName)) {
fetchClassInfo();
}
gettingAllMethodValues();
} catch (Exception e) {
//e.printStackTrace();
}
}
/**
* This method returns the class name in which we fetch dual sim details
*/
public void fetchClassInfo() {
try {
telephonyClassName = "android.telephony.TelephonyManager";
listofClass = new String[]{
"com.mediatek.telephony.TelephonyManagerEx",
"android.telephony.TelephonyManager",
"android.telephony.MSimTelephonyManager",
"com.android.internal.telephony.Phone",
"com.android.internal.telephony.PhoneFactory",
"com.lge.telephony.msim.LGMSimTelephonyManager",
"com.asus.telephony.AsusTelephonyManager",
"com.htc.telephony.HtcTelephonyManager"};
for (int index = 0; index < listofClass.length; index++) {
if (isTelephonyClassExists(listofClass[index])) {
for (String deviceIdMethod : deviceIdMethods) {
if (isMethodExists(listofClass[index], deviceIdMethod)) {
//System.out.println("getDeviceId method found");
if (!SIM_VARINT.equalsIgnoreCase("")) {
break;
}
}
}
for (String networkOperatorNameMethod : networkOperatorNameMethods) {
if (isMethodExists(listofClass[index], networkOperatorNameMethod)){
//System.out.println("getNetworkOperatorName method found");
if (!SIM_VARINT.equalsIgnoreCase("")) {
break;
}
}
}
// if (isMethodExists(listofClass[index], "getNetworkOperatorName") ||
// isMethodExists(listofClass[index], "getNetworkOperatorNameGemini") ||
// isMethodExists(listofClass[index], "getNetworkOperatorNameExt")) {
// /*System.out
// .println("getNetworkOperatorName method found");*/
// break;
// } else if (isMethodExists(listofClass[index],
// "getSimOperatorName") || isMethodExists(listofClass[index],
// "getSimOperatorNameGemini")) {
// /*System.out.println("getSimOperatorName method found");*/
// break;
// }
}
}
for (int index = 0; index < listofClass.length; index++) {
try {
if (slotName_1 == null || slotName_1.equalsIgnoreCase("")) {
getValidSlotFields(listofClass[index]);
// if(slotName_1!=null || !slotName_1.equalsIgnoreCase("")){
getSlotNumber(listofClass[index]);
} else {
break;
}
} catch (Exception e) {
//e.printStackTrace();
}
}
Editor edit = pref.edit();
edit.putString("dualsim_telephonycls", telephonyClassName);
edit.putString("SIM_VARINT", SIM_VARINT);
edit.putString("SIM_SLOT_NAME_1", slotName_1);
edit.putString("SIM_SLOT_NAME_2", slotName_2);
edit.putInt("SIM_SLOT_NUMBER_1", slotNumber_1);
edit.putInt("SIM_SLOT_NUMBER_2", slotNumber_2);
edit.commit();
} catch (Exception e) {
//e.printStackTrace();
}
}
/**
* Check Method is found in class
*/
public boolean isValidMethod(String className) {
boolean isValidMail = false;
try {
if (isMethodExists(className, "getDeviceId")) {
isValidMail = true;
} else if (isMethodExists(className, "getNetworkOperatorName")) {
isValidMail = true;
} else if (isMethodExists(className, "getSimOperatorName")) {
isValidMail = true;
}
} catch (Exception e) {
//e.printStackTrace();
}
return isValidMail;
}
public String getMethodValue(String className, String compairMethod, int slotNumber_1) {
String value = "";
try {
Class<?> telephonyClass = Class.forName(className);
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
StringBuffer sbf = new StringBuffer();
Method[] methodList = telephonyClass.getDeclaredMethods();
for (int index = methodList.length - 1; index >= 0; index--) {
sbf.append("\n\n" + methodList[index].getName());
if (methodList[index].getReturnType().equals(String.class)) {
String methodName = methodList[index].getName();
if (methodName.contains(compairMethod)) {
Class<?>[] param = methodList[index]
.getParameterTypes();
if (param.length > 0) {
if (param[0].equals(int.class)) {
try {
SIM_VARINT = methodName.substring(
compairMethod.length(),
methodName.length());
if (!methodName.equalsIgnoreCase(compairMethod + "Name") && !methodName.equalsIgnoreCase(compairMethod + "ForSubscription")) {
value = invokeMethod(telephonyClassName, slotNumber_1, compairMethod, SIM_VARINT);
if (!TextUtils.isEmpty(value)) {
break;
}
}
} catch (Exception e) {
//e.printStackTrace();
}
} else if (param[0].equals(long.class)) {
try {
SIM_VARINT = methodName.substring(
compairMethod.length(),
methodName.length());
if (!methodName.equalsIgnoreCase(compairMethod + "Name") && !methodName.equalsIgnoreCase(compairMethod + "ForSubscription")) {
value = invokeLongMethod(telephonyClassName, slotNumber_1, compairMethod, SIM_VARINT);
if (!TextUtils.isEmpty(value)) {
break;
}
}
} catch (Exception e) {
//e.printStackTrace();
}
}
}
}
}
}
} catch (Exception e) {
//e.printStackTrace();
}
return value;
}
/**
* Check method with sim variant
*/
public boolean isMethodExists(String className, String compairMethod) {
boolean isExists = false;
try {
Class<?> telephonyClass = Class.forName(className);
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
StringBuffer sbf = new StringBuffer();
Method[] methodList = telephonyClass.getDeclaredMethods();
for (int index = methodList.length - 1; index >= 0; index--) {
sbf.append("\n\n" + methodList[index].getName());
if (methodList[index].getReturnType().equals(String.class)) {
String methodName = methodList[index].getName();
if (methodName.contains(compairMethod)) {
Class<?>[] param = methodList[index]
.getParameterTypes();
if (param.length > 0) {
if (param[0].equals(int.class)) {
try {
SIM_VARINT = methodName.substring(
compairMethod.length(),
methodName.length());
telephonyClassName = className;
isExists = true;
break;
} catch (Exception e) {
//e.printStackTrace();
}
} else {
telephonyClassName = className;
isExists = true;
}
}
}
}
}
} catch (Exception e) {
//e.printStackTrace();
}
return isExists;
}
public ArrayList<String> getIMSIList() {
ArrayList<String> imeiList = new ArrayList<>();
IMSI_1 = invokeMethod(telephonyClassName, slotNumber_1, m_IMSI, SIM_VARINT);
if (TextUtils.isEmpty(IMSI_1)) {
IMSI_1 = getMethodValue(telephonyClassName, m_IMSI, slotNumber_1);
}
if (IMSI_1 == null || IMSI_1.equalsIgnoreCase("")) {
IMSI_1 = telephony.getSubscriberId();
}
IMSI_2 = invokeMethod(telephonyClassName, slotNumber_2, m_IMSI, SIM_VARINT);
if (TextUtils.isEmpty(IMSI_2)) {
IMSI_2 = getMethodValue(telephonyClassName, m_IMSI, slotNumber_2);
if (TextUtils.isEmpty(IMSI_2)) {
IMSI_2 = getMethodValue(telephonyClassName, m_IMSI, slotNumber_2 + 1);
}
}
if (!TextUtils.isEmpty(IMSI_2) && !TextUtils.isEmpty(IMSI_1)) {
if (IMSI_1.equalsIgnoreCase(IMSI_2)) {
IMSI_1 = "";
}
}
if (IMSI_1 != null && IMSI_2 != null && IMSI_1.equalsIgnoreCase("")) {
String IMSI2 = getMethodValue(telephonyClassName, m_IMSI, slotNumber_2 + 1);
if (!TextUtils.isEmpty(IMSI2)) {
Editor edit = pref.edit();
edit.putString("SIM_SLOT_NAME_1", slotName_1);
edit.putString("SIM_SLOT_NAME_2", slotName_2);
IMSI_1 = IMSI_2;
IMSI_2 = IMSI2;
slotNumber_1 = slotNumber_2;
slotNumber_2 = slotNumber_2 + 1;
}
}
if (!TextUtils.isEmpty(IMSI_1)) {
imeiList.add(IMSI_1);
}
if (!TextUtils.isEmpty(IMSI_2)) {
imeiList.add(IMSI_2);
}
return imeiList;
}
public ArrayList<String> getIMEIList() {
ArrayList<String> imeiList = new ArrayList<>();
try {
IMEI_1 = invokeMethod(telephonyClassName, slotNumber_1, m_IMEI, SIM_VARINT);
if (TextUtils.isEmpty(IMEI_1)) {
IMEI_1 = getMethodValue(telephonyClassName, m_IMEI, slotNumber_1);
}
if (IMEI_1 == null || IMEI_1.equalsIgnoreCase("")) {
IMEI_1 = telephony.getDeviceId();
}
IMEI_2 = invokeMethod(telephonyClassName, slotNumber_2, m_IMEI, SIM_VARINT);
if (TextUtils.isEmpty(IMEI_2)) {
IMEI_2 = getMethodValue(telephonyClassName, m_IMEI, slotNumber_1);
}
} catch (Exception e) {
// TODO: handle exception
}
if (!TextUtils.isEmpty(IMEI_2)) {
imeiList.add(IMEI_1);
}
if (!TextUtils.isEmpty(IMEI_2)) {
imeiList.add(IMEI_2);
}
return imeiList;
}
public void getDefaultSIMInfo() {
telephony = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
String IMSI = telephony.getSubscriberId();
if (TextUtils.isEmpty(IMSI_1) || IMSI_1.equalsIgnoreCase(IMSI)) {
IMEI_1 = telephony.getDeviceId();
isGPRS_1 = String.valueOf(telephony.isNetworkRoaming());
SIM_OPERATOR_CODE_1 = telephony.getSimOperator();
SIM_OPERATOR_NAME_1 = telephony.getSimOperatorName();
NETWORK_OPERATOR_CODE_1 = telephony.getNetworkOperator();
NETWORK_OPERATOR_NAME_1 = telephony.getNetworkOperatorName();
NETWORK_TYPE_1 = getNetworkTypeName(telephony.getNetworkType());
} else if (isSecondSimActive() && IMSI_2.equalsIgnoreCase(IMSI)) {
IMEI_2 = telephony.getDeviceId();
isGPRS_2 = String.valueOf(telephony.isNetworkRoaming());
SIM_OPERATOR_CODE_2 = telephony.getSimOperator();
SIM_OPERATOR_NAME_2 = telephony.getSimOperatorName();
NETWORK_OPERATOR_CODE_2 = telephony.getNetworkOperator();
NETWORK_OPERATOR_NAME_2 = telephony.getNetworkOperatorName();
NETWORK_TYPE_2 = getNetworkTypeName(telephony.getNetworkType());
}
}
public String getNetworkTypeName(int type) {
switch (type) {
case TelephonyManager.NETWORK_TYPE_GPRS:
return "GPRS";
case TelephonyManager.NETWORK_TYPE_EDGE:
return "EDGE";
case TelephonyManager.NETWORK_TYPE_UMTS:
return "UMTS";
case TelephonyManager.NETWORK_TYPE_HSDPA:
return "HSDPA";
case TelephonyManager.NETWORK_TYPE_HSUPA:
return "HSUPA";
case TelephonyManager.NETWORK_TYPE_HSPA:
return "HSPA";
case TelephonyManager.NETWORK_TYPE_CDMA:
return "CDMA";
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return "CDMA - EvDo rev. 0";
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return "CDMA - EvDo rev. A";
case TelephonyManager.NETWORK_TYPE_EVDO_B:
return "CDMA - EvDo rev. B";
case TelephonyManager.NETWORK_TYPE_1xRTT:
return "CDMA - 1xRTT";
case TelephonyManager.NETWORK_TYPE_LTE:
return "LTE";
case TelephonyManager.NETWORK_TYPE_EHRPD:
return "CDMA - eHRPD";
case TelephonyManager.NETWORK_TYPE_IDEN:
return "iDEN";
case TelephonyManager.NETWORK_TYPE_HSPAP:
return "HSPA+";
default:
return "UNKNOWN";
}
}
public void gettingAllMethodValues() {
try {
IMEI_1 = invokeMethod(telephonyClassName, slotNumber_1, m_IMEI, SIM_VARINT);
if (TextUtils.isEmpty(IMEI_1)) {
IMEI_1 = getMethodValue(telephonyClassName, m_IMEI, slotNumber_1);
}
if (IMEI_1 == null || IMEI_1.equalsIgnoreCase("")) {
IMEI_1 = telephony.getDeviceId();
}
IMEI_2 = invokeMethod(telephonyClassName, slotNumber_2, m_IMEI, SIM_VARINT);
if (TextUtils.isEmpty(IMEI_2)) {
IMEI_2 = getMethodValue(telephonyClassName, m_IMEI, slotNumber_1);
}
IMSI_1 = invokeMethod(telephonyClassName, slotNumber_1, m_IMSI, SIM_VARINT);
if (TextUtils.isEmpty(IMSI_1)) {
IMSI_1 = getMethodValue(telephonyClassName, m_IMSI, slotNumber_1);
}
if (IMSI_1 == null || IMSI_1.equalsIgnoreCase("")) {
IMSI_1 = telephony.getSubscriberId();
}
IMSI_2 = invokeMethod(telephonyClassName, slotNumber_2, m_IMSI, SIM_VARINT);
if (TextUtils.isEmpty(IMSI_2)) {
IMSI_2 = getMethodValue(telephonyClassName, m_IMSI, slotNumber_2);
if (TextUtils.isEmpty(IMSI_2)) {
IMSI_2 = getMethodValue(telephonyClassName, m_IMSI, slotNumber_2 + 1);
}
}
if (!TextUtils.isEmpty(IMSI_2) && !TextUtils.isEmpty(IMSI_1)) {
if (IMSI_1.equalsIgnoreCase(IMSI_2)) {
IMSI_1 = "";
}
}
if (IMSI_1 != null && IMSI_2 != null && IMSI_1.equalsIgnoreCase("")) {
String IMSI2 = getMethodValue(telephonyClassName, m_IMSI, slotNumber_2 + 1);
if (!TextUtils.isEmpty(IMSI2)) {
Editor edit = pref.edit();
edit.putString("SIM_SLOT_NAME_1", slotName_1);
edit.putString("SIM_SLOT_NAME_2", slotName_2);
IMSI_1 = IMSI_2;
IMSI_2 = IMSI2;
slotNumber_1 = slotNumber_2;
slotNumber_2 = slotNumber_2 + 1;
}
}
SIM_OPERATOR_NAME_1 = getMethodValue(telephonyClassName, m_SIM_OPERATOR_NAME, 0);
SIM_OPERATOR_NAME_2 = getMethodValue(telephonyClassName, m_SIM_OPERATOR_NAME, 1);
if (TextUtils.isEmpty(SIM_OPERATOR_NAME_1))
SIM_OPERATOR_NAME_1 = invokeMethod(telephonyClassName, slotNumber_1, m_SIM_OPERATOR_NAME, SIM_VARINT);
if (TextUtils.isEmpty(SIM_OPERATOR_NAME_1)) {
SIM_OPERATOR_NAME_1 = getMethodValue(telephonyClassName, m_SIM_OPERATOR_NAME, slotNumber_1);
}
if (TextUtils.isEmpty(SIM_OPERATOR_NAME_2))
SIM_OPERATOR_NAME_2 = invokeMethod(telephonyClassName, slotNumber_2, m_SIM_OPERATOR_NAME, SIM_VARINT);
if (TextUtils.isEmpty(SIM_OPERATOR_NAME_2)) {
SIM_OPERATOR_NAME_2 = getMethodValue(telephonyClassName, m_SIM_OPERATOR_NAME, slotNumber_2);
}
SIM_OPERATOR_CODE_1 = invokeMethod(telephonyClassName, slotNumber_1, m_SIM_OPERATOR_CODE, SIM_VARINT);
if (TextUtils.isEmpty(SIM_OPERATOR_CODE_1)) {
SIM_OPERATOR_CODE_1 = getMethodValue(telephonyClassName, m_SIM_OPERATOR_CODE, slotNumber_1);
}
SIM_OPERATOR_CODE_2 = invokeMethod(telephonyClassName, slotNumber_2, m_SIM_OPERATOR_CODE, SIM_VARINT);
NETWORK_OPERATOR_NAME_1 = getMethodValue(telephonyClassName, m_NETWORK_OPERATOR, 0);
NETWORK_OPERATOR_NAME_2 = getMethodValue(telephonyClassName, m_NETWORK_OPERATOR, 1);
if (TextUtils.isEmpty(NETWORK_OPERATOR_NAME_1))
NETWORK_OPERATOR_NAME_1 = invokeMethod(telephonyClassName, slotNumber_1, m_NETWORK_OPERATOR, SIM_VARINT);
if (TextUtils.isEmpty(NETWORK_OPERATOR_NAME_1)) {
NETWORK_OPERATOR_NAME_1 = getMethodValue(telephonyClassName, m_NETWORK_OPERATOR, slotNumber_1);
}
if (TextUtils.isEmpty(NETWORK_OPERATOR_NAME_2))
NETWORK_OPERATOR_NAME_2 = invokeMethod(telephonyClassName, slotNumber_2, m_NETWORK_OPERATOR_CODE, SIM_VARINT);
if (TextUtils.isEmpty(NETWORK_OPERATOR_NAME_2)) {
NETWORK_OPERATOR_NAME_2 = getMethodValue(telephonyClassName, m_NETWORK_OPERATOR_CODE, slotNumber_2);
}
if (NETWORK_OPERATOR_NAME_1.equalsIgnoreCase(""))
NETWORK_OPERATOR_NAME_1 = invokeMethod(telephonyClassName, slotNumber_1, m_NETWORK_OPERATOR, SIM_VARINT);
if (NETWORK_OPERATOR_NAME_2.equalsIgnoreCase(""))
NETWORK_OPERATOR_NAME_2 = invokeMethod(telephonyClassName, slotNumber_2, m_NETWORK_OPERATOR, SIM_VARINT);
if (TextUtils.isEmpty(NETWORK_OPERATOR_CODE_1)) {
NETWORK_OPERATOR_NAME_1 = getMethodValue(telephonyClassName, m_NETWORK_OPERATOR, slotNumber_1);
}
if (TextUtils.isEmpty(NETWORK_OPERATOR_CODE_1)) {
NETWORK_OPERATOR_NAME_2 = getMethodValue(telephonyClassName, m_NETWORK_OPERATOR, slotNumber_2);
}
NETWORK_OPERATOR_CODE_1 = getMethodValue(telephonyClassName, m_NETWORK_OPERATOR_CODE, 0);
NETWORK_OPERATOR_CODE_2 = getMethodValue(telephonyClassName, m_NETWORK_OPERATOR_CODE, 1);
if (TextUtils.isEmpty(NETWORK_OPERATOR_CODE_1))
NETWORK_OPERATOR_CODE_1 = invokeMethod(telephonyClassName, slotNumber_1, m_NETWORK_OPERATOR_CODE, SIM_VARINT);
if (TextUtils.isEmpty(NETWORK_OPERATOR_CODE_1)) {
NETWORK_OPERATOR_CODE_1 = getMethodValue(telephonyClassName, m_NETWORK_OPERATOR_CODE, slotNumber_1);
}
if (TextUtils.isEmpty(NETWORK_OPERATOR_CODE_2))
NETWORK_OPERATOR_CODE_2 = invokeMethod(telephonyClassName, slotNumber_2, m_NETWORK_OPERATOR_CODE, SIM_VARINT);
if (TextUtils.isEmpty(NETWORK_OPERATOR_CODE_2)) {
NETWORK_OPERATOR_CODE_2 = getMethodValue(telephonyClassName, m_NETWORK_OPERATOR_CODE, slotNumber_2);
}
SIMSerial_1 = getSimSerialNumber(slotNumber_1);
SIMSerial_2 = getSimSerialNumber(slotNumber_2);
if (SIMSerial_1.equalsIgnoreCase(SIMSerial_2)) {
SIMSerial_2 = getSimSerialNumber(slotNumber_2 + 1);
}
getCurrentData();
if (NETWORK_OPERATOR_NAME_1 == null || NETWORK_OPERATOR_NAME_1.equalsIgnoreCase("") || NETWORK_OPERATOR_NAME_1.equalsIgnoreCase("UNKNOWN")) {
NETWORK_OPERATOR_NAME_1 = telephony.getSimOperatorName();
}
if (NETWORK_OPERATOR_CODE_1 == null || NETWORK_OPERATOR_CODE_1.equalsIgnoreCase("") || NETWORK_OPERATOR_CODE_1.equalsIgnoreCase("UNKNOWN")) {
NETWORK_OPERATOR_CODE_1 = telephony.getSimOperator();
}
if (TextUtils.isEmpty(m_IS_ROAMING)) {
isRoaming_1 = telephony.isNetworkRoaming();
}
} catch (Exception e) {
// TODO: handle exception
}
}
public String getSimSerialNumber(int slotNumber) {
String SIMSerial = invokeMethod(telephonyClassName, slotNumber, m_SIM_SUBSCRIBER, SIM_VARINT);
if (TextUtils.isEmpty(SIMSerial)) {
SIMSerial = getMethodValue(telephonyClassName, m_SIM_SUBSCRIBER, slotNumber);
if (TextUtils.isEmpty(SIMSerial)) {
SIMSerial = getMethodValue(telephonyClassName, m_SIM_SERIAL, slotNumber);
}
if (TextUtils.isEmpty(SIMSerial)) {
SIMSerial = getMethodValue(telephonyClassName, m_SIM_SERIAL, slotNumber);
}
}
return SIMSerial;
}
private void getCurrentData() {
try {
telephony = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
NETWORK_TYPE_1 = getNetworkType(0);
NETWORK_TYPE_2 = getNetworkType(1);
if (NETWORK_TYPE_1 == null || NETWORK_TYPE_1.equalsIgnoreCase("") || NETWORK_TYPE_1.equalsIgnoreCase("UNKNOWN")) {
NETWORK_TYPE_1 = getNetworkTypeName(telephony.getNetworkType());
}
isRoaming_1 = invokeMethodboolean(telephonyClassName, slotNumber_1, m_IS_ROAMING, SIM_VARINT);
if (!isRoaming_1) {
isRoaming_1 = telephony.isNetworkRoaming();
}
isRoaming_2 = invokeMethodboolean(telephonyClassName, slotNumber_2, m_IS_ROAMING, SIM_VARINT);
isGPRS_1 = invokeMethod(telephonyClassName, slotNumber_1, m_DATA_STATE, SIM_VARINT);
isGPRS_2 = invokeMethod(telephonyClassName, slotNumber_2, m_DATA_STATE, SIM_VARINT);
CELL_LOC_1 = getCellLocation(slotNumber_1);
CELL_LOC_2 = getCellLocation(slotNumber_2);
} catch (Exception e) {
// TODO: handle exception
}
}
public String getNetworkType(int slotnumber) {
String networkType = "UNKNOWN";
try {
if (slotnumber == 0) {
networkType = invokeMethod(telephonyClassName, slotNumber_1, m_NETWORK_TYPE_NAME, SIM_VARINT);
} else {
networkType = invokeMethod(telephonyClassName, slotNumber_2, m_NETWORK_TYPE_NAME, SIM_VARINT);
}
if (networkType.equalsIgnoreCase("")) {
for(String networktype : networkTypeMethods) {
try {
networkType = getDeviceIdBySlot(networktype, slotnumber);
} catch (Exception e) {
}
}
}
ConnectivityInfo connInfo = new ConnectivityInfo(mContext);
networkType = connInfo.getNetworkTypeName(Integer.parseInt(networkType));
if (slotnumber == 0 && !TextUtils.isEmpty(networkType)) {
networkType = connInfo.getNetworkTypeName(telephony.getNetworkType());
}
} catch (Exception e) {
////e.printStackTrace();
}
return networkType;
}
/*
* 电话方位:
*
*/
public int[] getCellLocation(int slot) {
int[] cellLoc = new int[]{-1, -1};
try {
if (slot == slotNumber_1) {
if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
GsmCellLocation location = (GsmCellLocation) telephony
.getCellLocation();
if (location == null) {
location = (GsmCellLocation) telephony
.getCellLocation();
}
if (location != null) {
cellLoc[0] = location.getCid();
cellLoc[1] = location.getLac();
}
}
} else {
Object cellInfo = (Object) getObjectBySlot("getNeighboringCellInfo" + SIM_VARINT, slot);
if (cellInfo != null) {
List<NeighboringCellInfo> info = (List<NeighboringCellInfo>) cellInfo;
cellLoc[0] = info.get(0).getCid();
cellLoc[1] = info.get(0).getLac();
}
}
} catch (Exception e) {
////e.printStackTrace();
}
return cellLoc;
}
private Object getObjectBySlot(String predictedMethodName, int slotID) {
Object ob_phone = null;
try {
Class<?> telephonyClass = Class.forName(telephonyClassName);
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotID;
ob_phone = getSimID.invoke(telephony, obParameter);
} catch (Exception e) {
////e.printStackTrace();
}
return ob_phone;
}
private boolean invokeMethodboolean(String className,
int slotNumber, String methodName, String SIM_variant) {
boolean val = false;
try {
Class<?> telephonyClass = Class.forName(telephonyClassName);
Constructor[] cons = telephonyClass.getDeclaredConstructors();
cons[0].getName();
cons[0].setAccessible(true);
Object obj = cons[0].newInstance();
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Object ob_phone = null;
try {
Method getSimID = telephonyClass.getMethod(methodName
+ SIM_variant, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotNumber;
ob_phone = getSimID.invoke(obj, obParameter);
} catch (Exception e) {
if (slotNumber == 0) {
Method getSimID = telephonyClass.getMethod(methodName
+ SIM_variant, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotNumber;
ob_phone = getSimID.invoke(obj);
}
//e.printStackTrace();
}
if (ob_phone != null) {
val = (boolean) Boolean.parseBoolean(ob_phone.toString());
}
} catch (Exception e) {
invokeOldMethod(className, slotNumber, methodName, SIM_variant);
}
return val;
}
public boolean isTelephonyClassExists(String className) {
boolean isClassExists = false;
try {
Class<?> telephonyClass = Class.forName(className);
isClassExists = true;
} catch (ClassNotFoundException e) {
//e.printStackTrace();
} catch (Exception e) {
//e.printStackTrace();
}
return isClassExists;
}
/**
* Here we are identify sim slot number
*/
public void getValidSlotFields(String className) {
String value = null;
try {
Class<?> telephonyClass = Class.forName(className);
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
StringBuffer sbf = new StringBuffer();
Field[] fieldList = telephonyClass.getDeclaredFields();
for (int index = 0; index < fieldList.length; index++) {
sbf.append("\n\n" + fieldList[index].getName());
Class<?> type = fieldList[index].getType();
Class<?> type1 = int.class;
if (type.equals(type1)) {
String variableName = fieldList[index].getName();
if (variableName.contains("SLOT")
|| variableName.contains("slot")) {
if (variableName.contains("1")) {
slotName_1 = variableName;
} else if (variableName.contains("2")) {
slotName_2 = variableName;
} else if (variableName.contains("" + slotNumber_1)) {
slotName_1 = variableName;
} else if (variableName.contains("" + slotNumber_2)) {
slotName_2 = variableName;
}
}
}
}
} catch (Exception e) {
//e.printStackTrace();
}
}
/**
* Some device assign different slot number so here code execute
* to get slot number
*/
public void getSlotNumber(String className) {
try {
Class<?> c = Class.forName(className);
Field fields1 = c.getField(slotName_1);
fields1.setAccessible(true);
slotNumber_1 = (Integer) fields1.get(null);
Field fields2 = c.getField(slotName_2);
fields2.setAccessible(true);
slotNumber_2 = (Integer) fields2.get(null);
} catch (Exception e) {
slotNumber_1 = 0;
slotNumber_2 = 1;
// //e.printStackTrace();
}
}
private String invokeMethod(String className, int slotNumber,
String methodName, String SIM_variant) {
String value = "";
try {
Class<?> telephonyClass = Class.forName(className);
Constructor[] cons = telephonyClass.getDeclaredConstructors();
cons[0].getName();
cons[0].setAccessible(true);
Object obj = cons[0].newInstance();
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Object ob_phone = null;
try {
Method getSimID = telephonyClass.getMethod(methodName
+ SIM_variant, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotNumber;
ob_phone = getSimID.invoke(obj, obParameter);
} catch (Exception e) {
if (slotNumber == 0) {
Method getSimID = telephonyClass.getMethod(methodName
+ SIM_variant, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotNumber;
ob_phone = getSimID.invoke(obj);
}
}
if (ob_phone != null) {
value = ob_phone.toString();
}
} catch (Exception e) {
invokeOldMethod(className, slotNumber, methodName, SIM_variant);
}
return value;
}
private String invokeLongMethod(String className, long slotNumber,
String methodName, String SIM_variant) {
String value = "";
try {
Class<?> telephonyClass = Class.forName(className);
Constructor[] cons = telephonyClass.getDeclaredConstructors();
cons[0].getName();
cons[0].setAccessible(true);
Object obj = cons[0].newInstance();
Class<?>[] parameter = new Class[1];
parameter[0] = long.class;
Object ob_phone = null;
try {
Method getSimID = telephonyClass.getMethod(methodName
+ SIM_variant, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotNumber;
ob_phone = getSimID.invoke(obj, obParameter);
} catch (Exception e) {
if (slotNumber == 0) {
Method getSimID = telephonyClass.getMethod(methodName
+ SIM_variant, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotNumber;
ob_phone = getSimID.invoke(obj);
}
}
if (ob_phone != null) {
value = ob_phone.toString();
}
} catch (Exception e) {
}
return value;
}
public String invokeOldMethod(String className, int slotNumber,
String methodName, String SIM_variant) {
String val = "";
try {
Class<?> telephonyClass = Class
.forName("android.telephony.TelephonyManager");
Constructor[] cons = telephonyClass.getDeclaredConstructors();
cons[0].getName();
cons[0].setAccessible(true);
Object obj = cons[0].newInstance();
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Object ob_phone = null;
try {
Method getSimID = telephonyClass.getMethod(methodName
+ SIM_variant, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotNumber;
ob_phone = getSimID.invoke(obj, obParameter);
} catch (Exception e) {
if (slotNumber == 0) {
Method getSimID = telephonyClass.getMethod(methodName
+ SIM_variant, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotNumber;
ob_phone = getSimID.invoke(obj);
}
}
if (ob_phone != null) {
val = ob_phone.toString();
}
} catch (Exception e) {
}
return val;
}
/*
* get the IMEI/MEID of the device.
* Return null if device ID is not available.
*/
public String getDeviceIdBySlot(String predictedMethodName, int slotID) {
String imei = null;
try {
Class<?> telephonyClass = Class.forName(telephonyClassName);
Constructor[] cons = telephonyClass.getDeclaredConstructors();
cons[0].getName();
cons[0].setAccessible(true);
Object obj = cons[0].newInstance();
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimID = telephonyClass.getMethod(predictedMethodName,
parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotID;
Object ob_phone = getSimID.invoke(obj, obParameter);
if (ob_phone != null) {
imei = ob_phone.toString();
}
} catch (Exception e) {
////e.printStackTrace();
}
return imei;
}
public String getDeviceIdBySlotOld(String predictedMethodName, int slotID) {
String value = null;
try {
Class<?> telephonyClass = Class.forName(telephony.getClass()
.getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimID = telephonyClass.getMethod(predictedMethodName,
parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotID;
Object ob_phone = getSimID.invoke(telephony, obParameter);
if (ob_phone != null) {
value = ob_phone.toString();
}
} catch (Exception e) {
////e.printStackTrace();
}
return value;
}
}
}
|
/*
* Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.stdext.translation.out;
import pl.edu.icm.unity.server.translation.out.OutputTranslationAction;
import pl.edu.icm.unity.server.translation.out.OutputTranslationActionFactory;
import pl.edu.icm.unity.types.translation.ActionParameterDefinition;
import pl.edu.icm.unity.types.translation.ProfileType;
import pl.edu.icm.unity.types.translation.TranslationActionType;
/**
* Boilerplate code for the output profile's {@link OutputTranslationActionFactory} implementations.
* @author K. Benedyczak
*/
public abstract class AbstractOutputTranslationActionFactory implements OutputTranslationActionFactory
{
private TranslationActionType actionType;
public AbstractOutputTranslationActionFactory(String name, ActionParameterDefinition... parameters)
{
actionType = new TranslationActionType(ProfileType.OUTPUT,
"TranslationAction." + name + ".desc",
name,
parameters);
}
@Override
public TranslationActionType getActionType()
{
return actionType;
}
@Override
public OutputTranslationAction getBlindInstance(String... parameters)
{
return new BlindStopperOutputAction(getActionType(), parameters);
}
}
|
package de.scads.gradoop_service.server.helper.filtering.pojos;
import de.scads.gradoop_service.server.helper.filtering.enums.BinaryBooleanOperation;
import java.io.Serializable;
/**
* POJO for handling logic between operations.
*/
public class FilterEvalElement implements Serializable {
public final BinaryBooleanOperation booleanOperation;
public final int firstId;
public final int secondId;
public FilterEvalElement(BinaryBooleanOperation booleanOperation, int firstId, int secondId) {
this.booleanOperation = booleanOperation;
this.firstId = firstId;
this.secondId = secondId;
}
@Override
public String toString() {
return "FilterEvalElement{" +
"booleanOperation=" + booleanOperation +
", firstId=" + firstId +
", secondId=" + secondId +
'}';
}
}
|
package com.practicalddd.cargotracker.booking.domain.model;
import java.util.Collections;
import java.util.List;
public class Itinerary {
private List<Leg> legs = Collections.emptyList();
public Itinerary() {
// Nothing to initialize.
}
public Itinerary(List<Leg> legs) {
this.legs = legs;
}
public List<Leg> getLegs() {
return Collections.unmodifiableList(legs);
}
}
|
package com.itheima;
import com.itheima.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/*
事务xml配置测试,已无用,此项目为注解,留住只为笔记
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean2.xml")
public class AccountTest {
@Autowired
private IAccountService as;
@Test
public void name() {
as.transfer("仁宣之治", "张飞", 100f);
}
}
|
package com.example.htw.currencyconverter.model;
import android.support.annotation.NonNull;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class CurrencyDeserializer implements JsonDeserializer<Currency> {
private Gson gson = new Gson();
private final String BASE_FIELD = "base";
private final String DATE_FIELD = "date";
private final String RATES_FIELD = "rates";
@Override
public Currency deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Currency(
gson.fromJson(json.getAsJsonObject().get(BASE_FIELD), String.class),
gson.fromJson(json.getAsJsonObject().get(DATE_FIELD), String.class),
rates(gson.fromJson(json.getAsJsonObject().get(RATES_FIELD), JsonObject.class))
);
}
private Map<String,Double> rates(@NonNull JsonObject jsonObject){
HashMap result = new HashMap();
for(Map.Entry<String,JsonElement> parameter : jsonObject.entrySet()){
result.put(parameter.getKey(),parameter.getValue().getAsDouble());
}
return result;
}
}
|
package br.com.mixfiscal.prodspedxnfe.dao.own;
import br.com.mixfiscal.prodspedxnfe.dao.util.ConstroyerHibernateUtil;
import br.com.mixfiscal.prodspedxnfe.domain.own.ClassificacaoTributaria;
import br.com.mixfiscal.prodspedxnfe.domain.own.ClassificacaoTributariaProduto;
import br.com.mixfiscal.prodspedxnfe.domain.own.IcmsEntrada;
import br.com.mixfiscal.prodspedxnfe.domain.own.IcmsSaida;
import br.com.mixfiscal.prodspedxnfe.domain.own.Cliente;
import br.com.mixfiscal.prodspedxnfe.domain.own.custom.ClassificacaoTributariaProdutoCustom;
import br.com.mixfiscal.prodspedxnfe.util.StringUtil;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class AtualizarClassificacaoTributariaTeste {
@Test
public void PercorrerPlanoExelParaSalvarNoBDTeste() {
String line = "";
ClassificacaoTributaria clTributaria = null;
ClassificacaoTributariaDAO clTribDao = new ClassificacaoTributariaDAO();
int cont = 0;
try {
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
String caminho_arquivo_xls = "D:\\LULU SOFTWARES\\MIX_FISCAL\\ProdSPEDxNFe\\trunk-old\\DOCUMENTOS\\documentacao\\exemplos\\CASTELI\\produtos_mxf.csv";
BufferedReader br = new BufferedReader(new FileReader(caminho_arquivo_xls));
while ((line = br.readLine()) != null) {
cont++;
if (cont > 2) {
Cliente cli = new Cliente();
cli.setCnpj("05587850000151");
clTributaria = new ClassificacaoTributaria();
String[] row = line.split(";");
carregarObjetoDaImportacaoDoExelCompletoTest(clTributaria, row);
clTributaria.setCliente(cli);
clTribDao.salvar(clTributaria);
}
}
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
// System.out.println(row[0] + " - " + row[1]); }
} catch (FileNotFoundException fe) {
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
System.out.println(fe.getMessage());
} catch (IOException Ie) {
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
System.out.println(Ie.getMessage());
} catch (NumberFormatException Ne) {
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
System.out.println(Ne.getMessage());
} catch (Exception e) {
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
System.out.println("Erro ao ler e gravar" + e.getMessage() + "" + clTribDao);
}
}
@Test
public void excluir() {
/*ClassificacaoTributaria cl = new ClassificacaoTributaria();
ClassificacaoTributariaDAO clDao = new ClassificacaoTributariaDAO();
ClassificacaoTributariaProdutoCustomDAO clProdCustomDao = new ClassificacaoTributariaProdutoCustomDAO();
ClassificacaoTributariaProduto prod = new ClassificacaoTributariaProduto();
ClassificacaoTributariaProdutoDAO prodDao = new ClassificacaoTributariaProdutoDAO();
List<ClassificacaoTributariaProdutoCustom> lista = new ArrayList<>();
IcmsEntradaCustomDAO icmsEntradaDao = new IcmsEntradaCustomDAO();
IcmsSaidaCustomDAO icmsSaidaDao = new IcmsSaidaCustomDAO();
String cnpj = "18765188000124";
try {
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
lista = clProdCustomDao.listarParaExcluirCustom(cnpj);
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
} catch (Exception ex) {
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
}
try {
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
prodDao.excluirCustom(cnpj);
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
} catch (Exception ex) {
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
}
try {
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
clDao.excluirCustom(cnpj);
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
} catch (Exception ex) {
ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
}*/
}
public void carregarObjetoDaImportacaoDoExelCompletoTest(ClassificacaoTributaria objCT, String[] row) {
try {
ClassificacaoTributariaProduto produto = new ClassificacaoTributariaProduto();
IcmsEntrada icmsEntrada = new IcmsEntrada();
IcmsSaida icmsSaida = new IcmsSaida();
try {
produto.setEan(StringUtil.isNullOrEmpty(row[1]) ? "campo vazio" : row[1]);
} catch (Exception ex) {
}
try {
produto.setDescricao(row[2].isEmpty() ? "campo vazio" : row[2]);
} catch (Exception ex) {
}
try {
objCT.getProduto().getPisCofins().setNcm(row[9].isEmpty() ? "campo vazio" : row[9]);
} catch (Exception ex) {
}
try {
objCT.getProduto().getPisCofins().setNcmEx(row[10].isEmpty() ? "campo vazio" : row[10]);
} catch (Exception ex) {
}
try {
objCT.getProduto().getPisCofins().setCodNaturezaReceita(row[11].isEmpty() ? "campo vazio" : row[11]);
} catch (Exception ex) {
}
try {
objCT.getProduto().getPisCofins().setPisCstE(row[12].isEmpty() ? "campo vazio" : row[12]);
} catch (Exception ex) {
}
try {
objCT.getProduto().getPisCofins().setPisCstS(row[13].isEmpty() ? "campo vazio" : row[13]);
} catch (Exception ex) {
}
try {
objCT.getProduto().getPisCofins().setPisAlqE(row[14].isEmpty() ? "campo vazio" : row[14]);
} catch (Exception ex) {
}
try {
objCT.getProduto().getPisCofins().setPisAlqS(row[15].isEmpty() ? "campo vazio" : row[15]);
} catch (Exception ex) {
}
try {
objCT.getProduto().getPisCofins().setCofinsAlqE(row[16].isEmpty() ? "campo vazio" : row[16]);
} catch (Exception ex) {
}
try {
objCT.getProduto().getPisCofins().setCofinsAlqS(row[17].isEmpty() ? "campo vazio" : row[17]);
} catch (Exception ex) {
}
try {
icmsSaida.setSacCst(row[19].isEmpty() ? "campo vazio" : row[19]);
} catch (Exception ex) {
}
try {
icmsSaida.setSacAlq(row[20].isEmpty() ? "campo vazio" : row[20]);
} catch (Exception ex) {
}
try {
icmsSaida.setSacAlqst(row[21].isEmpty() ? "campo vazio" : row[21]);
} catch (Exception ex) {
}
try {
icmsSaida.setSacRbc(row[22].isEmpty() ? "campo vazio" : row[22]);
} catch (Exception ex) {
}
try {
icmsSaida.setSacRbcst(row[23].isEmpty() ? "campo vazio" : row[23]);
} catch (Exception ex) {
}
try {
icmsSaida.setSasCst(row[24].isEmpty() ? "campo vazio" : row[24]);
} catch (Exception ex) {
}
try {
icmsSaida.setSasAlq(row[25].isEmpty() ? "campo vazio" : row[25]);
} catch (Exception ex) {
}
try {
icmsSaida.setSasAlqst(row[26].isEmpty() ? "campo vazio" : row[26]);
} catch (Exception ex) {
}
try {
icmsSaida.setSasRbc(row[27].isEmpty() ? "campo vazio" : row[27]);
} catch (Exception ex) {
}
try {
icmsSaida.setSasRbcst(row[28].isEmpty() ? "campo vazio" : row[28]);
} catch (Exception ex) {
}
try {
icmsSaida.setSvcCst(row[29].isEmpty() ? "campo vazio" : row[29]);
} catch (Exception ex) {
}
try {
icmsSaida.setSvcAlq(row[30].isEmpty() ? "campo vazio" : row[30]);
} catch (Exception ex) {
}
try {
icmsSaida.setSvcAlqst(row[31].isEmpty() ? "campo vazio" : row[31]);
} catch (Exception ex) {
}
try {
icmsSaida.setSvcRbc(row[32].isEmpty() ? "campo vazio" : row[32]);
} catch (Exception ex) {
}
try {
icmsSaida.setSvcRbcst(row[33].isEmpty() ? "campo vazio" : row[33]);
} catch (Exception ex) {
}
try {
icmsSaida.setSncCst(row[34].isEmpty() ? "campo vazio" : row[34].toString());
} catch (Exception ex) {
}
try {
icmsSaida.setSncAlq(row[35].isEmpty() ? "campo vazio" : row[35].toString());
} catch (Exception ex) {
}
try {
icmsSaida.setSncAlqst(row[36].isEmpty() ? "campo vazio" : row[36].toString());
} catch (Exception ex) {
}
try {
icmsSaida.setSncRbc(row[37].isEmpty() ? "campo vazio" : row[37].toString());
} catch (Exception ex) {
}
try {
icmsSaida.setSncRbcst(row[38].isEmpty() ? "campo vazio" : row[38].toString());
} catch (Exception ex) {
}
try {
icmsSaida.setFundamentoLegal(row[40].isEmpty() ? "campo vazio" : row[40].toString());
} catch (Exception ex) {
}
try {
icmsSaida.setProduto(produto);
} catch (Exception ex) {
}
;
try {
icmsEntrada.setEiCst(row[41].isEmpty() ? "campo vazio" : row[41].toString());
} catch (Exception ex) {
objCT.getProduto().getIcmsEntrada().setEiCst("0");
}
try {
icmsEntrada.setEiAlq(row[42].isEmpty() ? "campo vazio" : row[42].toString());
} catch (Exception ex) {
objCT.getProduto().getIcmsEntrada().setEiAlq("0");
}
try {
icmsEntrada.setEiAlqst(row[43].isEmpty() ? "campo vazio" : row[43].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEiRbc(row[44].isEmpty() ? "campo vazio" : row[44].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEiRbcst(row[45].isEmpty() ? "campo vazio" : row[45].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEdCst(row[46].isEmpty() ? "campo vazio" : row[46].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEdAlq(row[47].isEmpty() ? "campo vazio" : row[47].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEdAlqst(row[48].isEmpty() ? "campo vazio" : row[48].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEdRbc(row[49].isEmpty() ? "campo vazio" : row[49].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEdRbcst(row[50].isEmpty() ? "campo vazio" : row[50].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEsCst(row[51].isEmpty() ? "campo vazio" : row[51].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEsAlq(row[52].isEmpty() ? "campo vazio" : row[52].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEsAlqst(row[53].isEmpty() ? "campo vazio" : row[53].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEsRbc(row[54].isEmpty() ? "campo vazio" : row[54].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setEsRbcst(row[55].isEmpty() ? "campo vazio" : row[55].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setNfiCst(row[56].isEmpty() ? "campo vazio" : row[56].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setNfdCst(row[57].isEmpty() ? "campo vazio" : row[57].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setNfsCsosn(row[58].isEmpty() ? "campo vazio" : row[58].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setNfAlq(row[59].isEmpty() ? "campo vazio" : row[59].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setFundamentoLegal(row[39].isEmpty() ? "campo vazio" : row[39].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setTipoMva(row[60].isEmpty() ? "campo vazio" : row[60].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setMva(row[61].isEmpty() ? "campo vazio" : row[61].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setMvaDataIni(row[63].isEmpty() ? "campo vazio" : row[63].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setMvaDataFim(row[64].isEmpty() ? "campo vazio" : row[64].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setCreditoOutorgado(row[65].isEmpty() ? "campo vazio" : row[65].toString());
} catch (Exception ex) {
}
try {
icmsEntrada.setProduto(produto);
} catch (Exception ex) {
}
;
Cliente cli = new Cliente();
cli.setCnpj("05587850000151");
objCT.setCliente(cli);
objCT.setProduto(produto);
objCT.getProduto().setIcmsEntrada(icmsEntrada);
objCT.getProduto().setIcmsSaida(icmsSaida);
} catch (Exception e) {
System.out.println(e);
}
}
public void salvarCustomTeste(ClassificacaoTributaria cl) {
Serializable idGerado = 0;
ClassificacaoTributariaDAO classificacaoTribDAO = null;
try {
classificacaoTribDAO = new ClassificacaoTributariaDAO();
} catch (Exception ex) {
String re = ex.getMessage();
}
try {
// ConstroyerHibernateUtil.beginTransaction();
if (cl != null) {
idGerado = classificacaoTribDAO.salvar(cl);
}
// if(produto != null)
// idGerado = classificacaoTribDAO.salvar(produto);
// ConstroyerHibernateUtil.commitCurrentTransaction();
} catch (Exception ex) {
// ConstroyerHibernateUtil.rollbackCurrentTransaction();
}
}
@Test
public void testarSelecionarCnpj() {
Cliente cliente = new Cliente();
cliente.setCnpj("27579252000173");
ClienteDAO clienteDao = new ClienteDAO();
try {
cliente = clienteDao.selecionarUm(cliente);
System.out.println("" + cliente.getNome());
} catch (Exception ex) {
System.out.println("" + ex.getMessage());
}
}
}
|
package app.akexorcist.d2dcontroller;
import java.io.IOException;
import java.util.ArrayList;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
// IP address scanner class
public class IPDiscover {
private Context mContext;
private int count = 0;
public boolean getIPState = false;
public String DEVICE_IP_ADDRESS;
private String ipTrim;
private ArrayList<String> arr_ip;
private ListView mListIP;
private View mNormal, mLoad;
public IPDiscover(Context context, ListView listIP, View normal, View load) {
mContext = context;
getDeviceIP();
mListIP = listIP;
mNormal = normal;
mLoad = load;
}
// Get class state
// true = is scanning IP address (Busy)
// false = isn't scanning or finished (Idle)
public boolean isDiscovered() {
return getIPState;
}
// Get each other device's IP Address on wlan network
public String get(int index) {
return arr_ip.get(index);
}
// Get all other device's IP Address on wlan network
public ArrayList<String> getIPList() {
return arr_ip;
}
// Get device IP address
private void getDeviceIP() {
WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
ipTrim = (ipAddress & 0xFF) + "."
+ ((ipAddress >> 8 ) & 0xFF) + "."
+ ((ipAddress >> 16 ) & 0xFF);
DEVICE_IP_ADDRESS = (ipAddress & 0xFF) + "."
+ ((ipAddress >> 8 ) & 0xFF) + "."
+ ((ipAddress >> 16 ) & 0xFF) + "."
+ ((ipAddress >> 24 ) & 0xFF);
Log.i("IP Discoverage", "Device IP : " + DEVICE_IP_ADDRESS);
}
// Find other device's IP Address on wlan network
public void getConnectedDevices() {
// Busy state
getIPState = false;
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run() {
mNormal.setVisibility(View.INVISIBLE);
mLoad.setVisibility(View.VISIBLE);
}
});
arr_ip = new ArrayList<String>();
mListIP.setAdapter(new ArrayAdapter<String>(mContext
, android.R.layout.simple_list_item_1, arr_ip));
// Scan from xxx.xxx.xxx.0 to xxx.xxx.xxx.255
for (int i = 0; i <= 255; i++) {
final int j = i;
Runnable runnable = new Runnable() {
public void run() {
try {
// Execute "ping" command
Process proc = Runtime.getRuntime().exec("ping -c 2 " + ipTrim + "." + String.valueOf(j));
proc.waitFor();
int exit = proc.exitValue();
proc.destroy();
// Get ping response and not itself IP address
if (exit == 0 && !(ipTrim + "." + String.valueOf(j)).equals(DEVICE_IP_ADDRESS)) {
count++;
arr_ip.add(ipTrim + "." + String.valueOf(j));
} else {
count++;
}
// When scanning has finish, will show IP address list on list view
if(count >= 255) {
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run() {
mListIP.setAdapter(new ArrayAdapter<String>(mContext
, android.R.layout.simple_list_item_1, arr_ip));
mNormal.setVisibility(View.VISIBLE);
mLoad.setVisibility(View.INVISIBLE);
}
});
// Idle state
getIPState = true;
count = 0;
}
} catch (IOException e) {
} catch (InterruptedException e) { }
}
};
new Thread(runnable).start();
}
}
}
|
/*
* Copyright 2015 Zbynek Vyskovsky mailto:kvr000@gmail.com http://kvr.znj.cz/ http://github.com/kvr000/
*
* 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 net.dryuf.bigio;
import java.nio.ByteOrder;
/**
* Implementation {@link FlatBuffer}, changing the byte order.
*/
public class SwappedBytesFlatBuffer extends AbstractDelegatingFlatBuffer
{
public SwappedBytesFlatBuffer(FlatBuffer underlying)
{
super(underlying);
}
@Override
public ByteOrder getByteOrder()
{
return underlying.getByteOrder() == ByteOrder.LITTLE_ENDIAN ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN;
}
@Override
public short getShort(long pos)
{
return Short.reverseBytes(underlying.getShort(pos));
}
@Override
public int getInt(long pos)
{
return Integer.reverseBytes(underlying.getInt(pos));
}
@Override
public long getLong(long pos)
{
return Long.reverseBytes(underlying.getLong(pos));
}
@Override
public void putShort(long pos, short val)
{
underlying.putShort(pos, Short.reverseBytes(val));
}
@Override
public void putInt(long pos, int val)
{
underlying.putInt(pos, Integer.reverseBytes(val));
}
@Override
public void putLong(long pos, long val)
{
underlying.putLong(pos, Long.reverseBytes(val));
}
}
|
package com.example.ecommerceapp;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
public class OrderActivity extends AppCompatActivity implements View.OnClickListener{
TextView total, n_items;
Button place, back;
private FirebaseFirestore fStore;
private FirebaseAuth fAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
total = findViewById(R.id.totalTxt);
n_items = findViewById(R.id.nItemsTxt);
place = findViewById(R.id.placeOrderBtn);
back = findViewById(R.id.backCartBtn);
calculate_receit();
place.setOnClickListener(this);
back.setOnClickListener(this);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.placeOrderBtn:
placeOrder();
break;
case R.id.backCartBtn:
Intent intent = new Intent(OrderActivity.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("cart", true);
startActivity(intent);
finish();
break;
}
}
private void calculate_receit(){
int n = 0, sum = 0;
for (String item : Helper.cart_products) {
int price = Integer.valueOf(Helper.products_prices.get(item));
int qnt = Integer.valueOf(Helper.products_qnt.get(item));
n += qnt;
sum += qnt * price;
}
total.setText(sum + "$");
n_items.setText(n + " Items");
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void placeOrder(){
String date = java.time.LocalDate.now().toString();
String Total = total.getText().toString();
String uID = fAuth.getCurrentUser().getUid();
HashMap<String,Object> order_details = new HashMap<>();
order_details.put("date", date);
order_details.put("total", Total);
order_details.put("uID", uID);
order_details.put("items", Helper.cart_products);
DocumentReference docR = fStore.collection("order").document();
docR.set(order_details).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void unused) {
Toast.makeText(OrderActivity.this,"Order Placed successfully!", Toast.LENGTH_LONG).show();
// send email
Helper.reset_cart();
Helper.order_number += 1;
startActivity(new Intent(OrderActivity.this, HomeActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull @NotNull Exception e) {
Toast.makeText(OrderActivity.this,"Failed to place order. Try Again!", Toast.LENGTH_LONG).show();
}
});
}
}
|
package etc;
public interface DInterface {
public void m2();
}
|
package com.example.thread;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by zhaoningqiang on 16/7/7.
*/
public class CyclicBarrierTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
for (int i = 0; i < 3; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程:" + Thread.currentThread().getName() + " 即将到达集合点1,当前已有: " + (cyclicBarrier.getNumberWaiting() + 1));
cyclicBarrier.await();
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程:" + Thread.currentThread().getName() + " 即将到达集合点2,当前已有: " + (cyclicBarrier.getNumberWaiting() + 1));
cyclicBarrier.await();
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程:" + Thread.currentThread().getName() + " 都到集合点3了,继续走,当前已有: " + (cyclicBarrier.getNumberWaiting() + 1));
cyclicBarrier.await();
} catch (Exception e) {
}
}
};
executorService.execute(runnable);
}
executorService.shutdown();
}
}
|
/*
* 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 Windows;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import Windows.Shoot;
/**
*
* @author Matt
*/
public class mainMenu extends Stage{
Scene mainMenu;
public mainMenu(String Title) {
//Buttons/Labels/Stage
this.initModality(Modality.APPLICATION_MODAL);
Button shotLogging = new Button("Shoot!");
Button profileInfo = new Button("Profile Info");
Button logoutButton = new Button("Logout");
//setting title for window
this.setTitle(Title);
VBox layout = new VBox();
layout.setAlignment(Pos.CENTER);
layout.setSpacing(35);
layout.getChildren().add(shotLogging);
layout.getChildren().add(profileInfo);
layout.getChildren().add(logoutButton);
Scene mainMenu = new Scene(layout,300,380);
this.setScene(mainMenu);
this.show();
shotLogging.setOnAction(e -> {
try {
Shoot newChart = new Shoot("shot");
} catch (FileNotFoundException ex) {
Logger.getLogger(mainMenu.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
public Scene getMainMenu() {
return mainMenu;
}
public void setMainMenu(Scene mainMenu) {
this.mainMenu = mainMenu;
}
}
|
package video.api.android.sdk.domain.analytic;
public class AnalyticReferrer {
private String url;
private String medium;
private String source;
private String search_term;
public AnalyticReferrer(String url, String medium, String source, String search_term) {
this.url = url;
this.medium = medium;
this.source = source;
this.search_term = search_term;
}
public AnalyticReferrer() {
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMedium() {
return medium;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getSearch_term() {
return search_term;
}
public void setSearch_term(String search_term) {
this.search_term = search_term;
}
}
|
/**
* FileName: KafkaTopicEnum
* Author: yangqinkuan
* Date: 2019-1-13 18:06
* Description: kafka主题枚举
*/
package com.ice.find.util.kafka;
public enum KafkaTopicEnum {
/**
* 2xxxx代表用户模块类事件,如注册,登陆,找回密码等
*
*
* */
/* 2xxxx*/
REGISTRY_MAIL_SEND("user_mail","20001"),
AA_MAIL_SEND("user_mail","20002"),
;
public static String getTopicByEventTypeID(String eventTypeID){
for(KafkaTopicEnum e:KafkaTopicEnum.values()){
if(e.getEventTypeID().equals(eventTypeID)){
return e.getTopic();
}
}
return null;
}
private String topic;
private String eventTypeID;
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getEventTypeID() {
return eventTypeID;
}
public void setEventTypeID(String eventTypeID) {
this.eventTypeID = eventTypeID;
}
KafkaTopicEnum(String topic, String eventTypeID) {
this.topic = topic;
this.eventTypeID = eventTypeID;
}
}
|
package com.lgbear.weixinplatform.api.domain;
public abstract class WeixinMessage {
private String toUserName;
private String fromUserName;
private String createTime;
protected String msgType;
public static final String TEXT = "text";
public static final String IMAGE = "image";
public static final String LOCATION = "location";
public static final String LINK = "link";
public static final String EVENT = "event";
public static final String NEWS = "news";
public static final String MUSIC = "music";
public String getToUserName() {
return toUserName;
}
public void setToUserName(String toUserName) {
this.toUserName = toUserName;
}
public String getFromUserName() {
return fromUserName;
}
public void setFromUserName(String fromUserName) {
this.fromUserName = fromUserName;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
}
|
package com.droid.btkeyboard;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.droid.keys.NumericKeyboard;
import com.droid.keys.QwertyKeyboard;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QwertyKeyboard keyboard = findViewById(R.id.keyboard);
keyboard.onKeyClicked(new QwertyKeyboard.KeysClickEvent() {
@Override
public void onKeyClicked(String clickedKey) {
Toast.makeText(MainActivity.this, clickedKey, Toast.LENGTH_SHORT).show();
}
});
}
}
|
package stacksnqueues;
import static org.junit.Assert.*;
import org.junit.Test;
public class HistogramTest {
// @Test
// public void testExample() {
// assertEquals(12,Histogram.findArea(new int[]{6,2,5,4,5,1,6}));
// }
//
@Test
public void testMinimum() {
int[] array =new int[]{6,2,4,3,4,1,1,1,1,1,1};
assertEquals(array.length,Histogram.findArea(array));
}
}
|
package interfaces;
import java.util.ArrayList;
import org.newdawn.slick.command.Command;
public interface CommandProvider {
public ArrayList<Command> getCommands();
}
|
/**
* Copyright 2014 Bill McDowell
*
* This file is part of theMess (https://github.com/forkunited/theMess)
*
* 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 ark.experiment;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ark.data.annotation.DataSet;
import ark.data.annotation.Datum;
import ark.data.feature.Feature;
import ark.model.SupervisedModel;
import ark.model.evaluation.KFoldCrossValidation;
import ark.model.evaluation.metric.SupervisedModelEvaluation;
import ark.util.SerializationUtil;
/**
* ExperimentKCV represents a k-fold cross-validation training/evaluation
* experiment with an optional grid-search for each fold. An experiment
* configuration file determines the model, features, number of folds and
* other settings for the experiment. ExperimentKCV parses this configuration
* file with the help of the ark.model.SupervisedModel, ark.data.feature.Feature,
* ark.util.SerializationUtil and other classes, and then uses
* ark.model.evaluation.KFoldCrossValidation to carry out the
* experiment. See the experiments/KCVTLinkType directory in the
* TemporalOrdering project at https://github.com/forkunited/TemporalOrdering
* for examples of experiment configuration files.
*
* @author Bill McDowell
*
* @param <D> datum type
* @param <L> datum label type
*
*/
public class ExperimentKCV<D extends Datum<L>, L> extends Experiment<D, L> {
protected SupervisedModel<D, L> model;
protected List<Feature<D, L>> features;
protected int crossValidationFolds;
protected Datum.Tools.TokenSpanExtractor<D, L> errorExampleExtractor;
protected Map<String, List<String>> gridSearchParameterValues;
protected List<SupervisedModelEvaluation<D, L>> evaluations;
protected DataSet<D, L> data;
public ExperimentKCV(String name, String inputPath, DataSet<D, L> data) {
super(name, inputPath, data.getDatumTools());
this.features = new ArrayList<Feature<D, L>>();
this.gridSearchParameterValues = new HashMap<String, List<String>>();
this.evaluations = new ArrayList<SupervisedModelEvaluation<D, L>>();
this.data = data;
}
@Override
protected boolean execute() {
KFoldCrossValidation<D, L> validation = new KFoldCrossValidation<D, L>(
this.name,
this.model,
this.features,
this.evaluations,
this.data,
this.crossValidationFolds
);
validation.setPossibleHyperParameterValues(this.gridSearchParameterValues);
if (validation.run(this.maxThreads, this.errorExampleExtractor).get(0) < 0)
return false;
return true;
}
@Override
protected boolean deserializeNext(BufferedReader reader, String nextName) throws IOException {
if (nextName.equals("crossValidationFolds")) {
this.crossValidationFolds = Integer.valueOf(SerializationUtil.deserializeAssignmentRight(reader));
} else if (nextName.startsWith("model")) {
String[] nameParts = nextName.split("_");
String referenceName = null;
if (nameParts.length > 1)
referenceName = nameParts[1];
String modelName = SerializationUtil.deserializeGenericName(reader);
this.model = this.datumTools.makeModelInstance(modelName);
if (!this.model.deserialize(reader, false, false, this.datumTools, referenceName))
return false;
} else if (nextName.startsWith("feature")) {
String[] nameParts = nextName.split("_");
String referenceName = null;
boolean ignore = false;
if (nameParts.length > 1)
referenceName = nameParts[1];
if (nameParts.length > 2)
ignore = true;
String featureName = SerializationUtil.deserializeGenericName(reader);
Feature<D, L> feature = this.datumTools.makeFeatureInstance(featureName);
if (!feature.deserialize(reader, false, false, this.datumTools, referenceName, ignore))
return false;
this.features.add(feature);
} else if (nextName.startsWith("errorExampleExtractor")) {
this.errorExampleExtractor = this.datumTools.getTokenSpanExtractor(
SerializationUtil.deserializeAssignmentRight(reader));
} else if (nextName.startsWith("gridSearchParameterValues")) {
String parameterName = SerializationUtil.deserializeGenericName(reader);
List<String> parameterValues = SerializationUtil.deserializeList(reader);
this.gridSearchParameterValues.put(parameterName, parameterValues);
} else if (nextName.startsWith("evaluation")) {
String evaluationName = SerializationUtil.deserializeGenericName(reader);
SupervisedModelEvaluation<D, L> evaluation = this.datumTools.makeEvaluationInstance(evaluationName);
if (!evaluation.deserialize(reader, false, this.datumTools))
return false;
this.evaluations.add(evaluation);
}
return true;
}
}
|
// Copyright 2016 The WWU eLectures Team All rights reserved.
//
// Licensed under the Educational Community 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://opensource.org/licenses/ECL-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.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Console application that tries multiple times to connect to a JDBC URL.
*/
public class TryToConnectToDb {
private static final int SLEEP_TIME = 5 * 1000;
public static void main(String[] args) throws InterruptedException {
if (args.length != 5) {
System.err.println("Wrong number of arguments provided");
printUsage();
System.exit(1);
}
final String
driver = args[0],
url = args[1],
user = args[2],
password = args[3];
final int numberOfTries = Integer.parseInt(args[4]);
if (numberOfTries == 0) {
System.out.println("Skip DB connection check");
System.exit(0);
}
// 1. Check if driver is available
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.err.println("Driver could not be found");
System.exit(1);
}
// 2. Try to connect to DB
Connection conn = null;
boolean failed = true;
for (int i = 1; failed && i <= numberOfTries; i++) {
failed = false;
try {
System.out.print("Try to connect to DB (" + i + "/" + numberOfTries + ") ");
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
failed = true;
System.out.println("FAILED");
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
// ignore
}
}
}
if (failed && i < numberOfTries) {
Thread.sleep(SLEEP_TIME);
} else if (!failed) {
System.out.println("SUCCEEDED");
}
}
if (failed) {
System.err.println("Could not connect to DB");
System.exit(1);
}
}
private static void printUsage() {
System.out.println("Usage: java TryToConnectToDb DRIVER URL USER PASSWORD NUMBER_OF_TRIES");
}
}
|
package com.base.widget.cobe.ptr.header;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.base.widget.cobe.ptr.PtrFrameLayout;
import com.base.widget.cobe.ptr.PtrUIHandler;
import com.base.widget.cobe.ptr.indicator.PtrIndicator;
import com.wmlives.heihei.R;
public class JiyuHeaderArrow extends RelativeLayout implements PtrUIHandler {
private int ARROW_SIZE = 43;
private int PB_SIZE = 31;
public JiyuHeaderArrow(Context context) {
super(context);
init();
}
public JiyuHeaderArrow(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public JiyuHeaderArrow(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
// ----------------R.layout.jiyu_header_arrow-------------Start
private JiyuHeaderArrowView arrowView;
private ProgressBar pb;
public void autoLoad_jiyu_header_arrow() {
arrowView = (JiyuHeaderArrowView) findViewById(R.id.arrowView);
pb = (ProgressBar) findViewById(R.id.pb);
}
// ----------------R.layout.jiyu_header_arrow-------------End
private void init() {
final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
final float screenDensity = metrics.density;
LayoutInflater.from(getContext()).inflate(R.layout.jiyu_header_arrow, this);
autoLoad_jiyu_header_arrow();
arrowView.onLevelChange(0);
arrowView.setVisibility(View.VISIBLE);
pb.setVisibility(View.GONE);
}
// PTR下拉刷新 UI控制接口 ----------------------------
/**
* Content 重新回到顶部, Header 消失,整个下拉刷新过程完全结束以后,重置 View 。
*/
public void onUIReset(PtrFrameLayout frame) {
arrowView.onLevelChange(0);
arrowView.setVisibility(View.VISIBLE);
pb.setVisibility(View.GONE);
}
/**
* 准备刷新,Header 将要出现时调用。
*/
public void onUIRefreshPrepare(PtrFrameLayout frame) {
arrowView.onLevelChange(0);
arrowView.setVisibility(View.VISIBLE);
pb.setVisibility(View.GONE);
}
/**
* 开始刷新,Header 进入刷新状态之前调用。
*/
public void onUIRefreshBegin(PtrFrameLayout frame) {
arrowView.setVisibility(View.INVISIBLE);
pb.setVisibility(View.VISIBLE);
}
/**
* 刷新结束,Header 开始向上移动之前调用。
*/
public void onUIRefreshComplete(PtrFrameLayout frame) {
arrowView.setVisibility(View.INVISIBLE);
pb.setVisibility(View.GONE);
}
/**
* header滑动时调用
*/
public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
if (ptrIndicator != null && arrowView != null) {
int mOffsetToRefresh = ptrIndicator.getOffsetToRefresh();// 滑动到多少距离 开始刷新
int currentPos = ptrIndicator.getCurrentPosY();// 已经滑动了多少距离
if (mOffsetToRefresh != 0) {
int level = (int) (currentPos * 100.0F / mOffsetToRefresh);
level = Math.max(level, 0);
level = Math.min(level, 100);
arrowView.onLevelChange(level);
}
}
}
}
|
package com.utils.redis.command;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.springframework.data.redis.core.query.SortQuery;
/**
* Interface Key Command Operations.
* <p>
* http://doc.redisfans.com/
* </p>
*
* @author memory 2017年5月11日 下午9:05:38
* @version V1.0
* @modificationHistory=========================逻辑或功能性重大变更记录
* @modify by user: {修改人} 2017年5月11日
* @modify by reason:{方法名}:{原因}
*/
public interface CommandRedisOperation {
/**
* Key(键),简单的key-value操作 实现命令:DEL key,删除一个key。不存在的 key 会被忽略。
*
* @author memory 2017年5月11日 上午11:27:40
* @param key
*/
void del(String key);
/**
* Key(键),简单的key-value操作 实现命令:DEL [key ...],删除多个key。不存在的 key 会被忽略。
*
* @author memory 2017年5月12日 上午10:41:20
* @param keys
*/
void del(Collection<String> keys);
/**
* Key(键),简单的key-value操作 实现命令:DUMP key。序列化给定 key ,并返回被序列化的值,使用 RESTORE 命令可以将这个值反序列化为 Redis 键。
*
* <p>
* 序列化生成的值有以下几个特点: 它带有 64 位的校验和,用于检测错误, RESTORE 在进行反序列化之前会先检查校验和。 值的编码格式和 RDB 文件保持一致。 RDB 版本会被编码在序列化值当中,如果因为 Redis
* 的版本不同造成 RDB 格式不兼容,那么 Redis 会拒绝对这个值进行反序列化操作。 序列化的值不包括任何生存时间信息。
* </p>
*
* @author memory 2017年5月12日 上午10:46:03
* @param key
* @return 如果 key 不存在,那么返回 nil 。否则,返回序列化之后的值。
*/
byte[] dump(String key);
/**
* Key(键),简单的key-value操作 实现命令:EXISTS key。检查给定 key 是否存在。
*
* @author memory 2017年5月12日 上午10:55:04
* @param key
* @return
*/
Boolean exists(String key);
/**
* Key(键),简单的key-value操作 实现命令:EXPIRE key seconds。为给定 key 设置生存时间,当 key 过期时(生存时间为 0 ),它会被自动删除。
*
* @author memory 2017年5月12日 上午11:04:20
* @param key
* @param timeout
* @return 当 key 不存在或者不能为 key 设置生存时间时(比如在低于 2.1.3 版本的 Redis 中你尝试更新 key 的生存时间),返回 false 。
*/
Boolean expire(String key, long timeout);
/**
* Key(键),简单的key-value操作 实现命令:EXPIREAT key timestamp。
*
* <p>EXPIREAT 的作用和 EXPIRE 类似,都用于为 key 设置生存时间。不同在于 EXPIREAT 命令接受的时间参数是 UNIX 时间戳(unix timestamp)。</p>
*
* @author memory 2017年5月12日 上午11:06:59
* @param key
* @param timestamp 单位:seconds,UNIX 时间戳(unix timestamp),从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数
* @return 当 key 不存在或没办法设置生存时间,返回false
*/
Boolean expireAt(String key, long timestamp);
/**
* Key(键),简单的key-value操作 实现命令:KEYS pattern,查找所有符合给定模式 pattern的 key。
*
* <p>KEYS * 匹配数据库中所有 key 。</p>
* <p>KEYS h?llo 匹配 hello , hallo 和 hxllo 等。</p>
* <p>KEYS h*llo 匹配 hllo 和 heeeeello 等。</p>
* <p>KEYS h[ae]llo 匹配 hello 和 hallo ,但不匹配 hillo 。</p>
*
* @author memory 2017年5月11日 上午11:27:06
* @param pattern
* @return
*/
Set<String> keys(String pattern);
/**
* Key(键),简单的key-value操作 实现命令:MOVE key db。将当前数据库的 key 移动到给定的数据库 db 当中。
*
* <p>如果当前数据库(源数据库)和给定数据库(目标数据库)有相同名字的给定 key ,或者 key 不存在于当前数据库,那么 MOVE 没有任何效果。</p>
*
* @author memory 2017年5月12日 上午11:31:14
* @param key
* @param db
* @return
*/
Boolean move(String key, int db);
/**
* Key(键),简单的key-value操作 实现命令:PERSIST key。
*
* <p>移除给定 key 的生存时间,将这个 key 从『易失的』(带生存时间 key )转换成『持久的』(一个不带生存时间、永不过期的 key )。</p>
*
* @author memory 2017年5月12日 上午11:47:29
* @param key
* @return 如果 key 不存在或 key 没有设置生存时间,返回false。
*/
Boolean persist(String key);
/**
* Key(键),简单的key-value操作 实现命令:PEXPIRE key milliseconds。
*
* <p>这个命令和 EXPIRE 命令的作用类似,但是它以毫秒为单位设置 key 的生存时间,而不像 EXPIRE 命令那样,以秒为单位。</p>
*
* @author memory 2017年5月12日 上午11:51:37
* @param key
* @param milliseconds 毫秒
* @return
*/
Boolean pExpire(String key, long milliseconds);
/**
* Key(键),简单的key-value操作 实现命令:PEXPIREAT key milliseconds-timestamp。
*
* <p>这个命令和 EXPIREAT 命令类似,但它以毫秒为单位设置 key 的过期 unix 时间戳,而不是像 EXPIREAT 那样,以秒为单位。</p>
*
* @author memory 2017年5月12日 下午12:06:33
* @param key
* @param millisecondsTimestamp 单位:milliseconds,UNIX 时间戳(unix timestamp),从格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数。
* @return
*/
Boolean pExpireAt(String key, long millisecondsTimestamp);
/**
* Key(键),简单的key-value操作 实现命令:TTL key,以millseconds为单位,返回给定 key的剩余生存时间(TTL, time to live)
*
* @author memory 2017年5月12日 上午11:40:00
* @param key
* @return 返回毫秒millseconds
*/
Long pTTL(String key);
/**
* Key(键),简单的key-value操作 实现命令:RANDOMKEY。从当前数据库中随机返回(不删除)一个 key 。
*
* @author memory 2017年5月12日 下午1:29:40
* @return当数据库为空时,返回 nil 。
*/
String randomKey();
/**
* Key(键),简单的key-value操作 实现命令:RENAME key newkey。将 key 改名为 newkey 。
*
* <p>当 key 和 newkey 相同,或者 key 不存在时,返回一个错误。当 newkey 已经存在时, RENAME 命令将覆盖旧值。</p>
*
* @author memory 2017年5月12日 下午1:32:44
* @param oldKey
* @param newKey
*/
void rename(String oldKey, String newKey);
/**
* Key(键),简单的key-value操作 实现命令:RENAMENX key newkey。当且仅当 newkey 不存在时,将 key 改名为 newkey 。当 key 不存在时,返回一个错误。
* @author memory 2017年5月12日 下午1:35:14
* @param oldKey
* @param newKey
* @return 如果 newkey 已经存在,返回false
*/
Boolean renameNX(String oldKey, String newKey);
/**
* Key(键),简单的key-value操作 实现命令:RESTORE key ttl serialized-value。反序列化给定的序列化值,并将它和给定的 key 关联。
*
* @author memory 2017年5月12日 下午1:39:51
* @param key
* @param timeToLive 参数 ttl 以毫秒为单位为 key 设置生存时间;如果 ttl 为 0 ,那么不设置生存时间。
* @param serializedValue 序列化值
*/
void sort(String key, long timeToLive, byte[] serializedValue);
/**
* Key(键),简单的key-value操作 实现命令:SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC | DESC] [ALPHA] [STORE destination]。
*
* 排序默认以数字作为对象,值被解释为双精度浮点数,然后进行比较。
*
* @author memory 2017年5月12日 下午5:57:35
* @param sortQuery
* @return 返回或保存给定列表、集合、有序集合 key 中经过排序的元素。
*/
List<String> sort(SortQuery<String> sortQuery);
/**
* Key(键),简单的key-value操作 实现命令:TTL key,以秒为单位,返回给定 key的剩余生存时间(TTL, time to live)
*
* @author memory 2017年5月11日 上午11:26:27
* @param key
* @return 返回秒seconds
*/
Long ttl(String key);
/**
* Key(键),简单的key-value操作 实现命令:TYPE key。返回 key 所储存的值的类型。
* @author memory 2017年5月15日 下午4:14:08
* @param key
* @return null (key不存在)、string (字符串)、list (列表)、set (集合)、zset (有序集)、hash (哈希表)
*/
String redisType(String key);
}
|
package com.nexlesoft.tenwordsaday_chiforeng.fragment;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import com.nexlesoft.tenwordsaday_chiforeng.DHConstant;
import com.nexlesoft.tenwordsaday_chiforeng.R;
import com.nexlesoft.tenwordsaday_chiforeng.base.BaseFragment;
import com.nexlesoft.tenwordsaday_chiforeng.base.SessionManager;
import com.nexlesoft.tenwordsaday_chiforeng.db.LevelDataSource;
import com.nexlesoft.tenwordsaday_chiforeng.db.SessionDataSource;
import com.nexlesoft.tenwordsaday_chiforeng.db.WordDataSource;
import com.nexlesoft.tenwordsaday_chiforeng.model.Level;
import com.nexlesoft.tenwordsaday_chiforeng.model.Session;
import com.nexlesoft.tenwordsaday_chiforeng.model.Setting;
import com.nexlesoft.tenwordsaday_chiforeng.model.Word;
import com.nexlesoft.tenwordsaday_chiforeng.model.Word.WordStatus;
import com.nexlesoft.tenwordsaday_chiforeng.utilities.Util;
import com.nexlesoft.tenwordsaday_chiforeng.widget.FontableButton;
import com.nexlesoft.tenwordsaday_chiforeng.widget.FontableTextView;
public class ActivitySummaryFragment extends BaseFragment implements OnClickListener {
private FontableTextView mtxtWordLearn, mtxtRemain, mtxtCompleted, mtxtObjective, mtxtSpentLearning, mTxtLevel,
mTxtSession;
private FontableButton mBtnStartSession;
private boolean mBIsFinished = false;
// private int m_nCurrentLevelId;
@SuppressWarnings("unchecked")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = (View) inflater.inflate(R.layout.fragment_activity_summary, container, false);
mActivity.setTitle(getString(R.string.str_activity_summary));
mBtnStartSession = (FontableButton) mRootView.findViewById(R.id.btn_start_session);
mBtnStartSession.setOnClickListener(this);
mtxtWordLearn = (FontableTextView) mRootView.findViewById(R.id.txt_word_learn_count);
mtxtRemain = (FontableTextView) mRootView.findViewById(R.id.txt_word_remain);
mtxtCompleted = (FontableTextView) mRootView.findViewById(R.id.txt_word_complete);
mtxtObjective = (FontableTextView) mRootView.findViewById(R.id.txt_total_object);
mtxtSpentLearning = (FontableTextView) mRootView.findViewById(R.id.txt_spend_time);
mTxtLevel = (FontableTextView) mRootView.findViewById(R.id.txt_level);
mTxtSession = (FontableTextView) mRootView.findViewById(R.id.txt_session);
/* check set up level */
LevelDataSource levelDS = new LevelDataSource(mActivity);
levelDS.open();
int levelCount = levelDS.getLevelCount();
int sessionInLevelCount = 0;
if (levelCount <= 0) {
levelCount = 1;
/* set up new level */
levelDS.insert(new Level(0, new Date().toString(), DHConstant.LEVEL_MAX_QUESTION_NUMBER, 0,
DHConstant.LEVEL_REQUIRE_QUESTION_NUMBER, false));
}
// m_nCurrentLevelId = levelDS.getLastLevel().id;
mTxtLevel.setText(levelCount + "");
WordDataSource wordDS = new WordDataSource(mActivity);
wordDS.open();
ArrayList<Word> words = (ArrayList<Word>) (ArrayList<?>) wordDS.getAllData();
wordDS.close();
SessionDataSource sessionDS = new SessionDataSource(mActivity);
sessionDS.open();
ArrayList<Session> sessionList = (ArrayList<Session>) (ArrayList<?>) sessionDS.getAllData();
if (levelCount > 0) {
sessionInLevelCount = sessionDS.GetFinishedSessionCount();
sessionInLevelCount++;
mTxtSession.setText(sessionInLevelCount + "");
}
sessionDS.close();
long spendLongTime = 0;
if (sessionList != null) {
for (Session session : sessionList) {
spendLongTime += session.longTimeSpent;
}
}
int wordLearnedNum = 0, wordRemainNum = 0;
if (words != null && words.size() > 0) {
for (Word word : words) {
if (word.status == WordStatus.GOT_IT) {
wordLearnedNum++;
}
}
Setting setting = SessionManager.getInstance(mActivity).getSetting();
if (setting != null) {
setting.overalObjectiveNum = setting.overalObjectiveNum == 0 ? words.size()
: setting.overalObjectiveNum;
setting.maxObject = words.size();
setting.allSpendTime = Util.convertLongToDateString(spendLongTime, true, true, false);
wordRemainNum = setting.overalObjectiveNum - wordLearnedNum;
float completePercent = ((float) wordLearnedNum / (float) setting.overalObjectiveNum) * 100;
mtxtRemain.setText(wordRemainNum + "");
mtxtCompleted.setText(new DecimalFormat("#.##").format(completePercent) + "%");
mtxtObjective.setText(setting.overalObjectiveNum + "");
mtxtSpentLearning.setText(setting.allSpendTime);
if (completePercent == 100) {
mBtnStartSession.setText(getString(R.string.str_reset_session));
mBIsFinished = true;
}
}
mtxtWordLearn.setText(wordLearnedNum + "");
}
return mRootView;
}
@Override
public void ClearInstance() {
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start_session:
if (mBIsFinished)
mActivity.resetDBData();
mActivity.pushFragments(new LearningSessionFragment(), true, false);
// /* check exam */
// WordDataSource wordDS = new WordDataSource(mActivity);
// wordDS.open();
// int gotItWordNum = wordDS.getWordCountInLevel(WordStatus.GOT_IT,
// m_nCurrentLevelId);
// wordDS.close();
//
// if (gotItWordNum >=
// DHConstant.LEVEL_MAX_WORD_REQUIRE_TO_START_EXAM)
// mActivity.pushFragments(new ExamFragment(), true, false);
// else
// mActivity.pushFragments(new LearningSessionFragment(), true,
// false);
break;
default:
break;
}
}
}
|
package com.example.bootcamp;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import com.example.bootcamp.controller.UserController;
@RunWith(SpringRunner.class)
@WebMvcTest(value = UserController.class)
@ContextConfiguration(classes = {TestContext.class, WebApplicationContext.class})
public class TestUserController {
@Autowired
private MockMvc mvc;
@MockBean
private UserController userController;
@Test
public void loginUser() throws Exception {
String exampleUserJson = "{ \"emailorPhone\": \"9599944411\", \"password\": \"Qwerty@123\"}";
mvc.perform(post("/login")
.content(exampleUserJson)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
@Test
public void registerUser() throws Exception {
String registerJson = "{\"email\": \"shubhamgupta@gmail.com\",\"firstName\": \"shubham\",\"gender\": \"Male\",\"lastName\": \"gupta\",\"password\": \"Qwerty@123\",\"phone\": \"9654259677\",\"userType\": \"USER\"}";
mvc.perform(post("/user/register")
.content(registerJson)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
|
public abstract class Enemy extends Base {
public abstract void attack(Base player);
}
|
package test.AbstractFactory.button;
import test.AbstractFactory.button.inter.Button;
/**
* Spring按钮:具体产品
* @author lho
*
*/
public class SpringButton implements Button {
@Override
public void display() {
System.out.println("显示浅绿色按钮。");
}
}
|
/*
* (C) Copyright 2018 Fresher Academy. All Rights Reserved.
*
* @author viettn.admin
* @date Apr 20, 2018
* @version 1.0
*/
package edu.fa.pattern.adapter;
import edu.fa.service.EmployeeService;
import edu.fa.service.HrService;
public class ClassAdapterService extends HrService implements EmployeeService{
public String getDetails(int id) {
// TODO Auto-generated method stub
return getStatus(id) + " " + getSalary(id);
}
}
|
package product;
//abstract product
public interface Product {
// ...
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.