blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
72d14cf9c0b5de4fa29df0ae2d70754ea313d69f | 6ec5c29ce081c63f25e37444a157a36a72564618 | /handler/promotionData.java | d9b0553eb21c86fb011ac9d2924748ba9e23ed36 | [] | no_license | SameetPati/PromotionalService | 4434d8fda2830182a3eb4c61ace7bce2523471c3 | b27f642387dbefe2b2b45a99f3939f19c3182fb7 | refs/heads/master | 2022-12-14T04:27:15.259396 | 2020-09-22T10:44:01 | 2020-09-22T10:44:01 | 297,595,743 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,045 | java | package handler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import data.sku;
public class promotionData {
public HashMap<List<String>, Integer> formatData(String inputString, sku skuObject) {
HashMap<List<String>, Integer> promoObject = new HashMap<List<String>, Integer>();
try {
HashMap<String, Integer> aa = skuObject.getSKUData();
Scanner inputStr = new Scanner(inputString).useDelimiter("EOL ");
while (inputStr.hasNext()) {
String x = inputStr.next();
int count = 0;
List<String> listData = new ArrayList<String>();
for (String mapElement : aa.keySet()) {
if (x.contains(mapElement)) {
listData.add(mapElement);
count++;
}
}
if (count == 1) {
int cost = 0;
int num = 0;
String[] breakstr = x.split("of");
if (breakstr[0] != null) {
if (!breakstr[0].contains("%")) {
num = Integer.parseInt(breakstr[0].replaceAll("\\s", ""));
for (int i = 1; i < num; i++) {
listData.add(listData.get(0));
}
String[] breakfor = breakstr[1].split("for");
cost = Integer.parseInt(breakfor[1].replaceAll("\\s", ""));
promoObject.put(listData, cost);
} else {
num = Integer.parseInt(breakstr[0].replaceAll("\\s", "").replaceAll("%", ""));
cost = aa.get(listData.get(0)) - ((aa.get(listData.get(0)) * num) / 100);
promoObject.put(listData, cost);
}
}
} else {
String[] breakst = x.split("for");
int value = Integer.parseInt(breakst[1].replaceAll("\\s", ""));
promoObject.put(listData, value);
}
}
inputStr.close();
} catch (Exception e) {
throw new Error("Unable to parse the string");
}
return promoObject;
}
}
| [
"[email protected]"
] | |
0c851c56b02d717a2edf46d60f4b488f1b67298a | 20eb62855cb3962c2d36fda4377dfd47d82eb777 | /IntroClassJava/dataset/grade/d009aa71ece41454c68d8038b5462d8eea8feb291bce1d53ee149f8477b5eab62ee28c7f690bf14dc6ce1d70c8943f7f3b3e4300965cb24da4cd2d2807dab19a/000/mutations/7/grade_d009aa71_000.java | b3402953596a7429e5f019680a9e7286b92490f3 | [] | no_license | ozzydong/CapGen | 356746618848065cce4e253e5d3c381baa85044a | 0ba0321b6b1191443276021f1997833342f02515 | refs/heads/master | 2023-03-18T20:12:02.923428 | 2020-08-21T03:08:28 | 2020-08-21T03:08:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,515 | java | package introclassJava;
class IntObj {
public int value;
public IntObj () {
} public IntObj (int i) {
value = i;
}
}
class FloatObj {
public float value;
public FloatObj () {
} public FloatObj (float i) {
value = i;
}
}
class LongObj {
public long value;
public LongObj () {
} public LongObj (long i) {
value = i;
}
}
class DoubleObj {
public double value;
public DoubleObj () {
} public DoubleObj (double i) {
value = i;
}
}
class CharObj {
public char value;
public CharObj () {
} public CharObj (char i) {
value = i;
}
}
public class grade_d009aa71_000 {
public java.util.Scanner scanner;
public String output = "";
public static void main (String[]args) throws Exception {
grade_d009aa71_000 mainClass = new grade_d009aa71_000 ();
String output;
if (args.length > 0) {
mainClass.scanner = new java.util.Scanner (args[0]);
} else {
mainClass.scanner = new java.util.Scanner (System.in);
}
mainClass.exec ();
System.out.println (mainClass.output);
}
public void exec () throws Exception {
FloatObj A = new FloatObj (), B = new FloatObj (), C =
new FloatObj (), D = new FloatObj (), score = new FloatObj ();
output +=
(String.format
("Enter thresholds for A, B, C, D\nin that order, decreasing percentages > "));
A.value = scanner.nextFloat ();
B.value = scanner.nextFloat ();
C.value = scanner.nextFloat ();
D.value = scanner.nextFloat ();
output +=
(String.format ("Thank you. Now enter student score (percent) > "));
score.value = scanner.nextFloat ();
if (score.value >= A.value) {
output += (String.format ("Student has an A grade\n"));
}
if ((score.value < A.value) && (score.value >= B.value)) {
output += (String.format ("Student has a B grade\n"));
}
if ((score.value < B.value) && (score.value >= C.value)) {
output += (String.format ("Student has a C grade\n"));
}
if ((score.value < C.value) && (score.value >= D.value)) {
output += (String.format ("Student has a D grade\n"));
}
if (score.value < B.value) {
output += (String.format ("Student has failed the course\n"));
}
if (true)
return;;
}
}
| [
"[email protected]"
] | |
f717d495db2961b1b654f5d5a53dddc55d6dc386 | 77f0d29d38c026b1cd89e9ae066aa225cd973306 | /youlaiwang/app/src/main/java/com/bm/chengshiyoutian/youlaiwang/oldall/oldview/activity/ResturantDetaisActivity.java | 9fe63f7903e804c45fa38c60ca39a1cbac9e1ee4 | [] | no_license | z453240360/YouLaiNew | 2284458aaf7c85bc85b32c458d0ea6008de5141a | 72279ad46b7336e25f6a7cb6bcf646de16be30bd | refs/heads/master | 2021-08-28T11:06:33.266581 | 2017-12-12T02:26:11 | 2017-12-12T02:26:11 | 110,525,435 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,758 | java | package com.bm.chengshiyoutian.youlaiwang.oldall.oldview.activity;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.TextView;
import com.android.pc.ioc.inject.InjectHttpErr;
import com.android.pc.ioc.inject.InjectHttpOk;
import com.android.pc.ioc.internet.FastHttpHander;
import com.android.pc.ioc.internet.InternetConfig;
import com.android.pc.ioc.internet.ResponseEntity;
import com.bm.chengshiyoutian.youlaiwang.R;
import com.bm.chengshiyoutian.youlaiwang.activity.XiangQingActivity;
import com.bm.chengshiyoutian.youlaiwang.app.MyApplication;
import com.bm.chengshiyoutian.youlaiwang.oldall.oldview.adapter.CommentAdapter;
import com.bm.chengshiyoutian.youlaiwang.oldall.oldview.bean.CommentBean;
import com.bm.chengshiyoutian.youlaiwang.oldall.oldview.constant.Constants;
import com.bm.chengshiyoutian.youlaiwang.oldall.oldview.utils.MyToastUtils;
import com.bm.chengshiyoutian.youlaiwang.oldall.oldview.view.RoundImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* 餐厅详情
* Created by youj on 2016/1/14.
*/
public class ResturantDetaisActivity extends Activity implements View.OnClickListener {
@Bind(R.id.iv_left)
ImageView ivLeft;
@Bind(R.id.title)
TextView title;
@Bind(R.id.lv)
ListView lv;
@Bind(R.id.photo)
RoundImageView photo;
@Bind(R.id.app_ratingbar)
RatingBar appRatingbar;
@Bind(R.id.tv_new_oil_num)
TextView tvNewOilNum;
@Bind(R.id.tv_total_oil_num)
TextView tvTotalOilNum;
@Bind(R.id.tv_new_junk_num)
TextView tvNewJunkNum;
@Bind(R.id.tv_total_junk_num)
TextView tvTotalJunkNum;
@Bind(R.id.tv_current_scale)
TextView tvCurrentScale;
@Bind(R.id.tv_history_scale)
TextView tvHistoryScale;
@Bind(R.id.ll_more_comment)
LinearLayout llMoreComment;
@Bind(R.id.iv_right)
ImageView ivRight;
@Bind(R.id.tv_cook_type)
TextView tvCookType;
@Bind(R.id.tv_phone)
TextView tvPhone;
@Bind(R.id.tv_address)
TextView tvAddress;
@Bind(R.id.tv_integral)
TextView tvIntegral;
@Bind(R.id.tv_qr_code)
TextView tvQrCode;
@Bind(R.id.textView3)
TextView textView3;
@Bind(R.id.textView4)
TextView textView4;
@Bind(R.id.textView6)
TextView textView6;
@Bind(R.id.textView7)
TextView textView7;
@Bind(R.id.tv1)
TextView tv1;
@Bind(R.id.tv2)
TextView tv2;
@Bind(R.id.tv_restaurant_name)
TextView tvRestaurantName;
private CommentAdapter adapter;
private ArrayList<CommentBean> commentList = new ArrayList<>();
private ProgressDialog progressDialog;
private String id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_resturant_detais);
ButterKnife.bind(this);
init();
}
private void init() {
title.setText("餐厅详情");
progressDialog = new ProgressDialog(this);
progressDialog.show();
id = getIntent().getStringExtra("id");
getDetais(id);
getCommentList(id);
ivRight.setVisibility(View.VISIBLE);
ivRight.setImageResource(R.mipmap.home);
ivRight.setOnClickListener(this);
ivLeft.setOnClickListener(this);
llMoreComment.setOnClickListener(this);
tvQrCode.setOnClickListener(this);
tvPhone.setOnClickListener(this);
adapter = new CommentAdapter(this, commentList, R.layout.item_comment);
lv.setAdapter(adapter);
}
/**
* 获取餐厅评论列表
*
* @param id
*/
private void getCommentList(String id) {
LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
InternetConfig config = new InternetConfig();
config.setKey(1);
params.put("id", id);
params.put("pageIndex", "1");
params.put("pageSize", "3");
config.setTimeout(Constants.TIMEOUT);
FastHttpHander.ajaxWebServer(Constants.RESTAURANT_URL, "GetCommentList", params, config, this);
}
@InjectHttpOk
private void ok(ResponseEntity entity) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
switch (entity.getKey()) {
case 1:
try {
JSONObject jsonObject = new JSONObject(entity.getContentAsString());
if (0 == jsonObject.getInt("status")) {
JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("ds");
int length = jsonArray.length();
for (int i = 0; i < length; i++) {
JSONObject object = jsonArray.optJSONObject(i);
String content = object.optString("content");
String time = object.optString("add_time");
commentList.add(new CommentBean(content, time));
}
adapter.setData(commentList);
} else {
MyToastUtils.show(this, "数据获取失败");
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
case 0:
try {
JSONObject object = new JSONObject(entity.getContentAsString());
if (object.optInt("status") == 0) {
JSONObject jsonObject = object.optJSONArray("data").getJSONObject(0);
String retaurantName = jsonObject.optString("title");
String img_url = jsonObject.optString("img_url");
String retaurantAddress = jsonObject.optString("seo_title");
String phone = jsonObject.optString("seo_keywords"); //电话
String cookType = jsonObject.optString("category_name"); //菜系名
String internal = jsonObject.optString("score");
String xing = jsonObject.optString("xing");//星级
String zxjy = jsonObject.optString("zxjy");//最新交油
String jyzl = jsonObject.optString("jyzl");//交油总量
String zxcclj = jsonObject.optString("zxcclj");//最新餐厨垃圾
String ccljzl = jsonObject.optString("ccljzl");//餐厨垃圾总量
String dqzhbl = jsonObject.optString("dqzhbl");//当前转换比例
String lszhbl = jsonObject.optString("lszhbl");//历史转换比例
tvRestaurantName.setText(retaurantName);
ImageLoader.getInstance().displayImage(img_url, photo, MyApplication.getInstance().getOptions());
tvAddress.setText(retaurantAddress);
tvPhone.setText(phone);
tvCookType.setText(cookType);
tvIntegral.setText(TextUtils.isEmpty(internal) ? "0" : internal);
tvNewOilNum.setText(zxjy);
tvNewJunkNum.setText(zxcclj);
tvTotalOilNum.setText(TextUtils.isEmpty(jyzl) ? "0" : jyzl);
tvTotalJunkNum.setText(TextUtils.isEmpty(ccljzl) ? "0" : ccljzl);
tvCurrentScale.setText(dqzhbl);
tvHistoryScale.setText(lszhbl);
appRatingbar.setRating(Float.parseFloat(xing));
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
@InjectHttpErr
public void err(ResponseEntity entity) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
MyToastUtils.show(this, getString(R.string.intnet_err));
}
private void getDetais(String id) {
LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
InternetConfig config = new InternetConfig();
config.setKey(0);
params.put("_id", id);
config.setTimeout(Constants.TIMEOUT);
FastHttpHander.ajaxWebServer(Constants.RESTAURANT_URL, "GetRestaurantDetail", params, config, this);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.iv_left:
finish();
break;
case R.id.iv_right:
startActivity(new Intent(this, XiangQingActivity.class));
finish();
break;
case R.id.tv_phone:
callPhone();
break;
case R.id.tv_qr_code: //二维码
Intent intent2 = new Intent(this, QRCodeActivity.class);
intent2.putExtra("id", this.id);
startActivity(intent2);
break;
case R.id.ll_more_comment: //用户评论
if (commentList.size() == 0) {
MyToastUtils.show(this, "没有更多评论");
return;
}
Intent intent = new Intent(this, UserCommentActivity.class);
intent.putExtra("id", this.id);
startActivity(intent);
break;
default:
break;
}
}
/**
* 弹出打电话的dialog
*/
private void callPhone() {
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_call_phone, null);
final PopupWindow pop = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, -2);
pop.setFocusable(true);
pop.setOutsideTouchable(true);
final WindowManager.LayoutParams params = getWindow().getAttributes();//创建当前界面的一个参数对象
params.alpha = 0.5f;//设置参数的透明度
getWindow().setAttributes(params);
pop.showAtLocation(view, Gravity.BOTTOM, 0, 15);
final TextView phone = (TextView) view.findViewById(R.id.tv_phone);
final String phoneNum = tvPhone.getText().toString();
phone.setText(phoneNum);
TextView cancel = (TextView) view.findViewById(R.id.tv_cancel);
phone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNum));
if (ActivityCompat.checkSelfPermission(ResturantDetaisActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(ResturantDetaisActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 100);
return;
}
startActivity(intent);
pop.dismiss();
params.alpha = 1f;//设置参数的透明度
getWindow().setAttributes(params);
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pop.dismiss();
params.alpha = 1f;//设置参数的透明度
getWindow().setAttributes(params);
}
});
}
}
| [
"[email protected]"
] | |
55474813addc2d574fe508bc9cfe11bdfe58f0c8 | 7589951c83cc9c0052ac716ba70bd71848191d49 | /src/main/java/TaskList.java | 899df292fb34205267ceff183bba1ee0d278438f | [] | no_license | mirozo/duke | 255d48579733b12dbf4487a0f810479528267984 | 1087143d285ea590e3cb0d05121e76fbc2e7175b | refs/heads/master | 2020-07-07T11:26:12.372926 | 2019-09-24T15:23:05 | 2019-09-24T15:23:05 | 203,335,973 | 0 | 0 | null | 2019-09-19T02:48:25 | 2019-08-20T08:43:48 | Java | UTF-8 | Java | false | false | 3,419 | java | import tasks.Task;
import tasks.Event;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class TaskList {
private ArrayList<Task> list;
public TaskList(ArrayList<Task> list) {
this.list = list;
}
/**
* Gets the ArrayList from a TaskList object.
*
* @return ArrayList of Tasks
*/
public ArrayList<Task> getList() {
return list;
}
/**
* Adds a task to the TaskList.
*
* @param task Task to be added
*/
public void addTask(Task task) {
list.add(task);
}
/**
* Deletes the task in the specified index.
* @param position index of task in task list.
* @return The deleted task.
*/
public Task deleteTask(String position) {
int index = Integer.parseInt(position) - 1;
assert index >= 0 : "index should not be negative";
Task currTask = list.get(index);
list.remove(index);
return currTask;
}
/**
* Change the status of a task of position p in the TaskList
* to "done" and returns the updated Task.
*
* @param position index + 1 of the task in the list.
* @return Updated Task.
*/
public Task doTask(String position) {
int index = Integer.parseInt(position) - 1;
assert index >= 0 : "index should not be negative";
Task currTask = list.get(index);
currTask.doTask();
return currTask;
}
/**
* Gets a list of dates that are already filled up.
* @return ArrayList of dates that are unavailable.
*/
public ArrayList<Date> getFilledTimeSlots() {
ArrayList<Date> timeSlots = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
Task task = list.get(i);
if (task instanceof Event) {
Date date = ((Event) task).getAt();
timeSlots.add(date);
}
}
return timeSlots;
}
/**
* Finds the next available date and time that has a
* time slot of the specified duration.
* @param duration Duration of time slot needed.
* @return Date of next available time slot.
*/
public Date findFreeTime(int duration) {
ArrayList<Date> timeSlots = this.getFilledTimeSlots();
Date currentTime = new Date();
while (true) {
boolean passed = true;
for (Date slot: timeSlots) {
long diff = slot.getTime() - currentTime.getTime();
int diffHours = (int) (diff / (60 * 60 * 1000));
if (diffHours >= -duration && diffHours <= duration) {
passed = false;
break;
}
}
if (passed) {
break;
} else {
currentTime = addHours(currentTime, 1);
}
}
return currentTime;
}
/**
* Adds the number of specified hours to a give date.
* @param currentDate Given date.
* @param hours Number of hours to be added.
* @return Date with hours added.
*/
public static Date addHours(Date currentDate, int hours) {
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(currentDate); // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, hours); // adds one hour
return cal.getTime();
}
}
| [
"[email protected]"
] | |
21481ad2f6204098aa714667ece2b8ae08c41e37 | 5449824379ef6828cf3dacafe2ab4ab720f663f5 | /.svn/pristine/b6/b6de40d2cdfe32494ee49901d3219b34ad43601f.svn-base | c478b5dc24f0e883e5b3fdc3799f86bb926b1f68 | [] | no_license | Xdone111/beyou | 38735050db0b1daa224cc4064c0858eefc68fb84 | f24acc510070b108f954e4ff1515c4918a322962 | refs/heads/master | 2020-03-17T00:38:40.571483 | 2018-05-12T07:56:17 | 2018-05-12T07:56:17 | 133,125,004 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 969 | package byou.yadun.wallet.wallet.Transaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import byou.yadun.wallet.R;
/**
* Created by Administrator on 2017/8/30.
*/
public class ItemFragmentSell extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//动态找到布局文件,再从这个布局中find出TextView对象
View contextView = inflater.inflate(R.layout.fragment_item_sell, container, false);
//获取Activity传递过来的参数
Bundle mBundle = getArguments();
String title = mBundle.getString("arg");
return contextView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
| [
"[email protected]"
] | ||
c40a5e9393e09f76a0d98b1c9526306ec9c1a326 | b668113c831e821fd46bfa9e991e251ace8a650f | /src/main/java/com/bo/PoliceStationBO.java | 9fbca1e8648ca5ae932e071d0188737fda7c1608 | [] | no_license | sam980464/forSpringDemo | bfa81c09ff8512ea055db5d2bc465f22c2a378f6 | b9f0be8ec853a86e4de2474e12b54b2f2f0c0905 | refs/heads/master | 2022-11-18T11:10:58.658268 | 2019-09-24T11:37:02 | 2019-09-24T11:37:02 | 210,587,054 | 0 | 0 | null | 2022-11-16T05:48:15 | 2019-09-24T11:34:34 | Java | UTF-8 | Java | false | false | 675 | java | package com.bo;
public class PoliceStationBO {
private int id;
private String policeStationName;
private String address;
private int status;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getPoliceStationName() {
return this.policeStationName;
}
public void setPoliceStationName(String policeStationName) {
this.policeStationName = policeStationName;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public int getStatus() {
return this.status;
}
public void setStatus(int status) {
this.status = status;
}
} | [
"[email protected]"
] | |
af86011eeae4ada597047632b59befa38817c78b | b6d3f0de2abd55c25dac5079f81058246b25c2f0 | /MAS-war/src/java/AFOSmanagedbean/ViewFiCrewDetailManagedBean.java | 87cbdc76dece37c8eda0ac1c1c6989aa265d0224 | [] | no_license | lvmilk/RepositoryName | b7416ae899fcf6d2222cd0c57e78d42de3497d24 | f2fd8f2b8fec9bff6f10354c804b3a96336ef565 | refs/heads/master | 2021-01-01T15:45:04.092237 | 2015-11-24T09:59:27 | 2015-11-24T09:59:27 | 41,839,290 | 6 | 6 | null | null | null | null | UTF-8 | Java | false | false | 11,432 | java | /*
* 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 AFOSmanagedbean;
import Entity.APS.FlightInstance;
import Entity.CommonInfa.CabinCrew;
import Entity.CommonInfa.CockpitCrew;
import SessionBean.AFOS.CrewSchedulingBeanLocal;
import SessionBean.APS.FlightSchedulingBeanLocal;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
/**
*
* @author Xu
*/
@Named(value = "VFCDMB")
@ViewScoped
public class ViewFiCrewDetailManagedBean implements Serializable {
@EJB
private CrewSchedulingBeanLocal csb;
@EJB
private FlightSchedulingBeanLocal fsb;
private Long fiId;
private FlightInstance fi;
private List<CabinCrew> cabinleaderList = new ArrayList<>();
private List<CabinCrew> cabincrewList = new ArrayList<>();
private List<CockpitCrew> captainList = new ArrayList<>();
private List<CockpitCrew> pilotList = new ArrayList<>();
private List<CabinCrew> cabinList = new ArrayList<>();
private List<CockpitCrew> cockpitList = new ArrayList<>();
private List<CabinCrew> idleCabincrew = new ArrayList<>();
private List<CabinCrew> idleCabinleader = new ArrayList<>();
private List<CockpitCrew> idleCaptain = new ArrayList<>();
private List<CockpitCrew> idlePilot = new ArrayList<>();
// private List<CabinCrew> idleCabin = new ArrayList<>();
// private List<CockpitCrew> idleCockpit = new ArrayList<>();
private String removeCc;
private String removeCp;
private String addCrewType;
private List<String> crewTypeList = new ArrayList<>();
private String addCrewId;
private List<String> addCrewIdList = new ArrayList<>();
public ViewFiCrewDetailManagedBean() {
}
@PostConstruct
public void init() {
fiId = (Long) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("fiId");
fi = fsb.findFlight(fiId);
initCPCC();
initIdleCPCC();
crewTypeList.add("Captain");
crewTypeList.add("Pilot");
crewTypeList.add("Cabin Leader");
crewTypeList.add("Cabin Crew");
}
public void initCPCC() {
cabinList = fi.getCabinList();
cockpitList = fi.getCockpitList();
for (CabinCrew cc : cabinList) {
if (cc.getStfLevel().equalsIgnoreCase("Cabin Leader")) {
cabinleaderList.add(cc);
} else {
cabincrewList.add(cc);
}
}
for (CockpitCrew cc : cockpitList) {
if (cc.getStfLevel().equalsIgnoreCase("Captain")) {
captainList.add(cc);
} else {
pilotList.add(cc);
}
}
System.out.println("initCPCC() cabinleaderList " + cabinleaderList);
System.out.println("initCPCC() cabincrewList " + cabincrewList);
System.out.println("initCPCC() captainList " + captainList);
System.out.println("initCPCC() pilotList " + pilotList);
}
public void initIdleCPCC() {
idleCabincrew = csb.getIdleCabin("Cabin Crew", fi);
idleCabinleader = csb.getIdleCabin("Cabin Leader", fi);
idleCaptain = csb.getIdleLicensedCockpit("Captain", fi);
idlePilot = csb.getIdleLicensedCockpit("Pilot", fi);
}
public void setCpCrewInfo() {
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
removeCp = params.get("removeCp");
System.out.println("Call this method? cp = " + removeCp);
}
public void setCcCrewInfo() {
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
removeCc = params.get("removeCc");
System.out.println("Call this method? cc = " + removeCc);
}
public void deleteCpFromFlight() {
CockpitCrew cp = csb.findCPById(removeCp);
csb.removeCpFromFlight(fi, cp);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Remove cockpit crew success", "Cockpit crew " + cp.getCpName() + " has been remove from flight " + fi));
}
public void deleteCcFromFlight() {
System.out.println("AAAAA here removeCc in managed bean");
CabinCrew cc = csb.findCCById(removeCc);
System.out.println("AAAAA here removeCc in managed bean *** cc == " + cc.getCbName());
csb.removeCcFromFlight(fi, cc);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Remove cabin crew success", "Cabin crew " + cc.getCbName() + " has been remove from flight " + fi));
}
public void addCrewToFlight() throws Exception {
try {
if (csb.getCrewType(addCrewId).equalsIgnoreCase("Cockpit")) {
csb.addCPToFlight(addCrewId, fiId);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Add cockpit crew success", "Cockpit crew " + addCrewId + " has been added to the flight " + fi));
}
if (csb.getCrewType(addCrewId).equalsIgnoreCase("Cabin")) {
csb.addCCToFlight(addCrewId, fiId);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Add cabin crew success", "Cabin crew " + addCrewId + " has been added to the flight " + fi));
}
} catch (Exception ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "An error has occurred : " + ex.getMessage(), ""));
}
}
public void onCrewTypeChange() {
switch (addCrewType) {
case "Captain": {
addCrewIdList = new ArrayList<String>();
for (CockpitCrew cc : idleCaptain) {
addCrewIdList.add(cc.getCpName());
}
break;
}
case "Pilot": {
addCrewIdList = new ArrayList<String>();
for (CockpitCrew cc : idlePilot) {
addCrewIdList.add(cc.getCpName());
}
break;
}
case "Cabin Leader": {
addCrewIdList = new ArrayList<String>();
for (CabinCrew cc : idleCabinleader) {
addCrewIdList.add(cc.getCbName());
}
break;
}
case "Cabin Crew": {
addCrewIdList = new ArrayList<String>();
for (CabinCrew cc : idleCabincrew) {
addCrewIdList.add(cc.getCbName());
}
break;
}
}
}
public void viewFCDetailBack() throws Exception {
FacesContext.getCurrentInstance().getExternalContext().redirect("./viewFiCrew.xhtml");
}
public void refresh() throws IOException {
System.out.println("REFRESH!");
FacesContext.getCurrentInstance().getExternalContext().redirect("./viewFiCrewDetail.xhtml");
}
public FlightInstance getFi() {
return fi;
}
public void setFi(FlightInstance fi) {
this.fi = fi;
}
public List<CabinCrew> getCabinleaderList() {
return cabinleaderList;
}
public void setCabinleaderList(List<CabinCrew> cabinleaderList) {
this.cabinleaderList = cabinleaderList;
}
public List<CabinCrew> getCabincrewList() {
return cabincrewList;
}
public void setCabincrewList(List<CabinCrew> cabincrewList) {
this.cabincrewList = cabincrewList;
}
public List<CockpitCrew> getCaptainList() {
return captainList;
}
public void setCaptainList(List<CockpitCrew> captainList) {
this.captainList = captainList;
}
public List<CockpitCrew> getPilotList() {
return pilotList;
}
public void setPilotList(List<CockpitCrew> pilotList) {
this.pilotList = pilotList;
}
public List<CabinCrew> getCabinList() {
return cabinList;
}
public void setCabinList(List<CabinCrew> cabinList) {
this.cabinList = cabinList;
}
public List<CockpitCrew> getCockpitList() {
return cockpitList;
}
public void setCockpitList(List<CockpitCrew> cockpitList) {
this.cockpitList = cockpitList;
}
public String getRemoveCc() {
return removeCc;
}
public void setRemoveCc(String removeCc) {
this.removeCc = removeCc;
}
public String getRemoveCp() {
return removeCp;
}
public void setRemoveCp(String removeCp) {
this.removeCp = removeCp;
}
public Long getFiId() {
return fiId;
}
public void setFiId(Long fiId) {
this.fiId = fiId;
}
public List<CabinCrew> getIdleCabincrew() {
return idleCabincrew;
}
public void setIdleCabincrew(List<CabinCrew> idleCabincrew) {
this.idleCabincrew = idleCabincrew;
}
public List<CabinCrew> getIdleCabinleader() {
return idleCabinleader;
}
public void setIdleCabinleader(List<CabinCrew> idleCabinleader) {
this.idleCabinleader = idleCabinleader;
}
public List<CockpitCrew> getIdleCaptain() {
return idleCaptain;
}
public void setIdleCaptain(List<CockpitCrew> idleCaptain) {
this.idleCaptain = idleCaptain;
}
public List<CockpitCrew> getIdlePilot() {
return idlePilot;
}
public void setIdlePilot(List<CockpitCrew> idlePilot) {
this.idlePilot = idlePilot;
}
// public List<CabinCrew> getIdleCabin() {
// return idleCabin;
// }
//
// public void setIdleCabin(List<CabinCrew> idleCabin) {
// this.idleCabin = idleCabin;
// }
//
// public List<CockpitCrew> getIdleCockpit() {
// return idleCockpit;
// }
//
// public void setIdleCockpit(List<CockpitCrew> idleCockpit) {
// this.idleCockpit = idleCockpit;
// }
public String getAddCrewType() {
return addCrewType;
}
public void setAddCrewType(String addCrewType) {
this.addCrewType = addCrewType;
}
public List<String> getCrewTypeList() {
return crewTypeList;
}
public void setCrewTypeList(List<String> crewTypeList) {
this.crewTypeList = crewTypeList;
}
public String getAddCrewId() {
return addCrewId;
}
public void setAddCrewId(String addCrewId) {
this.addCrewId = addCrewId;
}
public List<String> getAddCrewIdList() {
return addCrewIdList;
}
public void setAddCrewIdList(List<String> addCrewIdList) {
this.addCrewIdList = addCrewIdList;
}
}
| [
"[email protected]"
] | |
40b526b600ed642100016976c1e06b80dace3f4a | a5d01febfd8d45a61f815b6f5ed447e25fad4959 | /Source Code/5.5.1/sources/com/iqoption/withdrawal/common/fields/verify/VerificationWarningType.java | a3272457dbc3e59644ce394b9169e3e64e3f42f3 | [] | no_license | kkagill/Decompiler-IQ-Option | 7fe5911f90ed2490687f5d216cb2940f07b57194 | c2a9dbbe79a959aa1ab8bb7a89c735e8f9dbc5a6 | refs/heads/master | 2020-09-14T20:44:49.115289 | 2019-11-04T06:58:55 | 2019-11-04T06:58:55 | 223,236,327 | 1 | 0 | null | 2019-11-21T18:17:17 | 2019-11-21T18:17:16 | null | UTF-8 | Java | false | false | 660 | java | package com.iqoption.withdrawal.common.fields.verify;
import kotlin.i;
@i(aXC = {1, 1, 11}, aXD = {"\u0000\f\n\u0002\u0018\u0002\n\u0002\u0010\u0010\n\u0002\b\u0005\b\u0001\u0018\u00002\b\u0012\u0004\u0012\u00020\u00000\u0001B\u0007\b\u0002¢\u0006\u0002\u0010\u0002j\u0002\b\u0003j\u0002\b\u0004j\u0002\b\u0005¨\u0006\u0006"}, aXE = {"Lcom/iqoption/withdrawal/common/fields/verify/VerificationWarningType;", "", "(Ljava/lang/String;I)V", "NONE", "DOCUMENTS_WARNING", "CARDS_WARNING", "IqOption-5.5.1_optionXRelease"})
/* compiled from: VerificationWarnings.kt */
public enum VerificationWarningType {
NONE,
DOCUMENTS_WARNING,
CARDS_WARNING
}
| [
"[email protected]"
] | |
ee5ec9b963fc8b5075f59f64b4c1608e6d6ee641 | 5812a35410148139e5e31382aba0386506957082 | /java/com/ecosian/epfse/system/qna/ctrl/QnaAnswrController.java | 538859466f7f4a02f8ca32e1311c729f83c77c7a | [] | no_license | keumhwanmoon/advanced-epfse | d13bf526ea2c13302f8f2066646dfa967e36cd04 | b7350ad7297922ee8794fa6d82169597453b4af4 | refs/heads/master | 2021-06-19T11:23:43.436726 | 2017-07-18T02:24:44 | 2017-07-18T02:24:44 | 69,471,319 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,332 | java | /*
--------------------------------------------------------------------------------
PROJECT NAME : ES-MRV3
--------------------------------------------------------------------------------
- 단위업무명 : Q&A답변 Controller
- 최초작성일 : 2014-09-18
- 작 성 자 : 이승윤
- 비 고 : Controller 클래스내 모든 함수는 매개변수에 HttpServletRequest 를 추가한다.
페이지경로 가져오는 함수의 return type 은 ModelAndView 이고, 그 외의 함수는 Channel 이다.
--------------------------------------------------------------------------------
*/
package com.ecosian.epfse.system.qna.ctrl;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import com.ecosian.epfse.system.common.Base;
import com.ecosian.epfse.system.common.Channel;
import com.ecosian.epfse.system.common.dao.vo.ComParamVO;
import com.ecosian.epfse.system.qna.dao.vo.QnaAnswrVO;
import com.ecosian.epfse.system.qna.dao.vo.QnaVO;
// 공통매개변수
import com.ecosian.epfse.system.qna.svc.QnaAnswrService;
@Controller // Presentation Layer 를 구성하는 Controller Class 를 정의
public class QnaAnswrController
{
@Resource(name = "qnaAnswrService") // 해당 beanName 과 일치하는 bean 을 가져온다.
private QnaAnswrService svc;
// 페이지경로 가져오기 // Q&A답변 화면 요청시 사용한다.
@RequestMapping(value="/system/qnaAnswrEdit.do")
public ModelAndView getPagePath(HttpServletRequest req)
{
// Page Path = [InternalResourceViewResolver prefix] + [return value] + [InternalResourceViewResolver suffix]
// = "/WEB-INF/views/" + [return value] + ".jsp"
return new ModelAndView("/epfse" + Base.getReturnPath(req));
}
// 목록 저장 // Q&A답변 화면 저장 클릭시 사용한다.
@RequestMapping(method=RequestMethod.POST, value="/system/saveQnaAnswrInfo.do")
@ResponseStatus(HttpStatus.OK)
public @ResponseBody Channel saveInfo(HttpServletRequest req, @ModelAttribute ComParamVO voComParam,
@ModelAttribute QnaAnswrVO vo, @ModelAttribute QnaVO voQna)
{
voQna.setLoginUserId(vo.getComParamLoginUserId());
vo.setRgstUserId(vo.getComParamLoginUserId());
vo.setUpdtUserId(vo.getComParamLoginUserId());
return svc.saveInfo(vo, voQna);
}
// 목록 삭제 // Q&A답변 화면 삭제 클릭시 사용한다.
@RequestMapping(method=RequestMethod.POST, value="/system/deltQnaAnswrInfo.do")
@ResponseStatus(HttpStatus.OK)
public @ResponseBody Channel deltInfo(HttpServletRequest req, @ModelAttribute ComParamVO voComParam,
@ModelAttribute QnaAnswrVO vo, @ModelAttribute QnaVO voQna)
{
voQna.setLoginUserId(vo.getComParamLoginUserId());
return svc.deltInfo(vo, voQna);
}
} | [
"[email protected]"
] | |
7ddd012265ab9c3a128e45be5172ba89927c4fd6 | 18b731ab437622d5936e531ece88c3dd0b2bb2ea | /pbtd-user-sd/src/main/java/com/pbtd/playuser/web/controller/ActiveController.java | 3947e2deaf8c602c3379aeadc08ba9f593726410 | [] | no_license | harry0102/bai_project | b6c130e7235d220f2f0d4294a3f87b58f77cd265 | 674c6ddff7cf5dae514c69d2639d4b0245c0761f | refs/heads/master | 2021-10-07T20:32:15.985439 | 2018-12-05T06:50:11 | 2018-12-05T06:50:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,937 | java | package com.pbtd.playuser.web.controller;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.pbtd.playuser.service.IActivitiesInfoService;
import com.pbtd.playuser.util.JsonMessage;
@RestController
@RequestMapping("/phone/user")
public class ActiveController {
private static final Logger logger = LoggerFactory.getLogger(ActiveController.class);
@Autowired
private IActivitiesInfoService ictivitiesInfoService;
/***
* 0,获取活动接口
*
*/
@RequestMapping("/queryactivity")
@ResponseBody
public JsonMessage queryactivity(HttpServletRequest request) throws IOException{
String userId = request.getParameter("userId");
if(userId == null){
logger.info("返回值:-1,返回信息:请输入用户ID!");
return new JsonMessage(-1,"请输入用户ID!") ;
}
HashMap<String,Object> params = new HashMap<String, Object>();
logger.info("入参userId:"+userId);
params.put("userid", userId);
try {
return ictivitiesInfoService.queryActivity(params);
}catch (Exception e) {
e.printStackTrace();
logger.info("返回值:0,返回信息:系统正在维护中,请稍后!");
return new JsonMessage(0,"系统正在维护中,请稍后!") ;
}
}
/***
* 1,生成奖品
*
*/
@RequestMapping("/getprizeforactivity")
@ResponseBody
public JsonMessage getprizeforactivity(HttpServletRequest request) throws IOException{
String userId = request.getParameter("userId");
if(userId == null){
logger.info("返回值:-1,返回信息:请输入用户ID!");
return new JsonMessage(-1,"请输入用户ID!") ;
}
String activeName = request.getParameter("activeName");
if(activeName == null){
logger.info("返回值:-2,返回信息:请输入活动名称!");
return new JsonMessage(-2,"请输入活动名称!") ;
}
HashMap<String,Object> params = new HashMap<String, Object>();
logger.info("入参userId:"+userId+" |activeName:"+activeName);
params.put("userid", userId);
params.put("activeName", activeName);
try {
return ictivitiesInfoService.isnotJoinActivities(params);
}catch (Exception e) {
e.printStackTrace();
logger.info("返回值:0,返回信息:系统正在维护中,请稍后!");
return new JsonMessage(0,"系统正在维护中,请稍后!") ;
}
}
/***
* 2,输入收货地址
*/
@RequestMapping("/saveAddress")
@ResponseBody
public JsonMessage saveAddress(HttpServletRequest request) throws IOException{
JsonMessage result = new JsonMessage();
String userId = request.getParameter("userId");
if(userId == null){
result.setCode(-1);
result.setMessage("请输入用户ID!");
return result;
}
String activeName = request.getParameter("activeName");
if(activeName == null){
result.setCode(-2);
result.setMessage("请输入参与活动ID!");
return result;
}
String userAddress = request.getParameter("userAddress");
if(userAddress == null || userAddress.trim().length() == 0 ){
result.setCode(-3);
result.setMessage("请输入收货地址");
return result;
}
HashMap<String,Object> params = new HashMap<String, Object>();
logger.info("入参userId:"+userId+" |activeName:"+activeName+" |userAddress:"+userAddress);
params.put("userid", userId);
params.put("activeName", activeName);
params.put("userAddress", userAddress);
try {
result = ictivitiesInfoService.saveAddress(params);
}catch (Exception e) {
result.setCode(0);
result.setMessage("系统正在维护中,请稍后!");
e.printStackTrace();
return result;
}
return result;
}
}
| [
"[email protected]"
] | |
42109ab5c68caf03dc40fc1729b864d2a7329caa | 8e4905083b70b5510ca6e7ae118a563eeddf9e69 | /src/main/java/it/ariadne/shapes/model/Circle.java | 6c2a1b5998eb7c2807dcf2d69c5f890ccfe0e2e8 | [] | no_license | dalima29/shape | 80c5e30524476881228fa1792b158d823b9192c2 | 38ed682251071f047636554cd196e8ddb9e4cf0c | refs/heads/master | 2020-04-05T08:27:46.250300 | 2018-11-08T14:38:48 | 2018-11-08T14:38:48 | 156,716,845 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 252 | java | package it.ariadne.shapes.model;
import it.ariadne.shapes.Shape;
public class Circle implements Shape {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
public int calculateArea() {
return radius*radius*3;
}
}
| [
"[email protected]"
] | |
1c754bf215c183e1f7df2e1680c775c6de1a68a8 | b99d26a0584523afaa21ef160bd1684a0791c35f | /ludumtest/org/lwjgl/opengles/EXTSRGBWriteControl.java | 6ebbd307b9ebdf82da3dfe8d7ec1340414eb2aac | [] | no_license | alu0100777758/ludum | 8532e03a67bdc874d47cc9385b17977c89cb009e | 284eeb4f20feeef303f90f890b0cf448abc55bb0 | refs/heads/master | 2021-01-10T14:28:24.974659 | 2015-12-14T01:08:12 | 2015-12-14T01:08:12 | 47,064,259 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,240 | java | /*
* Copyright LWJGL. All rights reserved.
* License terms: http://lwjgl.org/license.php
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opengles;
/**
* Native bindings to the <a href="https://www.khronos.org/registry/gles/extensions/EXT/EXT_sRGB_write_control.txt">EXT_sRGB_write_control</a> extension.
*
* <p>This extension's intent is to expose new functionality which allows an application the ability to decide if the conversion from linear space to sRGB is
* necessary by enabling or disabling this conversion at framebuffer write or blending time. An application which passes non-linear vector data to a
* shader may not want the color conversion occurring, and by disabling conversion the application can be simplified, sometimes in very significant and
* more optimal ways.</p>
*
* <p>Requires {@link GLES20 GLES E.S} and {@link EXTSRGB EXT_sRGB} or {@link GLES30 GLES E.S}.</p>
*/
public final class EXTSRGBWriteControl {
/**
* Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetFloatv, GetIntegerv and
* GetInteger64v.
*/
public static final int GL_FRAMEBUFFER_SRGB_EXT = 0x8DB9;
private EXTSRGBWriteControl() {}
} | [
"[email protected]"
] | |
2fd319cf40ed6586b41f8e9f25c0535d57fc7ec6 | 1adcc7a43c57df49c5861b65e1b4142d64327fe1 | /MakeYourSmile/app/src/main/java/com/avocado/makeyoursmile/network/data/error/ErrorData.java | 3e3d5cca69d8a290726b67613ec5db737f798733 | [] | no_license | verywildbanana/chi_is_mys | 7e55af70c6f74f40a6a479d4a550e2ced7aea856 | 9fe81561191735c525d545c144403ba61d76e588 | refs/heads/master | 2021-01-21T13:03:21.805487 | 2016-05-04T07:20:01 | 2016-05-04T07:20:01 | 50,815,865 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,078 | java | package com.avocado.makeyoursmile.network.data.error;
import com.avocado.makeyoursmile.util.SmartLog;
import com.google.gson.annotations.SerializedName;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class ErrorData {
public final static String TAG = ErrorData.class.getSimpleName();
@SerializedName("code")
public String mCode;
@SerializedName("message")
private String dpMsg;
@SerializedName("update_info")
public UpdateData update_info;
public String getDpMsg() {
try {
dpMsg = URLDecoder.decode(dpMsg, "utf-8");
}
catch (UnsupportedEncodingException e) {
SmartLog.getInstance().e(TAG, "UnsupportedEncodingException");
}
catch (Exception e) {
SmartLog.getInstance().e(TAG, "Exception: " + e);
}
return dpMsg;
}
// {
// "code": "400.1101",
// "message": "최신 버전으로 업데이트가 필요합니다.",
// "update_info": {
// "required_version": "1.0.0",
// "update_url": "https://play.google.com/store/apps/details?id=com.nsocialnetwork.wearru"
// }
// }
}
| [
"[email protected]"
] | |
99677714257ff1b432f618f88d1a36846d9b4bb3 | 1c4c87802c342e83dfdd271751d53c93acafbea0 | /Exercises/1.1 Arrays/src/_1_1/Arrays_3.java | 2c8039beb5535698940e66e83314dbd96094e590 | [
"MIT"
] | permissive | sadmanca/ics4u | 8366b8de79760ffd9c25a5cf87c39022b4cab4a1 | 2b3790131a4cb79104696fed964ce2e24ced67b4 | refs/heads/master | 2023-04-11T14:28:14.742036 | 2021-04-21T23:02:48 | 2021-04-21T23:02:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,359 | java | package _1_1;
import java.util.Scanner;
/**
*
* @author Sadman
*/
public class Arrays_3 {
public static void main(String[] args) {
// 3. Write a program to complete the following tasks. Could write some
// methods.
// a) Get an integer n from the user and initialize a double array of
// length n. Ask the user to enter n numbers, and fill the array with
// them in order.
Scanner s = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = Integer.parseInt(s.nextLine());
double[] array = new double[n];
for (int i = 0; i < n; i++) {
System.out.print((i+1)+": ");
array[i] = Double.parseDouble(s.nextLine());
}
// b) Calculate and print the sum and average of all the elements in
// the array.
int sum = 0;
for (double num : array) {
sum += num;
}
System.out.println("Sum: " + sum);
System.out.println("Average: " + sum/array.length);
// c) Print all the elements of the array “nicely”, without using the
// Arrays.toString() method. If the array was [3, 5, -4, 1], the print
// out should be exactly as: 3, 5, -4, 1
// No brackets or braces, no extra commas at the end.
for (int i = 0; i < array.length-1; i++) {
if ((int) array[i] == array[i]) {
System.out.print((int) array[i] + ", ");
} else {
System.out.print(array[i] + ", ");
}
}
if ((int) array[array.length-1] == array[array.length-1]) {
System.out.print((int) array[array.length-1]);
} else {
System.out.print(array[array.length-1]);
}
System.out.println();
// d) Identify and print the smallest value of the array.
// e) Identify and print the index of the smallest value (first
// occurence, if more than 1) of the array.
double smallest = 999999;
int smallest_index = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] < smallest) {
smallest = array[i];
smallest_index = i;
}
}
System.out.println(smallest);
System.out.println(smallest_index);
s.close();
}
}
| [
"[email protected]"
] | |
5ea0b5555c8d459f47964f3454363da71774b042 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/8/8_3f1f39774ecbd0216cec665a70ad186843976a83/RandomizingVisitor/8_3f1f39774ecbd0216cec665a70ad186843976a83_RandomizingVisitor_t.java | f1e2d80c7b05164792166f645e5e0f4ef4fdba8b | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 20,400 | java | package Interpreter;
import java.util.*;
public class RandomizingVisitor implements VizParserVisitor, VizParserTreeConstants {
String[] possVars = {"g","m","n", "v", "w"};
final double chanceOfNumToVar = 1.0/10.0;
final double chanceOfAssignToOp = 1.5/10.0;
final double chanceOfPlusToMinus = 1.0/2.0;
final double chanceOfArrayDecl = 1.0/1.0;
final double chanceOfArrayToVarOp = 1.5/10.0;
final int largestPossibleRandomInt = 5;
final int maxVarDeclsInGlobal = 3;
final int minVarDeclsInGlobal = 1;
@Override
public Object visit(SimpleNode node, Object data) {
if (node instanceof ASTProgram)
this.visit((ASTProgram)node, null);
else if (node instanceof ASTFunction)
this.visit((ASTFunction)node, null);
else if (node instanceof ASTDeclarationList)
this.visit((ASTDeclarationList)node, null);
else if (node instanceof ASTStatementList)
this.visit((ASTStatementList)node, null);
else if (node instanceof ASTDeclaration)
this.visit((ASTDeclaration)node, null);
return null;
}
@Override
/**
* TODO: THIS RESTRICTS THE SECOND FUNCTION NAME TO FOO
*/
public Object visit(ASTProgram node, Object data) {
ASTDeclarationList innerDecl = (ASTDeclarationList)node.jjtGetChild(0);
// add 1-3 var decls
Random r = new Random();
int numOfVars = r.nextInt(maxVarDeclsInGlobal) + minVarDeclsInGlobal;
SymbolTable symbols = Global.getSymbolTable();
for (int i = 0; i < numOfVars; i++)
{
String varName = getRandomItem(possVars);
while(symbols.get(varName) != -255)
{
varName = getRandomItem(possVars);
}
createVarDecl(innerDecl,varName, r.nextInt(largestPossibleRandomInt)+1, i, ASTDeclaration.class, true);
}
//TODO: should an array decl always appear or just sometimes?
if (addArrayDecl())
{
int arrayElems = 6;
int[] values = new int[arrayElems];
for (int i = 0; i < arrayElems; i++)
{
values[i] = randNum();
}
String varName = getRandomItem(possVars);
while(symbols.get(varName) != -255)
{
varName = getRandomItem(possVars);
}
createArrayDecl(innerDecl, varName, values, numOfVars, ASTDeclaration.class, true);
}
visitMain(findChildFuncOfProg(node, "main"), null);
visitFunc(findChildFuncOfProg(node, "foo"), null);
node.childrenAccept(this, null);
return null;
}
@Override
public Object visit(ASTVarDecl node, Object data) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object visit(ASTFunction node, Object data) {
/* do nothing for now
if (node.getName().equals("main"))
{
visitMain(node, data);
}
else
{
visitFunc(node, data);
}
*/
return null;
}
@Override
public Object visit(ASTCall node, Object data) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object visit(ASTVar node, Object data) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object visit(ASTExpression node, Object data) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object visit(ASTDeclarationList node, Object data) {
node.childrenAccept(this, null);
return null;
}
@Override
public Object visit(ASTDeclaration node, Object data) {
node.childrenAccept(this, null);
return null;
}
@Override
public Object visit(ASTNum node, Object data) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object visit(ASTArrayDeclaration node, Object data) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object visit(ASTStatementList node, Object data) {
node.childrenAccept(this, null);
return null;
}
@Override
public Object visit(ASTStatement node, Object data) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object visit(ASTOp node, Object data) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object visit(ASTAssignment node, Object data) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object visit(ASTArgs node, Object data) {
// TODO Auto-generated method stub
return null;
}
/**
* this limits the entire randomizer to one function other than main
* @param node
* @param data
* @return
*/
private Object visitMain(ASTFunction node, Object data)
{
ASTStatementList innerStatement = (ASTStatementList)node.jjtGetChild(0);
// add 0-2 var decls
Random r = new Random();
int numOfVars = r.nextInt(3);
SymbolTable symbols = node.getSymbolTable();
for (int i = 0; i < numOfVars; i++)
{
//TODO: how do we decide which var names to use in here?
String varName = getRandomItem(possVars);
while(symbols.get(varName, true) != -255)
{
varName = getRandomItem(possVars);
}
createVarDecl(innerStatement,varName, r.nextInt(5)+1, i, ASTStatement.class);
}
// TODO: add 0-1 array decl
// add funcCall
ASTStatement surroundingStmt = new ASTStatement(JJTSTATEMENT);
surroundingStmt.jjtSetParent(innerStatement);
innerStatement.jjtAddChild(surroundingStmt, innerStatement.jjtGetNumChildren());
ASTCall call = new ASTCall(JJTCALL);
call.jjtSetParent(surroundingStmt);
surroundingStmt.jjtAddChild(call, surroundingStmt.jjtGetNumChildren());
HashMap<String, ASTFunction> funcs = Global.getFunctions();
Set<String> keys = funcs.keySet();
String callName = null;
Iterator<String> iter = keys.iterator();
while(iter.hasNext())
{
callName = iter.next();
if (!callName.equals("main"))
break;
}
call.setName(callName);
//decide on the number of params the second func will have.
HashSet<String> varNames = node.getSymbolTable().getCurrentVarNames();
//if true 3 params, else 2
if (r.nextBoolean())
{
String[] varNameArray = new String[varNames.size()];
varNames.toArray(varNameArray);
//TODO: get it so there's repeated params sometimes
for (int i = 0; i < 3; i++)
{
ASTVar var = new ASTVar(JJTVAR);
createFooArg(var,node.getSymbolTable());
call.addArg(var);
}
funcs.get(callName).addParams("x","y","z");
}
else
{
String[] varNameArray = new String[varNames.size()];
varNames.toArray(varNameArray);
//TODO: get it so there's repeated params more often
for (int i = 0; i < 2; i++)
{
ASTVar var = new ASTVar(JJTVAR);
createFooArg(var,node.getSymbolTable());
call.addArg(var);
}
funcs.get(callName).addParams("x", "y");
}
return null;
}
private Object visitFunc(ASTFunction node, Object data)
{
ASTStatementList innerStmtList = (ASTStatementList)node.jjtGetChild(0);
SymbolTable symbols = node.getSymbolTable();
//have to add params to the the SymbolTable
for (String param : node.getParameters())
{
symbols.put(param, new ByValVariable(0));
}
// add 0-1 var decls
Random r = new Random();
int numOfVars = r.nextInt(2);
for (int i = 0; i < numOfVars; i++)
{
String varName = getRandomItem(possVars);
while(symbols.get(varName, true) != -255)
{
varName = getRandomItem(possVars);
}
createVarDecl(innerStmtList,varName, r.nextInt(5)+ 1, i, ASTStatement.class);
}
//choose a "safe variable" for use by the array index
int numVars = symbols.getCurrentVarNames().size();
String[] symbolNames = new String[numVars];
symbols.getCurrentVarNames().toArray(symbolNames);
String safeVarName = getRandomItem(symbolNames);
Variable safeVar = symbols.getVariable(safeVarName);
while(safeVar.getIsArray())
{
safeVarName = getRandomItem(symbolNames);
safeVar = symbols.getVariable(safeVarName);
}
//start making some crazy assignment statements
// between 4 - 6 assignment statements
int numOfAssgnStmts = r.nextInt(3) + 4;
//...one of which will be an array
int arrayStmt = r.nextInt(numOfAssgnStmts);
for (int i = 0; i < numOfAssgnStmts; i++)
{
if (i == arrayStmt)
{
createOpAssign(innerStmtList, symbols, numOfVars + i, safeVarName, true);
}
else // its not an array statement
{
if (assignOrOp()) //a basic assignment statement
{
createBasicAssign(innerStmtList, symbols, numOfVars + i, safeVarName);
}
else // assignment with operations
{
createOpAssign(innerStmtList, symbols, numOfVars + i, safeVarName, false);
}
}
}
return null;
}
private void createBasicAssign(ASTStatementList parent, SymbolTable symbols,
int index, String safeVar)
{
ASTStatement stmt = new ASTStatement(JJTSTATEMENT);
stmt.jjtSetParent(parent);
parent.jjtAddChild(stmt, index);
ASTExpression enclosingExp = new ASTExpression(JJTEXPRESSION);
enclosingExp.jjtSetParent(stmt);
stmt.jjtAddChild(enclosingExp, 0);
ASTAssignment assign = new ASTAssignment(JJTASSIGNMENT);
assign.jjtSetParent(enclosingExp);
enclosingExp.jjtAddChild(assign, 0);
ASTVar var = new ASTVar(JJTVAR);
var.jjtSetParent(assign);
assign.jjtAddChild(var, 0);
String[] varNames = new String[symbols.getCurrentVarNames().size()];
symbols.getCurrentVarNames().toArray(varNames);
// Tom added this to fix some null problems
String randomName = getRandomItem(varNames);
Variable testVar = symbols.getVariable(randomName);
while (randomName.equals(safeVar) || testVar.getIsArray())
{
randomName = getRandomItem(varNames);
testVar = symbols.getVariable(randomName);
}
var.setName(randomName);
assign.setName(randomName);
ASTExpression numExp = new ASTExpression(JJTEXPRESSION);
numExp.jjtSetParent(assign);
assign.jjtAddChild(numExp, 1);
ASTNum num = new ASTNum(JJTNUM);
num.jjtSetParent(numExp);
numExp.jjtAddChild(num, 0);
num.setValue(randNum());
}
private void createOpAssign(ASTStatementList parent, SymbolTable symbols,
int index, String safeVar, boolean lhsArray)
{
ASTStatement stmt = new ASTStatement(JJTSTATEMENT);
stmt.jjtSetParent(parent);
parent.jjtAddChild(stmt, index);
ASTExpression enclosingExp = new ASTExpression(JJTEXPRESSION);
enclosingExp.jjtSetParent(stmt);
stmt.jjtAddChild(enclosingExp, 0);
ASTAssignment assign = new ASTAssignment(JJTASSIGNMENT);
assign.jjtSetParent(enclosingExp);
enclosingExp.jjtAddChild(assign, 0);
ASTVar var = new ASTVar(JJTVAR);
var.jjtSetParent(assign);
assign.jjtAddChild(var, 0);
createLHSOpExp(var, symbols, safeVar, lhsArray);
assign.setName(var.getName());
ASTExpression rhsExp = new ASTExpression(JJTEXPRESSION);
rhsExp.jjtSetParent(assign);
assign.jjtAddChild(rhsExp, 1);
ASTOp opExp = new ASTOp(JJTOP);
opExp.jjtSetParent(rhsExp);
rhsExp.jjtAddChild(opExp, 0);
createRHSOpExp(opExp, symbols);
}
private void createLHSOpExp(ASTVar var, SymbolTable symbols,
String safeVar, boolean lhsArray)
{
String[] varNames = new String[symbols.getCurrentVarNames().size()];
symbols.getCurrentVarNames().toArray(varNames);
//again, Tom added this to fix some null problems
String randomName = getRandomItem(varNames);
Variable testVar = symbols.getVariable(randomName);
if (lhsArray) //array value!
{
while (!testVar.getIsArray())
{
randomName = getRandomItem(varNames);
testVar = symbols.getVariable(randomName);
}
var.setName(randomName);
var.setIsArray(true);
ASTExpression exp = new ASTExpression(JJTEXPRESSION);
exp.jjtSetParent(var);
var.jjtAddChild(exp, 0);
ASTVar innerVar = new ASTVar(JJTVAR);
innerVar.jjtSetParent(exp);
exp.jjtAddChild(innerVar, 0);
innerVar.setName(safeVar);
}
else //non array value
{
while (randomName.equals(safeVar) || testVar.getIsArray())
{
randomName = getRandomItem(varNames);
testVar = symbols.getVariable(randomName);
}
}
var.setName(randomName);
}
private void createRHSOpExp(ASTOp opExp, SymbolTable symbols)
{
if (plusOrMinus())
opExp.setOp("+");
else
opExp.setOp("-");
createOperand(opExp, symbols, 0);
createOperand(opExp, symbols, 1);
}
/**
*
* @param opExp
* @param symbols
* @param index the index in the opExp, either 0 or 1
*/
private void createOperand(ASTOp opExp, SymbolTable symbols, int index)
{
String[] varNames = new String[symbols.getCurrentVarNames().size()];
symbols.getCurrentVarNames().toArray(varNames);
if(numOrVar()) //num
{
ASTNum num = new ASTNum(JJTNUM);
num.jjtSetParent(opExp);
opExp.jjtAddChild(num, index);
num.setValue(randNum());
}
else //var
{
ASTVar midVar = new ASTVar(JJTVAR);
midVar.jjtSetParent(opExp);
opExp.jjtAddChild(midVar, index);
String varName = getRandomItem(varNames);
if (arrayOrVarOperand())// an array index
{
midVar.setIsArray(true);//its an array, duh
Variable test = symbols.getVariable(varName);
while(!test.getIsArray())
{
varName = getRandomItem(varNames);
test = symbols.getVariable(varName);
}
midVar.setName(varName);
ASTExpression varChild = new ASTExpression(JJTEXPRESSION);
varChild.jjtSetParent(midVar);
midVar.jjtAddChild(varChild, 0);
ASTNum indexStmt = new ASTNum(JJTNUM);
indexStmt.jjtSetParent(varChild);
varChild.jjtAddChild(indexStmt, 0);
Random r = new Random();
int indexNum = r.nextInt(6);
indexStmt.setValue(indexNum);
}
else //just a var
{
midVar.setName(varName);
}
}
}
private <T> T getRandomItem(T[] array)
{
Random r = new Random();
int rand = r.nextInt(array.length);
return array[rand];
}
/**
*
* @return random int between 1 and the largestPossibleRandomInt final, inclusive.
*/
private int randNum()
{
Random r = new Random();
return r.nextInt(largestPossibleRandomInt) + 1;
}
private <T> void createVarDecl(Node parent, String varName,
int value, int indexInParent, T surroundingClass)
{
createVarDecl(parent, varName, value, indexInParent, surroundingClass, false);
}
/**
* Creates an ASTVarDecl in parent. Assumes that the parent is one step below an
* ASTFunction or an ASTProgram.
* @param parent the node that will contain the new ASTVarDecl.
* @param varName name of the variable
* @param value an integer that will be held in the variable.
* @param indexInParent the index in whatever list parent is.
* @param surroundingClass either ASTStatement or ASTDeclaration, depending on what you want
*/
private <T> void createVarDecl(Node parent, String varName,
int value, int indexInParent, T surroundingClass, boolean addSafely)
{
Node surroundingNode = null;
if (surroundingClass == ASTDeclaration.class)
surroundingNode = new ASTDeclaration(JJTDECLARATION);
else
surroundingNode = new ASTStatement(JJTSTATEMENT);
surroundingNode.jjtSetParent(parent);
if (addSafely)
parent.jjtAddChildSafe(surroundingNode, indexInParent);
else
parent.jjtAddChild(surroundingNode, indexInParent);
ASTVarDecl var = new ASTVarDecl(JJTVARDECL);
var.jjtSetParent(surroundingNode);
surroundingNode.jjtAddChild(var, 0);
var.setName(varName);
ASTExpression exp = new ASTExpression(JJTEXPRESSION);
exp.jjtSetParent(var);
var.jjtAddChild(exp, 0);
ASTNum num = new ASTNum(JJTNUM);
num.jjtSetParent(exp);
exp.jjtAddChild(num, 0);
num.setValue(value);
if (parent.jjtGetParent() instanceof ASTProgram)
Global.getSymbolTable().put(varName, new ByValVariable(value));
else
((ASTFunction)parent.jjtGetParent()).getSymbolTable().put(
varName, new ByValVariable(value));
}
private <T> void createArrayDecl(Node parent, String varName,
int[] values, int indexInParent, T surroundingClass, boolean addSafely)
{
Node surroundingNode = null;
if (surroundingClass == ASTDeclaration.class)
surroundingNode = new ASTDeclaration(JJTDECLARATION);
else
surroundingNode = new ASTStatement(JJTSTATEMENT);
surroundingNode.jjtSetParent(parent);
if (addSafely)
parent.jjtAddChildSafe(surroundingNode, indexInParent);
else
parent.jjtAddChild(surroundingNode, indexInParent);
ASTVarDecl varDecl = new ASTVarDecl(JJTVARDECL);
varDecl.jjtSetParent(surroundingNode);
surroundingNode.jjtAddChild(varDecl, 0);
varDecl.setIsArray(true);
varDecl.setName(varName);
ASTArrayDeclaration arrayDecl = new ASTArrayDeclaration(JJTARRAYDECLARATION);
arrayDecl.jjtSetParent(varDecl);
varDecl.jjtAddChild(arrayDecl, 0);
for (int i = 0; i < values.length; i++)
{
ASTNum numNode = new ASTNum(JJTNUM);
numNode.jjtSetParent(arrayDecl);
arrayDecl.jjtAddChild(numNode, i);
numNode.setValue(values[i]);
}
Variable arrayVar = new ByValVariable(0);
arrayVar.setArray();
if (parent.jjtGetParent() instanceof ASTProgram)
Global.getSymbolTable().put(varName, arrayVar);
else
((ASTFunction)parent.jjtGetParent()).getSymbolTable().put(
varName, arrayVar);
}
private void createFooArg(ASTVar var, SymbolTable symbols)
{
String[] varNameArray = new String[symbols.getCurrentVarNames().size()];
symbols.getCurrentVarNames().toArray(varNameArray);
if (arrayOrVarOperand())
{
String randomName = null;
Variable testVar = null;
for (int j = 0; j < varNameArray.length; j++)
{
randomName = varNameArray[j];
testVar = symbols.getVariable(randomName);
if (testVar.getIsArray())
break;
}
var.setName(randomName);
var.setIsArray(true);
ASTExpression innerExp = new ASTExpression(JJTEXPRESSION);
innerExp.jjtSetParent(var);
var.jjtAddChild(innerExp, 0);
ASTVar indexVar = new ASTVar(JJTVAR);
indexVar.jjtSetParent(innerExp);
innerExp.jjtAddChild(indexVar, 0);
randomName = getRandomItem(varNameArray);
testVar = symbols.getVariable(randomName);
while(testVar.getIsArray())
{
randomName = getRandomItem(varNameArray);
testVar = symbols.getVariable(randomName);
}
indexVar.setName(randomName);
}
else
{
String randomName = getRandomItem(varNameArray);
Variable testVar = symbols.getVariable(randomName);
while(testVar.getIsArray())
{
randomName = getRandomItem(varNameArray);
testVar = symbols.getVariable(randomName);
}
//check for arrays
var.setName(randomName);
}
}
/**
*
* @return true for num, false for var.
*/
private boolean numOrVar()
{
return binDecision(chanceOfNumToVar);
}
/**
*
* @return true for assignment with operators,
* false for basic assignment.
*/
private boolean assignOrOp()
{
return binDecision(chanceOfAssignToOp);
}
private boolean plusOrMinus()
{
return binDecision(chanceOfPlusToMinus);
}
private boolean arrayOrVarOperand()
{
return binDecision(chanceOfArrayToVarOp);
}
private boolean addArrayDecl()
{
return binDecision(chanceOfArrayDecl);
}
private boolean binDecision(double probability)
{
Random r = new Random();
double test = r.nextDouble();
return test <= probability;
}
private ASTFunction findChildFuncOfProg(ASTProgram node, String name)
{
ASTFunction ret = null;
ASTDeclarationList list = (ASTDeclarationList)node.jjtGetChild(0);
int numChild = list.jjtGetNumChildren();
for (int i = 0; i < numChild; i++)
{
ASTDeclaration decl = (ASTDeclaration)list.jjtGetChild(i);
Node child = decl.jjtGetChild(0);
if (child instanceof ASTFunction)
{
ASTFunction func = (ASTFunction)child;
if (func.getName().equals(name))
{
ret = func;
break;
}
}
}
return ret;
}
}
| [
"[email protected]"
] | |
8a4aa06d1f6ad367d9e439155cd5b9b4aacaaefd | 7579d48c664303c030192aa8353e9810c51002c6 | /src/main/java/com/tom/se/crazyit/chapter07/chapter72/CloneTest.java | d076b4355c3fd6128bf9a95098d2cad3c813f439 | [] | no_license | loustrong/algorithmJava | 6b3c406ae28a375cb1f691f829963d9c154c8275 | 977ca0e749531e8061c654fe9482e98f8ac3f9c6 | refs/heads/main | 2023-03-09T17:53:26.697764 | 2021-02-01T06:04:35 | 2021-02-01T06:04:35 | 315,169,642 | 0 | 1 | null | 2021-02-01T06:04:36 | 2020-11-23T01:26:57 | Java | UTF-8 | Java | false | false | 847 | java | package com.tom.se.crazyit.chapter07.chapter72;
/**
* @descriptions: CloneTest
* @author: Tom
* @date: 2021/1/18 下午 07:24
* @version: 1.0
*/
public class CloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
User u1 = new User(29);
// clone得到的u1對象
User u2 = u1.clone();
System.out.println(u1 == u2);
System.out.println(u1.address == u2.address);
}
}
class Address{
String detail;
public Address(String detail){
this.detail = detail;
}
}
class User implements Cloneable{
int age;
Address address;
public User(int age){
this.age = age;
address = new Address("廣州天河");
}
@Override
public User clone() throws CloneNotSupportedException {
return (User)super.clone();
}
} | [
"[email protected]"
] | |
ff8f99f600ab92a46433058dcc6745b9db254f16 | da77cdefc74afd53d191f5506ddef5c8f8b5bd23 | /main/java/com/example/school/utilities/mappers/CourseMapper.java | df772a802befb984c73361bef0c5f5cb1f08bcc4 | [] | no_license | OPNydox/SchoolRegister | f40d674ee60e3d008710620ad82f1aba7238738d | ac02fa36889de80be1f4ec908f94b42014d2ec7d | refs/heads/master | 2022-12-29T03:33:54.485088 | 2020-10-14T11:17:23 | 2020-10-14T11:17:23 | 266,535,971 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 990 | java | package com.example.school.utilities.mappers;
import java.util.ArrayList;
import java.util.List;
import com.example.school.database.entities.Course;
import com.example.school.viewModels.CourseViewModel;
public class CourseMapper {
public static CourseViewModel mapEtityoToCourseViewModel(Course course) {
CourseViewModel resultViewModel = new CourseViewModel();
resultViewModel.setId(Long.toString(course.getClassId()));
resultViewModel.setHonorarium(Integer.toString(course.getHonorarium()));
resultViewModel.setName(course.getCourseName());
resultViewModel.setSubject(course.getSubject());
return resultViewModel;
}
public static List<CourseViewModel> mapEtityoToCourseViewModel (Iterable<Course> list) {
List<CourseViewModel> resultList = new ArrayList<>();
for (Course course : list) {
resultList.add(mapEtityoToCourseViewModel(course));
}
return resultList;
}
} | [
"[email protected]"
] | |
4ded7f66f21f264de585aea164402b5402c38013 | a80215be1ab39123e538fcdbd8ee3ffa6d985604 | /gof/src/main/java/pers/sherry/gof/mediator/MediatorPattern.java | 31d6cf4e9ea6d9ccc404ca217c6b9f05d4b66c03 | [] | no_license | SherryXRJ/test | 7a0741ae9fa5f79005bba95947dc0a7a7f891ad0 | 5b5cccf13a2d2d2c9416d1089dd5a7b0d93dc440 | refs/heads/master | 2022-08-02T07:01:07.969464 | 2019-02-02T02:40:41 | 2019-02-02T02:40:41 | 148,106,337 | 0 | 0 | null | 2022-06-21T00:51:35 | 2018-09-10T06:01:17 | Java | UTF-8 | Java | false | false | 934 | java | package pers.sherry.gof.mediator;
import pers.sherry.gof.mediator.colleague.AbstractChatter;
import pers.sherry.gof.mediator.colleague.concrete.ConcreteChatter;
import pers.sherry.gof.mediator.mediator.AbstractChatMediator;
import pers.sherry.gof.mediator.mediator.concrete.ConcreteChatMediator;
/**
* Mediator Pattern 中介者模式
*/
public class MediatorPattern {
public static void main(String[] args) {
// 中介者
AbstractChatMediator mediator = new ConcreteChatMediator();
// 同事类
AbstractChatter tom = new ConcreteChatter("Tom", mediator);
AbstractChatter jerry = new ConcreteChatter("Jerry", mediator);
AbstractChatter peter = new ConcreteChatter("Peter", mediator);
mediator.register(tom, jerry, peter);
tom.chat("Hello Jerry and Peter");
jerry.chat("Oh I can hear u, Jerry");
peter.chat("I receive all message");
}
}
| [
"[email protected]"
] | |
ec59939cf65784c963bd342f69fc5920bea29182 | d4cea5890a4e6865273987360df4ee9f93333574 | /android/app/src/main/java/com/destreetboard/rodicash/MainActivity.java | e7933f9aec8bb69570444389d9a38353ce0b0354 | [] | no_license | nnamanikester/Rodicash | 1eb5794c8f70f9d4fb3446a30714b6d4b1fc8edf | 457e452a8d7a6b841067a5d1c70a06fc45e23654 | refs/heads/main | 2023-08-28T22:00:14.198871 | 2021-10-21T09:06:10 | 2021-10-21T09:06:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 816 | java | package com.destreetboard.rodicash;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "Rodicash";
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
@Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(MainActivity.this);
}
};
}
}
| [
"[email protected]"
] | |
412cf82548b25d6ce29222a9924ade2fb1726dee | acacc905bea14456da8649a20a1b68f68f216fe1 | /urule-client-server/src/main/java/com.zhitong.uruleclientserver/UruleClientServerApplication.java | b9f143739533b1dd7c14aacdcfaf4ed99b6b1cf5 | [] | no_license | sudesperado/zt-parent | 23dbb5b23be11d76a87e7f0af98a2918199e383c | ba1c736fd9d09d2378baf35bc9e7683e250c495a | refs/heads/master | 2023-07-02T18:23:11.066205 | 2021-07-12T06:15:46 | 2021-07-12T06:15:46 | 323,587,795 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 481 | java | package com.zhitong.uruleclientserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class UruleClientServerApplication {
public static void main(String[] args) {
SpringApplication.run(UruleClientServerApplication.class, args);
}
}
| [
"[email protected]"
] | |
2a19ff57323195b7a63e63b0f1ffbc93efa47334 | ebaa0055554710c2ab78ec712462e702fcfb997a | /Esercizi/Oggetti/Esercizio-11/Specie.java | 572037beadd25082ce6e37f3815216dc0dec344b | [] | no_license | leonardo-rinaldi/Java-projects | 4f4c1fcd472921004691f83608250743f56c1797 | 17c0c5cc487fca390c6d39af428d069aa4f6891a | refs/heads/master | 2021-04-23T22:40:52.396801 | 2020-11-25T17:19:02 | 2020-11-25T17:19:02 | 250,022,841 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,525 | java | import java.util.Scanner;
/*
* 11- Si scriva un programma che risponda a domande come la seguente. Si supponga
* che la specie Bufalo Klingon abbia una popolazione di 100 individui e un
* tasso di crescita del 15% e che la specie Elefante abbia una popolazione di
* 10 individui e un tasso di crescita del 35%. In quanti anni la popolazione di
* elefanti supererà quella dei bufali klingon?
*
* Il programma richiederà i dati di entrambe le specie e risponderà dicendo quanti
* anni ci vorranno per far si che la specie con il minor numero di individui superi
* quella con il numero maggiore di individui. Le due specie possono essere inserite
* in qualsiasi ordine.
*
*/
public class Specie {
private String nome;
private int popolazione;
private double tassoCrescita;
public void leggiInput() {
Scanner tastiera = new Scanner(System.in);
System.out.println("Qual'è il nome della specie?");
nome = tastiera.nextLine();
System.out.println("A quanto ammonta la popolazione?");
popolazione = tastiera.nextInt();
System.out.println("Inserisci il tassto di crescita " + "(% crescita per anno):");
tassoCrescita = tastiera.nextDouble();
}
public void scriviOutput() {
System.out.println("Nome = " + nome);
System.out.println("Popolazione = " + popolazione);
System.out.println("Tasso crescita = " + tassoCrescita + "%");
}
/*
* Restituisce una proiezione della popolazione dopo un numero
* specificato di anni
*/
public int prediciPopolazione(int anni) {
int risultato = 0;
double totalePopolazione = popolazione;
int contatore = anni;
while((contatore < 0) && (totalePopolazione > 0)) {
totalePopolazione = (totalePopolazione + (tassoCrescita / 100) * totalePopolazione);
contatore--;
}
return risultato;
}
/*
* Restituisce in quanto tempo una popolazione supererà l'altra
* per numero.
*/
public int crescitaPopolazione(Specie secondoOggetto) {
double primaPopolazione = this.popolazione;
double secondaPopolazione = secondoOggetto.popolazione;
int anni = 0;
if(primaPopolazione > secondaPopolazione) {
while(secondaPopolazione < primaPopolazione) {
secondaPopolazione = (secondaPopolazione + (tassoCrescita / 100) * secondaPopolazione);
primaPopolazione = (primaPopolazione + (tassoCrescita / 100) * primaPopolazione); //aumento specie con popolazione maggiore
anni++;
}
} else { //if(secondaPopolazione > primaPopolazione)
while(primaPopolazione < secondaPopolazione) {
primaPopolazione = (primaPopolazione + (tassoCrescita / 100) * primaPopolazione);
secondaPopolazione = (secondaPopolazione + (tassoCrescita / 100) * primaPopolazione); //aumeno specie con popolazione maggiore
anni++;
}
}
return anni;
}
public void setSpecie(String nuovoNome, int nuovaPopolazione, double nuovoTassoCrescita) {
nome = nuovoNome;
if(nuovaPopolazione >= 0) {
popolazione = nuovaPopolazione;
} else {
System.out.println("ERRORE: si sta usando un numero negativo " + "per la popolazione");
System.exit(0);
}
tassoCrescita = nuovoTassoCrescita;
}
public String getNome() {
return nome;
}
public int getPopolazione() {
return popolazione;
}
public double getTassoCrescita() {
return tassoCrescita;
}
public boolean equals(Specie altroOggetto) {
return (nome.equalsIgnoreCase(altroOggetto.nome))
&& (popolazione == altroOggetto.popolazione)
&& (tassoCrescita == altroOggetto.tassoCrescita);
}
}
| [
"[email protected]"
] | |
16dab62a7039ef33aabc481bb4674925039ea416 | 082e26b011e30dc62a62fae95f375e4f87d9e99c | /docs/weixin_7.0.4_source/反编译源码/反混淆后/src/main/java/com/tencent/p177mm/protocal/protobuf/cvb.java | 5ab96c6290929f36c7040a08c07165262b2fe1bc | [] | no_license | xsren/AndroidReverseNotes | 9631a5aabc031006e795a112b7ac756a8edd4385 | 9202c276fe9f04a978e4e08b08e42645d97ca94b | refs/heads/master | 2021-04-07T22:50:51.072197 | 2019-07-16T02:24:43 | 2019-07-16T02:24:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,336 | java | package com.tencent.p177mm.protocal.protobuf;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.p177mm.p205bt.C1331a;
import p690e.p691a.p692a.p693a.C6086a;
import p690e.p691a.p692a.p695b.p697b.C6091a;
import p690e.p691a.p692a.p698c.C6093a;
/* renamed from: com.tencent.mm.protocal.protobuf.cvb */
public final class cvb extends C1331a {
public String nQB;
public String xra;
/* renamed from: op */
public final int mo4669op(int i, Object... objArr) {
AppMethodBeat.m2504i(124377);
int f;
if (i == 0) {
C6093a c6093a = (C6093a) objArr[0];
if (this.xra != null) {
c6093a.mo13475e(1, this.xra);
}
if (this.nQB != null) {
c6093a.mo13475e(2, this.nQB);
}
AppMethodBeat.m2505o(124377);
return 0;
} else if (i == 1) {
if (this.xra != null) {
f = C6091a.m9575f(1, this.xra) + 0;
} else {
f = 0;
}
if (this.nQB != null) {
f += C6091a.m9575f(2, this.nQB);
}
AppMethodBeat.m2505o(124377);
return f;
} else if (i == 2) {
C6086a c6086a = new C6086a((byte[]) objArr[0], unknownTagHandler);
for (f = C1331a.getNextFieldNumber(c6086a); f > 0; f = C1331a.getNextFieldNumber(c6086a)) {
if (!super.populateBuilderWithField(c6086a, this, f)) {
c6086a.ems();
}
}
AppMethodBeat.m2505o(124377);
return 0;
} else if (i == 3) {
C6086a c6086a2 = (C6086a) objArr[0];
cvb cvb = (cvb) objArr[1];
switch (((Integer) objArr[2]).intValue()) {
case 1:
cvb.xra = c6086a2.BTU.readString();
AppMethodBeat.m2505o(124377);
return 0;
case 2:
cvb.nQB = c6086a2.BTU.readString();
AppMethodBeat.m2505o(124377);
return 0;
default:
AppMethodBeat.m2505o(124377);
return -1;
}
} else {
AppMethodBeat.m2505o(124377);
return -1;
}
}
}
| [
"[email protected]"
] | |
a1277182a49726f94055b00d8dbfe36ad9cfdb9e | 22d0b84ce8ae77e375d7187574164a968a5f6d7d | /dept/src/main/java/scau/lizl/netty/source/echo/EchoClient.java | 63f673fc47e07d889ee562e740e1347b8de372bf | [] | no_license | he4thc11ff/forever | 9d11d1b523a490e1d2e86cada9f1f85ea6ab30d2 | c020a07b5814e70788467bde38e0d648317a4fd7 | refs/heads/master | 2022-10-30T02:06:49.600888 | 2020-04-04T09:46:36 | 2020-04-04T09:46:36 | 248,131,045 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,089 | java | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package scau.lizl.netty.source.echo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
/**
* Sends one message when a connection is open and echoes back any received
* data to the server. Simply put, the echo client initiates the ping-pong
* traffic between the echo client and server by sending the first message to
* the server.
*/
public final class EchoClient {
static final boolean SSL = System.getProperty("ssl") != null;
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
public static void main(String[] args) throws Exception {
// Configure SSL.git
final SslContext sslCtx;
if (SSL) {
sslCtx = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
}
//p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new EchoClientHandler());
}
});
// Start the client.
ChannelFuture f = b.connect(HOST, PORT).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down the event loop to terminate all threads.
group.shutdownGracefully();
}
}
}
| [
"[email protected]"
] | |
464e7108dbe5366838ec063b316bcff5cdd3e39b | 1d6fe821426fa9aaf8a02c680f74248af86aa7c1 | /psp/okhttpRetrofit/src/main/java/retrofit/UsuarioApi.java | 3f0f18fb54b03af4fce8368b701e2ea18e93bbe8 | [] | no_license | oscarnovillo/dam2_2019 | 01952917a2e9e044c1cae403fbcf32bcf967825f | 8ecee9c61eb2f5aa239165672f6150b76fe10eb4 | refs/heads/master | 2022-12-21T03:44:30.237694 | 2021-10-03T17:19:45 | 2021-10-03T17:19:45 | 203,876,464 | 0 | 0 | null | 2022-12-14T20:47:54 | 2019-08-22T21:31:42 | Java | UTF-8 | Java | false | false | 384 | java | package retrofit;
import modelo.AreasRequest;
import modelo.Usuario;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import java.util.List;
public interface UsuarioApi {
@GET("usuario/")
Call<List<Usuario>> loadUsuarios();
@POST("usuario/")
Call<Usuario> addUser(@Body Usuario user);
}
| [
"[email protected]"
] | |
9bb66f7a69d4ae77d0df0250c92ecc6c067a517c | e41394971e83e39f3d3699f58e5dae86437960ce | /src/test/TestFinale1/AskTimeBehaviour.java | 4dd4c7eebda0ea6436280fd19bdde289208ed582 | [
"MIT"
] | permissive | nachiti/JAM | 165d969e376c81a8b62b5cd8b10b8f16b06c4cfd | 342e10bc046e271580c035bd06df70c81c91e2e7 | refs/heads/master | 2021-01-20T03:46:45.284817 | 2013-11-03T14:21:39 | 2013-11-03T14:21:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,813 | java | package TestFinale1;
import jam.*;
import jam.eccezioni.*;
public class AskTimeBehaviour extends JAMWhileBehaviour {
private LogFile log;
public AskTimeBehaviour(JAMAgent myAgent) {
super(myAgent);
log = new LogFile();
}
public void setup() throws JAMBehaviourInterruptedException {
try {
log.startLog(myAgent.getMyID().toString().trim(), "Log file per " + myAgent.getMyID());
log.log("0- Inizializzazione comportamento.");
} catch (JAMIOException err) {
System.out.println("Errore: " + err);
done();
}
}
public void dispose() throws JAMBehaviourInterruptedException {
try {
log.log("END- Esecuguita dispose.");
log.endLog();
} catch (JAMIOException err) {
System.out.println("Errore: " + err);
done();
}
}
public void action() throws JAMBehaviourInterruptedException {
try {
log.log("1- Start del comportamento, attesa messaggio iniziale.");
CategoryAgentID timeProviderCategoryID = new CategoryAgentID("Time Provider");
log.log("2- Preparo REQUEST dell'ora.");
Message request = new Message(
myAgent.getMyID(),
timeProviderCategoryID,
Performative.REQUEST,
"Che ora e'?");
log.log("3- Invio REQUEST.", request);
myAgent.send(request);
log.log("4- Inviata REQUEST.", request);
log.log("5- Attendo risposta.");
Message answer = myAgent.receive(timeProviderCategoryID);
log.log("6- Trovata risposta.", answer);
if (answer.getPerformative() != Performative.AGREE) {
log.log("7- La risposta non e' una agree eseguo una done.", answer);
done();
} else {
log.log("8- La risposta e' una agree, prepara la conferma.", answer);
AgentID selectedProvider = answer.getSender();
Message confirm = new Message(
myAgent.getMyID(),
selectedProvider,
Performative.INFORM,
"Aspetto l'ora.");
log.log("9- Invio la conferma.", confirm);
myAgent.send(confirm);
log.log("10- Inviata la conferma.", confirm);
log.log("11- Attendo il messaggio con l'ora da " + selectedProvider);
sleep(2000);
log.log("12- Controllo se arrivato il messaggio con l'ora da " + selectedProvider);
if (myAgent.isThereMessage(selectedProvider, Performative.INFORM)) {
log.log("13- Leggo il messaggio con l'ora da " + selectedProvider);
Message inform = myAgent.receive(selectedProvider, Performative.INFORM);
log.log("14- Letto il messaggio con l'ora da " + selectedProvider, inform);
System.out.println(inform);
} else {
log.log("15- Nessun messagggio da " + selectedProvider);
System.out.println("Nessuna risposta, rinuncio.");
}
done();
}
} catch (JAMRemoteMessageBoxException ex) {
System.err.println("Impossibile contattare il time provider. "+ex.getMessage());
} catch (InterruptedException ex) {
throw new JAMBehaviourInterruptedException(ex.getMessage(), ex);
} catch (JAMADSLException err1) {
System.out.println("Errore: " + err1);
} catch (JAMIOException err2) {
System.out.println("Errore: " + err2);
}
finally {
done();
}
}
}
| [
"[email protected]"
] | |
8272c3ba4e4e06778e116c9fe041b5c6ae136cb4 | 5112b1d7720a6b72aaa6763f2d3616f6abb37236 | /common-component/v2.3.2/src/main/java/egovframework/com/uss/umt/web/EgovUserManageController.java | a1f738a94f2afbc2212225379790d09029967577 | [] | no_license | dasomel/egovframework | 1c5435f7b5ce6834379ec7f66cc546db18862b0b | a2fcdbf0a0a98e5a2ab8a3193f33cab9f1cd26e7 | refs/heads/master | 2021-06-03T10:44:26.848513 | 2020-11-03T07:27:05 | 2020-11-03T07:27:05 | 24,672,345 | 3 | 3 | null | null | null | null | UTF-8 | Java | false | false | 17,736 | java | package egovframework.com.uss.umt.web;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springmodules.validation.commons.DefaultBeanValidator;
import egovframework.com.cmm.ComDefaultCodeVO;
import egovframework.com.cmm.annotation.IncludedInfo;
import egovframework.com.cmm.service.EgovCmmUseService;
import egovframework.com.uss.umt.service.EgovUserManageService;
import egovframework.com.uss.umt.service.UserDefaultVO;
import egovframework.com.uss.umt.service.UserManageVO;
import egovframework.com.utl.sim.service.EgovFileScrty;
import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
/**
* 업무사용자관련 요청을 비지니스 클래스로 전달하고 처리된결과를 해당 웹 화면으로 전달하는 Controller를 정의한다
* @author 공통서비스 개발팀 조재영
* @since 2009.04.10
* @version 1.0
* @see
*
* <pre>
* << 개정이력(Modification Information) >>
*
* 수정일 수정자 수정내용
* ------- -------- ---------------------------
* 2009.04.10 조재영 최초 생성
* 2011.8.26 정진오 IncludedInfo annotation 추가
*
* </pre>
*/
@Controller
public class EgovUserManageController {
/** userManageService */
@Resource(name = "userManageService")
private EgovUserManageService userManageService;
/** cmmUseService */
@Resource(name="EgovCmmUseService")
private EgovCmmUseService cmmUseService;
/** EgovPropertyService */
@Resource(name = "propertiesService")
protected EgovPropertyService propertiesService;
/** Log Info */
protected Log log = LogFactory.getLog(this.getClass());
/** DefaultBeanValidator beanValidator */
@Autowired
private DefaultBeanValidator beanValidator;
/**
* 사용자목록을 조회한다. (pageing)
* @param userSearchVO 검색조건정보
* @param model 화면모델
* @return cmm/uss/umt/EgovUserManage
* @throws Exception
*/
@IncludedInfo(name="업무사용자관리", order = 460 ,gid = 50)
@RequestMapping(value="/uss/umt/EgovUserManage.do")
public String selectUserList(@ModelAttribute("userSearchVO") UserDefaultVO userSearchVO,
ModelMap model)
throws Exception {
/** EgovPropertyService.sample */
userSearchVO.setPageUnit(propertiesService.getInt("pageUnit"));
userSearchVO.setPageSize(propertiesService.getInt("pageSize"));
/** pageing */
PaginationInfo paginationInfo = new PaginationInfo();
paginationInfo.setCurrentPageNo(userSearchVO.getPageIndex());
paginationInfo.setRecordCountPerPage(userSearchVO.getPageUnit());
paginationInfo.setPageSize(userSearchVO.getPageSize());
userSearchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
userSearchVO.setLastIndex(paginationInfo.getLastRecordIndex());
userSearchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
List userList = userManageService.selectUserList(userSearchVO);
model.addAttribute("resultList", userList);
int totCnt = userManageService.selectUserListTotCnt(userSearchVO);
paginationInfo.setTotalRecordCount(totCnt);
model.addAttribute("paginationInfo", paginationInfo);
//사용자상태코드를 코드정보로부터 조회
ComDefaultCodeVO vo = new ComDefaultCodeVO();
vo.setCodeId("COM013");
List emplyrSttusCode_result = cmmUseService.selectCmmCodeDetail(vo);
model.addAttribute("emplyrSttusCode_result",emplyrSttusCode_result);//사용자상태코드목록
return "egovframework/com/uss/umt/EgovUserManage";
}
/**
* 사용자등록화면으로 이동한다.
* @param userSearchVO 검색조건정보
* @param userManageVO 사용자초기화정보
* @param model 화면모델
* @return cmm/uss/umt/EgovUserInsert
* @throws Exception
*/
@RequestMapping("/uss/umt/EgovUserInsertView.do")
public String insertUserView(
@ModelAttribute("userSearchVO") UserDefaultVO userSearchVO,
@ModelAttribute("userManageVO") UserManageVO userManageVO,
Model model
)throws Exception {
ComDefaultCodeVO vo = new ComDefaultCodeVO();
//패스워드힌트목록을 코드정보로부터 조회
vo.setCodeId("COM022");
List passwordHint_result = cmmUseService.selectCmmCodeDetail(vo);
//성별구분코드를 코드정보로부터 조회
vo.setCodeId("COM014");
List sexdstnCode_result = cmmUseService.selectCmmCodeDetail(vo);
//사용자상태코드를 코드정보로부터 조회
vo.setCodeId("COM013");
List emplyrSttusCode_result = cmmUseService.selectCmmCodeDetail(vo);
//소속기관코드를 코드정보로부터 조회 - COM025
vo.setCodeId("COM025");
List insttCode_result = cmmUseService.selectCmmCodeDetail(vo);
//조직정보를 조회 - ORGNZT_ID정보
vo.setTableNm("COMTNORGNZTINFO");
List orgnztId_result = cmmUseService.selectOgrnztIdDetail(vo);
//그룹정보를 조회 - GROUP_ID정보
vo.setTableNm("COMTNORGNZTINFO");
List groupId_result = cmmUseService.selectGroupIdDetail(vo);
model.addAttribute("passwordHint_result", passwordHint_result); //패스워트힌트목록
model.addAttribute("sexdstnCode_result", sexdstnCode_result); //성별구분코드목록
model.addAttribute("emplyrSttusCode_result",emplyrSttusCode_result);//사용자상태코드목록
model.addAttribute("insttCode_result", insttCode_result); //소속기관코드목록
model.addAttribute("orgnztId_result", orgnztId_result); //조직정보 목록
model.addAttribute("groupId_result", groupId_result); //그룹정보 목록
return "egovframework/com/uss/umt/EgovUserInsert";
}
/**
* 사용자등록처리후 목록화면으로 이동한다.
* @param userManageVO 사용자등록정보
* @param bindingResult 입력값검증용 bindingResult
* @param model 화면모델
* @return forward:/uss/umt/EgovUserManage.do
* @throws Exception
*/
@RequestMapping("/uss/umt/EgovUserInsert.do")
public String insertUser(
@ModelAttribute("userManageVO") UserManageVO userManageVO,
BindingResult bindingResult,
Model model
)throws Exception {
beanValidator.validate(userManageVO, bindingResult);
if (bindingResult.hasErrors()){
return "egovframework/com/uss/umt/EgovUserInsert";
}else{
if(userManageVO.getOrgnztId().equals("")){
userManageVO.setOrgnztId(null);
}
if(userManageVO.getGroupId().equals("")){
userManageVO.setGroupId(null);
}
userManageService.insertUser(userManageVO);
//Exception 없이 진행시 등록성공메시지
model.addAttribute("resultMsg", "success.common.insert");
}
return "forward:/uss/umt/EgovUserManage.do";
}
/**
* 사용자정보 수정을 위해 사용자정보를 상세조회한다.
* @param uniqId 상세조회대상 사용자아이디
* @param userSearchVO 검색조건
* @param model 화면모델
* @return uss/umt/EgovUserSelectUpdt
* @throws Exception
*/
@RequestMapping("/uss/umt/EgovUserSelectUpdtView.do")
public String updateUserView(
@RequestParam("selectedId") String uniqId ,
@ModelAttribute("searchVO") UserDefaultVO userSearchVO, Model model)
throws Exception {
ComDefaultCodeVO vo = new ComDefaultCodeVO();
//패스워드힌트목록을 코드정보로부터 조회
vo.setCodeId("COM022");
List passwordHint_result = cmmUseService.selectCmmCodeDetail(vo);
//성별구분코드를 코드정보로부터 조회
vo.setCodeId("COM014");
List sexdstnCode_result = cmmUseService.selectCmmCodeDetail(vo);
//사용자상태코드를 코드정보로부터 조회
vo.setCodeId("COM013");
List emplyrSttusCode_result = cmmUseService.selectCmmCodeDetail(vo);
//소속기관코드를 코드정보로부터 조회 - COM025
vo.setCodeId("COM025");
List insttCode_result = cmmUseService.selectCmmCodeDetail(vo);
//조직정보를 조회 - ORGNZT_ID정보
vo.setTableNm("COMTNORGNZTINFO");
List orgnztId_result = cmmUseService.selectOgrnztIdDetail(vo);
//그룹정보를 조회 - GROUP_ID정보
vo.setTableNm("COMTNORGNZTINFO");
List groupId_result = cmmUseService.selectGroupIdDetail(vo);
model.addAttribute("passwordHint_result", passwordHint_result); //패스워트힌트목록
model.addAttribute("sexdstnCode_result", sexdstnCode_result); //성별구분코드목록
model.addAttribute("emplyrSttusCode_result",emplyrSttusCode_result);//사용자상태코드목록
model.addAttribute("insttCode_result", insttCode_result); //소속기관코드목록
model.addAttribute("orgnztId_result", orgnztId_result); //조직정보 목록
model.addAttribute("groupId_result", groupId_result); //그룹정보 목록
UserManageVO userManageVO = new UserManageVO();
userManageVO = userManageService.selectUser(uniqId);
model.addAttribute("userSearchVO", userSearchVO);
model.addAttribute("userManageVO", userManageVO);
return "egovframework/com/uss/umt/EgovUserSelectUpdt";
}
/**
* 사용자정보 수정후 목록조회 화면으로 이동한다.
* @param userManageVO 사용자수정정보
* @param bindingResult 입력값검증용 bindingResult
* @param model 화면모델
* @return forward:/uss/umt/EgovUserManage.do
* @throws Exception
*/
@RequestMapping("/uss/umt/EgovUserSelectUpdt.do")
public String updateUser(
@ModelAttribute("userManageVO") UserManageVO userManageVO,
BindingResult bindingResult,
Model model
)throws Exception {
beanValidator.validate(userManageVO, bindingResult);
if (bindingResult.hasErrors()){
return "egovframework/com/uss/umt/EgovUserSelectUpdt";
}else{
//업무사용자 수정시 히스토리 정보를 등록한다.
userManageService.insertUserHistory(userManageVO);
if(userManageVO.getOrgnztId().equals("")){
userManageVO.setOrgnztId(null);
}
if(userManageVO.getGroupId().equals("")){
userManageVO.setGroupId(null);
}
userManageService.updateUser(userManageVO);
//Exception 없이 진행시 수정성공메시지
model.addAttribute("resultMsg", "success.common.update");
return "forward:/uss/umt/EgovUserManage.do";
}
}
/**
* 사용자정보삭제후 목록조회 화면으로 이동한다.
* @param checkedIdForDel 삭제대상아이디 정보
* @param userSearchVO 검색조건
* @param model 화면모델
* @return forward:/uss/umt/EgovUserManage.do
* @throws Exception
*/
@RequestMapping("/uss/umt/EgovUserDelete.do")
public String deleteUser(
@RequestParam("checkedIdForDel") String checkedIdForDel ,
@ModelAttribute("searchVO") UserDefaultVO userSearchVO, Model model)
throws Exception {
//log.debug("jjycon_delete-->"+checkedIdForDel);
userManageService.deleteUser(checkedIdForDel);
//Exception 없이 진행시 등록성공메시지
model.addAttribute("resultMsg", "success.common.delete");
return "forward:/uss/umt/EgovUserManage.do";
}
/**
* 입력한 사용자아이디의 중복확인화면 이동
* @param model 화면모델
* @return uss/umt/EgovIdDplctCnfirm
* @throws Exception
*/
@RequestMapping(value="/uss/umt/EgovIdDplctCnfirmView.do")
public String checkIdDplct(ModelMap model)
throws Exception {
model.addAttribute("checkId", "");
model.addAttribute("usedCnt", "-1");
return "egovframework/com/uss/umt/EgovIdDplctCnfirm";
}
/**
* 입력한 사용자아이디의 중복여부를 체크하여 사용가능여부를 확인
* @param commandMap 파라메터전달용 commandMap
* @param model 화면모델
* @return uss/umt/EgovIdDplctCnfirm
* @throws Exception
*/
@RequestMapping(value="/uss/umt/EgovIdDplctCnfirm.do")
public String checkIdDplct(
Map<String, Object> commandMap,
ModelMap model
)throws Exception {
String checkId = (String)commandMap.get("checkId");
checkId = new String(checkId.getBytes("ISO-8859-1"), "UTF-8");
if (checkId==null || checkId.equals("")) return "forward:/uss/umt/EgovIdDplctCnfirmView.do";
int usedCnt = userManageService.checkIdDplct(checkId);
model.addAttribute("usedCnt", usedCnt);
model.addAttribute("checkId", checkId);
return "egovframework/com/uss/umt/EgovIdDplctCnfirm";
}
/**
* 업무사용자 암호 수정처리 후 화면 이동
* @param model 화면모델
* @param commandMap 파라메터전달용 commandMap
* @param userSearchVO 검색조 건
* @param userManageVO 사용자수정정보(비밀번호)
* @return uss/umt/EgovUserPasswordUpdt
* @throws Exception
*/
@RequestMapping(value="/uss/umt/EgovUserPasswordUpdt.do")
public String updatePassword(ModelMap model,
Map<String, Object> commandMap,
@ModelAttribute("searchVO") UserDefaultVO userSearchVO,
@ModelAttribute("userManageVO") UserManageVO userManageVO)
throws Exception {
String oldPassword = (String)commandMap.get("oldPassword");
String newPassword = (String)commandMap.get("newPassword");
String newPassword2 = (String)commandMap.get("newPassword2");
String uniqId = (String)commandMap.get("uniqId");
boolean isCorrectPassword=false;
UserManageVO resultVO = new UserManageVO();
userManageVO.setPassword(newPassword);
userManageVO.setOldPassword(oldPassword);
userManageVO.setUniqId(uniqId);
String resultMsg = "";
resultVO = userManageService.selectPassword(userManageVO);
//패스워드 암호화
String encryptPass = EgovFileScrty.encryptPassword(oldPassword);
if (encryptPass.equals(resultVO.getPassword())){
if (newPassword.equals(newPassword2)){
isCorrectPassword = true;
}else{
isCorrectPassword = false;
resultMsg="fail.user.passwordUpdate2";
}
}else{
isCorrectPassword = false;
resultMsg="fail.user.passwordUpdate1";
}
if (isCorrectPassword){
userManageVO.setPassword(EgovFileScrty.encryptPassword(newPassword));
userManageService.updatePassword(userManageVO);
model.addAttribute("userManageVO", userManageVO);
resultMsg = "success.common.update";
}else{
model.addAttribute("userManageVO", userManageVO);
}
model.addAttribute("userSearchVO", userSearchVO);
model.addAttribute("resultMsg", resultMsg);
return "egovframework/com/uss/umt/EgovUserPasswordUpdt";
}
/**
* 업무사용자 암호 수정 화면 이동
* @param model 화면모델
* @param commandMap 파라메터전달용 commandMap
* @param userSearchVO 검색조건
* @param userManageVO 사용자수정정보(비밀번호)
* @return uss/umt/EgovUserPasswordUpdt
* @throws Exception
*/
@RequestMapping(value="/uss/umt/EgovUserPasswordUpdtView.do")
public String updatePasswordView(ModelMap model,
Map<String, Object> commandMap,
@ModelAttribute("searchVO") UserDefaultVO userSearchVO,
@ModelAttribute("userManageVO") UserManageVO userManageVO) throws Exception {
String userTyForPassword = (String)commandMap.get("userTyForPassword");
userManageVO.setUserTy(userTyForPassword);
model.addAttribute("userManageVO", userManageVO);
model.addAttribute("userSearchVO", userSearchVO);
return "egovframework/com/uss/umt/EgovUserPasswordUpdt";
}
}
| [
"[email protected]"
] | |
4d85b3b93c4e6d1dd4d40edf3dc4c891371e9412 | 203d6b0924fcc8ffe97197b14b94fdf083d67f7e | /renderer/src/main/java/net/anzix/kogutowicz/element/Relation.java | 7b520bba2dd8e83d2a4f403e95e2331e8408030a | [] | no_license | edwardsayer/kogutowicz | 9bb478a52fe058f38b845d0538135b216b1e6839 | 3526f2d6173180cf83c81564a86c0bce36f42958 | refs/heads/master | 2021-01-01T05:48:06.580315 | 2010-06-06T20:31:39 | 2010-06-06T20:31:39 | 41,657,265 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,610 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.anzix.kogutowicz.element;
import java.util.ArrayList;
import java.util.List;
/**
* Relation map object.
* @author elek
*/
public class Relation extends Element {
private List<RelationMember<Way>> ways = new ArrayList();
private List<RelationMember<Node>> nodes = new ArrayList();
public Relation() {
}
public boolean isIntersect(Box box) {
for (RelationMember<Node> node : nodes) {
if (node.getElement() != null && box.isContains(node.getElement())) {
return true;
}
}
for (RelationMember<Way> way : ways) {
if (way.getElement() != null && way.getElement().isIntersect(box)) {
return true;
}
}
return false;
}
public void addWay(RelationMember<Way> way) {
ways.add(way);
}
public void addNode(RelationMember<Node> node) {
nodes.add(node);
}
public Way getWay(String role) {
for (RelationMember<Way> way : ways) {
if (way.getRole().equals(role)) {
return way.getElement();
}
}
return null;
}
public List<RelationMember<Node>> getNodes() {
return nodes;
}
public void setNodes(List<RelationMember<Node>> nodes) {
this.nodes = nodes;
}
public List<RelationMember<Way>> getWays() {
return ways;
}
public void setWays(List<RelationMember<Way>> ways) {
this.ways = ways;
}
}
| [
"elek@localhost"
] | elek@localhost |
e3558500522d6e6fc48dbd8bf761bef70b1c35ea | f5cd67c0d03903049f4bfb4324cb04d57a326c86 | /src/com/lakshmi/singleton/SingletonNew/EagerSingleton.java | edcd7e9723d24c88afb209619e6ca3d393df5f51 | [] | no_license | lsudersanan88/Design-Principles-And-Patterns | 95f9d1fb3cfe4c1aec56ff90a3a4fa4df996bfcc | e837e3d9c6e0253670f6c926add015464ee25d76 | refs/heads/master | 2020-04-11T10:01:01.637859 | 2018-12-31T03:53:01 | 2018-12-31T03:53:01 | 161,699,796 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 728 | java | package com.lakshmi.singleton.SingletonNew;
public class EagerSingleton {
private static EagerSingleton soleInstance = new EagerSingleton(); //Eager loading
private EagerSingleton()
{
}
public static EagerSingleton getInstance()
{
return soleInstance;
}
}
class Test{
public static void main(String[] args) {
EagerSingleton singleton1 = EagerSingleton.getInstance();
EagerSingleton singleton2 = EagerSingleton.getInstance();
print("s1",singleton1);
print("s2",singleton2);
}
static void print(String name, EagerSingleton object)
{
System.out.println(String.format("Object: %s, Hashcode:%d", name ,object.hashCode()));
}
} | [
"[email protected]"
] | |
df4a035cefe50f89f855ae96ea95360b299add88 | f26fb5fd8aeb1918e9b9588b7e5250a299e6ea78 | /src/pl/michal/debski/itsmeim/model/exceptions/MessageNotConformingToProtocolException.java | 77993d95e5abfeca926e6124a8be36f073ce5c8a | [] | no_license | Neos3452/ItsMeIM | 80bef74ce38575bc6ef5c54f10848859e6c7acb7 | f2c6e5d167e41d97b2205a7e75c7df18736fca6e | refs/heads/master | 2020-05-17T17:31:25.627011 | 2014-05-20T08:07:57 | 2014-05-20T08:08:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 621 | java | package pl.michal.debski.itsmeim.model.exceptions;
/**
* Odebrana wiadomość nie jest wiadomością tego protokołu.
*
* @author Michał Dębski
*/
public class MessageNotConformingToProtocolException extends ProtocolException
{
private static final long serialVersionUID = 1L;
public MessageNotConformingToProtocolException()
{
}
public MessageNotConformingToProtocolException(String arg0)
{
super(arg0);
}
public MessageNotConformingToProtocolException(Throwable arg0)
{
super(arg0);
}
public MessageNotConformingToProtocolException(String arg0, Throwable arg1)
{
super(arg0, arg1);
}
}
| [
"[email protected]"
] | |
9d9e6d8ad4ff3cb5df43d82140865648f398e161 | 8be8f7db33a458e68675fa9e7620db0a6e411f24 | /src/main/java/me/fm/service/UserService.java | dbc59e2f9c84fa090570924369d312f2726e970f | [
"Apache-2.0"
] | permissive | Michael-Z/fm-cloud | f024e1232fd37a19529c9a22692632bc02a281ed | f51a18387f45c00c05b42520bb8497aa78d07f89 | refs/heads/master | 2021-01-16T20:47:56.177753 | 2014-11-06T06:11:59 | 2014-11-06T06:11:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,683 | java | package me.fm.service;
import java.util.List;
import java.util.Map;
import me.fm.cloud.model.User;
import org.unique.plugin.dao.Page;
/**
* 用户接口
* @author:rex
* @date:2014年8月19日
* @version:1.0
*/
public interface UserService {
/**
* 根据uid查询用户
* @param uid
* @return
*/
User getByUid(Integer uid);
/**
* 查询user
* @param email
* @return
*/
User get(String email, Integer status);
/**
* 根据email查询用户是否重复
* @param email
* @return
*/
boolean exists(String email);
/**
* 用户注册
* @param username
* @param email
* @param password
* @return
*/
User register(String username, String email, String password, String ip);
/**
* 用户登录
* @param email
* @param password
* @return
*/
User login(String email, String password);
/**
* 根据email/uid删除用户
* @param email
* @param uid
* @return
*/
int delete(String email, Integer uid);
/**
* 根据uids批量删除用户
* @param uids
* @return
*/
int deleteBatch(String uids);
/**
* 禁用/启用用户
* @param email
* @param uid
* @return
*/
int enable(String email, Integer uid, Integer status);
/**
* 根据查询条件获取用户列表
* @param username
* @param email
* @param status
* @param order
* @return
*/
List<User> getList(String username, String email, Integer status, String order);
/**
* 根据查询条件分页获取用户列表
* @param username
* @param email
* @param status
* @param page
* @param pageSize
* @param order
* @return
*/
Page<User> getPageList(String username, String email, Integer status, Integer page, Integer pageSize, String order);
Page<Map<String, Object>> getPageMapList(String username, String email, Integer status, Integer page, Integer pageSize, String order);
/**
* 增加剩余空间
* @param useSpace
* @return
*/
int updateUseSize(Integer uid, Long useSpace);
int update(Integer uid, String email, String nickName, Long space_size, Integer status);
/**
* 第三方登录
* @param openid
* @param type
* @return
*/
User openLogin(String openid, Integer type);
/**
* 绑定openid
* @param type
* @param openid
* @param nickName
* @param email
* @param ip
* @return
*/
User openBind(Integer type, String openid, String nickName, String email, String ip);
/**
* 获取user map
* @param user
* @param uid
* @return
*/
Map<String, Object> getMap(User user, Integer uid);
}
| [
"[email protected]"
] | |
1bc68fa6b8a879ce6d6c1c3d8ad41ad4823c15ae | b59363f5a6ab61cad6286f176a3390f863e18025 | /SnackOverflow/src/main/java/ro/utcn/sd/vasi/SnackOverflow/repository/jdbc/JdbcQuestionRepository.java | 3077a41473f03409fcb30745fa5f1b3ad509ed23 | [] | no_license | utcn-sd-serban/assignment-1-lupvasile | f51a6189ce48514e8384e5cdf235ecbd3d02bf1f | 948daecb26bc7567789f31c6a6f495e38fd1f7fe | refs/heads/master | 2020-04-27T08:43:52.067010 | 2019-03-24T21:11:21 | 2019-03-24T21:11:21 | 174,183,084 | 0 | 1 | null | 2019-03-25T21:01:20 | 2019-03-06T16:42:32 | Java | UTF-8 | Java | false | false | 2,455 | java | package ro.utcn.sd.vasi.SnackOverflow.repository.jdbc;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import ro.utcn.sd.vasi.SnackOverflow.model.Question;
import ro.utcn.sd.vasi.SnackOverflow.model.Tag;
import ro.utcn.sd.vasi.SnackOverflow.repository.api.QuestionRepository;
import ro.utcn.sd.vasi.SnackOverflow.repository.jdbc.JdbcGeneralRepository;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public class JdbcQuestionRepository extends JdbcGeneralRepository<Question> implements QuestionRepository {
private JdbcTagRepository jdbcTagRepository;
public JdbcQuestionRepository(JdbcTemplate template, JdbcTagRepository tagRepository) {
super(template, Question.class, new QuestionMapper());
this.jdbcTagRepository = tagRepository;
}
@Override
public List<Question> findAll() {
List<Question> questions = super.findAll();
questions.forEach(x->makeQuestionComplete(x));
return questions;
}
@Override
protected int insert(Question question) {
int questionId = super.insert(question);
SimpleJdbcInsert insert = new SimpleJdbcInsert(template);
insert.setTableName("question_tag");
insert.usingGeneratedKeyColumns("id");
Map<String,Object> map = new HashMap<>();
question.getTags().forEach(t-> {
map.clear();
map.put("question",questionId);
map.put("tag",t.getId());
insert.executeAndReturnKey(map);
});
return questionId;
}
@Override
public Optional<Question> findById(int id) {
Optional<Question> q = super.findById(id);
if(q.isPresent()) {
Question goodQ = q.get();
makeQuestionComplete(goodQ);
q = Optional.of(goodQ);
}
return q;
}
private void makeQuestionComplete(Question question) {
List<Integer> tagIds = template.query("SELECT * FROM question_tag WHERE question = ?", (rs, i) -> rs.getInt("tag"),
question.getId());
Set<Tag> tags = new HashSet<>();
tagIds.forEach(tagId->tags.add(jdbcTagRepository.findById(tagId).orElse(null)));
question.getTags().addAll(tags);
}
}
| [
"[email protected]"
] | |
507e0e3df92c9c6d115aab329d8af8487a653e7f | af474f67d4c30fef36c2e84805329974182b701c | /test/com/joshcheek/ttt/cli/PlayerMock.java | 8f7ce10edffb19e218c60d84d8e70f79daaf9672 | [
"MIT"
] | permissive | JoshCheek/java-ttt-cli | a53836a17450b665b5cca4bb97e82e4c4ab56e63 | 9f4b8c28821d39562bf1b417fde58c0dc25af3bd | refs/heads/master | 2021-01-19T21:28:32.617041 | 2011-09-13T04:06:33 | 2011-09-13T04:06:33 | 2,376,011 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 608 | java | package com.joshcheek.ttt.cli;
import com.joshcheek.ttt.library.Game;
import com.joshcheek.ttt.library.Player;
/**
* Created by IntelliJ IDEA.
* User: joshuajcheek
* Date: 9/8/11
* Time: 8:25 PM
* To change this template use File | Settings | File Templates.
*/
public class PlayerMock implements Player {
private int currentMove = 0;
private int[] moves;
private Game game;
public PlayerMock(int[] moves, Game game) {
this.moves = moves;
this.game = game;
currentMove = 0;
}
public void takeTurn() {
game.mark(moves[currentMove++]);
}
}
| [
"[email protected]"
] | |
b04b91c578277aaf0c3731ae5d4292c72da90640 | d383d855e48ee2f5da65791f4052533eca339369 | /src/main/java/com/alibaba/druid/sql/parser/SQLExprParser.java | 77c73d8a9e7ed049704f7f19af6ea554ee3da120 | [
"Apache-2.0"
] | permissive | liuxing7954/druid-source | 0e2dc0b1a2f498045b8689d6431764f4f4525070 | fc27b5ac4695dc42e1daa62db012adda7c217d36 | refs/heads/master | 2022-12-21T14:53:26.923986 | 2020-02-29T07:15:15 | 2020-02-29T07:15:15 | 243,908,145 | 1 | 1 | NOASSERTION | 2022-12-16T09:54:44 | 2020-02-29T05:07:04 | Java | UTF-8 | Java | false | false | 130,445 | java | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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.alibaba.druid.sql.parser;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLCommentHint;
import com.alibaba.druid.sql.ast.SQLDataType;
import com.alibaba.druid.sql.ast.SQLDataTypeImpl;
import com.alibaba.druid.sql.ast.SQLDataTypeRefExpr;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLLimit;
import com.alibaba.druid.sql.ast.SQLName;
import com.alibaba.druid.sql.ast.SQLObject;
import com.alibaba.druid.sql.ast.SQLOrderBy;
import com.alibaba.druid.sql.ast.SQLOrderingSpecification;
import com.alibaba.druid.sql.ast.SQLOver;
import com.alibaba.druid.sql.ast.SQLPartition;
import com.alibaba.druid.sql.ast.SQLPartitionBy;
import com.alibaba.druid.sql.ast.SQLPartitionValue;
import com.alibaba.druid.sql.ast.expr.SQLAggregateExpr;
import com.alibaba.druid.sql.ast.expr.SQLAggregateOption;
import com.alibaba.druid.sql.ast.expr.SQLAllColumnExpr;
import com.alibaba.druid.sql.ast.expr.SQLAllExpr;
import com.alibaba.druid.sql.ast.expr.SQLAnyExpr;
import com.alibaba.druid.sql.ast.expr.SQLBetweenExpr;
import com.alibaba.druid.sql.ast.expr.SQLBinaryExpr;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExprGroup;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOperator;
import com.alibaba.druid.sql.ast.expr.SQLBooleanExpr;
import com.alibaba.druid.sql.ast.expr.SQLCaseExpr;
import com.alibaba.druid.sql.ast.expr.SQLCastExpr;
import com.alibaba.druid.sql.ast.expr.SQLCharExpr;
import com.alibaba.druid.sql.ast.expr.SQLContainsExpr;
import com.alibaba.druid.sql.ast.expr.SQLCurrentOfCursorExpr;
import com.alibaba.druid.sql.ast.expr.SQLDateExpr;
import com.alibaba.druid.sql.ast.expr.SQLDefaultExpr;
import com.alibaba.druid.sql.ast.expr.SQLExistsExpr;
import com.alibaba.druid.sql.ast.expr.SQLGroupingSetExpr;
import com.alibaba.druid.sql.ast.expr.SQLHexExpr;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.expr.SQLInListExpr;
import com.alibaba.druid.sql.ast.expr.SQLInSubQueryExpr;
import com.alibaba.druid.sql.ast.expr.SQLIntegerExpr;
import com.alibaba.druid.sql.ast.expr.SQLListExpr;
import com.alibaba.druid.sql.ast.expr.SQLMethodInvokeExpr;
import com.alibaba.druid.sql.ast.expr.SQLNCharExpr;
import com.alibaba.druid.sql.ast.expr.SQLNotExpr;
import com.alibaba.druid.sql.ast.expr.SQLNullExpr;
import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;
import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
import com.alibaba.druid.sql.ast.expr.SQLSequenceExpr;
import com.alibaba.druid.sql.ast.expr.SQLSomeExpr;
import com.alibaba.druid.sql.ast.expr.SQLTimestampExpr;
import com.alibaba.druid.sql.ast.expr.SQLUnaryExpr;
import com.alibaba.druid.sql.ast.expr.SQLUnaryOperator;
import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr;
import com.alibaba.druid.sql.ast.statement.SQLAssignItem;
import com.alibaba.druid.sql.ast.statement.SQLCharacterDataType;
import com.alibaba.druid.sql.ast.statement.SQLCheck;
import com.alibaba.druid.sql.ast.statement.SQLColumnCheck;
import com.alibaba.druid.sql.ast.statement.SQLColumnDefinition;
import com.alibaba.druid.sql.ast.statement.SQLColumnPrimaryKey;
import com.alibaba.druid.sql.ast.statement.SQLColumnReference;
import com.alibaba.druid.sql.ast.statement.SQLColumnUniqueKey;
import com.alibaba.druid.sql.ast.statement.SQLConstraint;
import com.alibaba.druid.sql.ast.statement.SQLForeignKeyConstraint;
import com.alibaba.druid.sql.ast.statement.SQLForeignKeyImpl;
import com.alibaba.druid.sql.ast.statement.SQLNotNullConstraint;
import com.alibaba.druid.sql.ast.statement.SQLNullConstraint;
import com.alibaba.druid.sql.ast.statement.SQLPrimaryKey;
import com.alibaba.druid.sql.ast.statement.SQLPrimaryKeyImpl;
import com.alibaba.druid.sql.ast.statement.SQLSelect;
import com.alibaba.druid.sql.ast.statement.SQLSelectItem;
import com.alibaba.druid.sql.ast.statement.SQLSelectOrderByItem;
import com.alibaba.druid.sql.ast.statement.SQLSelectQuery;
import com.alibaba.druid.sql.ast.statement.SQLUnique;
import com.alibaba.druid.sql.ast.statement.SQLUpdateSetItem;
import com.alibaba.druid.sql.dialect.oracle.ast.expr.OracleArgumentExpr;
import com.alibaba.druid.sql.dialect.postgresql.ast.expr.PGTypeCastExpr;
import com.alibaba.druid.util.FnvHash;
import com.alibaba.druid.util.JdbcConstants;
public class SQLExprParser extends SQLParser {
public final static String[] AGGREGATE_FUNCTIONS;
public final static long[] AGGREGATE_FUNCTIONS_CODES;
static {
String[] strings = { "AVG", "COUNT", "MAX", "MIN", "STDDEV", "SUM" };
AGGREGATE_FUNCTIONS_CODES = FnvHash.fnv1a_64_lower(strings, true);
AGGREGATE_FUNCTIONS = new String[AGGREGATE_FUNCTIONS_CODES.length];
for (String str : strings) {
long hash = FnvHash.fnv1a_64_lower(str);
int index = Arrays.binarySearch(AGGREGATE_FUNCTIONS_CODES, hash);
AGGREGATE_FUNCTIONS[index] = str;
}
}
protected String[] aggregateFunctions = AGGREGATE_FUNCTIONS;
protected long[] aggregateFunctionHashCodes = AGGREGATE_FUNCTIONS_CODES;
protected boolean allowIdentifierMethod = true;
public SQLExprParser(String sql){
super(sql);
}
public SQLExprParser(String sql, String dbType){
super(sql, dbType);
}
public SQLExprParser(Lexer lexer){
super(lexer);
}
public SQLExprParser(Lexer lexer, String dbType){
super(lexer, dbType);
}
public SQLExpr expr() {
if (lexer.token == Token.STAR) {
lexer.nextToken();
SQLExpr expr = new SQLAllColumnExpr();
if (lexer.token == Token.DOT) {
lexer.nextToken();
accept(Token.STAR);
return new SQLPropertyExpr(expr, "*");
}
return expr;
}
SQLExpr expr = primary();
Token token = lexer.token;
if (token == Token.COMMA) {
return expr;
} else if (token == Token.EQ) {
expr = relationalRest(expr);
expr = andRest(expr);
expr = xorRest(expr);
expr = orRest(expr);
return expr;
} else {
return exprRest(expr);
}
}
public SQLExpr exprRest(SQLExpr expr) {
expr = bitXorRest(expr);
expr = multiplicativeRest(expr);
expr = additiveRest(expr);
expr = shiftRest(expr);
expr = bitAndRest(expr);
expr = bitOrRest(expr);
expr = inRest(expr);
expr = relationalRest(expr);
// expr = equalityRest(expr);
expr = andRest(expr);
expr = xorRest(expr);
expr = orRest(expr);
return expr;
}
public final SQLExpr bitXor() {
SQLExpr expr = primary();
return bitXorRest(expr);
}
public SQLExpr bitXorRest(SQLExpr expr) {
Token token = lexer.token;
switch (token) {
case CARET: {
lexer.nextToken();
SQLBinaryOperator op;
if (lexer.token == Token.EQ) {
lexer.nextToken();
op = SQLBinaryOperator.BitwiseXorEQ;
} else {
op = SQLBinaryOperator.BitwiseXor;
}
SQLExpr rightExp = primary();
expr = new SQLBinaryOpExpr(expr, op, rightExp, dbType);
expr = bitXorRest(expr);
break;
}
case SUBGT:{
lexer.nextToken();
SQLExpr rightExp = primary();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.SubGt, rightExp, dbType);
expr = bitXorRest(expr);
break;
}
case LT_SUB_GT: {
lexer.nextToken();
SQLExpr rightExp = primary();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.PG_ST_DISTANCE, rightExp, dbType);
expr = bitXorRest(expr);
break;
}
case SUBGTGT:{
lexer.nextToken();
SQLExpr rightExp = primary();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.SubGtGt, rightExp, dbType);
expr = bitXorRest(expr);
break;
}
case POUNDGT: {
lexer.nextToken();
SQLExpr rightExp = primary();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.PoundGt, rightExp, dbType);
expr = bitXorRest(expr);
break;
}
case POUNDGTGT: {
lexer.nextToken();
SQLExpr rightExp = primary();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.PoundGtGt, rightExp, dbType);
expr = bitXorRest(expr);
break;
}
case QUESQUES: {
lexer.nextToken();
SQLExpr rightExp = primary();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.QuesQues, rightExp, dbType);
expr = bitXorRest(expr);
break;
}
case QUESBAR: {
lexer.nextToken();
SQLExpr rightExp = primary();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.QuesBar, rightExp, dbType);
expr = bitXorRest(expr);
break;
}
case QUESAMP: {
lexer.nextToken();
SQLExpr rightExp = primary();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.QuesAmp, rightExp, dbType);
expr = bitXorRest(expr);
break;
}
default:
break;
}
return expr;
}
public final SQLExpr multiplicative() {
SQLExpr expr = bitXor();
return multiplicativeRest(expr);
}
public SQLExpr multiplicativeRest(SQLExpr expr) {
final Token token = lexer.token;
if (token == Token.STAR) {
lexer.nextToken();
SQLExpr rightExp = bitXor();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Multiply, rightExp, getDbType());
expr = multiplicativeRest(expr);
} else if (token == Token.SLASH) {
lexer.nextToken();
SQLExpr rightExp = bitXor();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Divide, rightExp, getDbType());
expr = multiplicativeRest(expr);
} else if (token == Token.PERCENT) {
lexer.nextToken();
SQLExpr rightExp = bitXor();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Modulus, rightExp, getDbType());
expr = multiplicativeRest(expr);
} else if (token == Token.DIV) {
lexer.nextToken();
SQLExpr rightExp = bitXor();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.DIV, rightExp, getDbType());
expr = multiplicativeRest(expr);
} else if (lexer.identifierEquals(FnvHash.Constants.MOD) || lexer.token == Token.MOD) {
Lexer.SavePoint savePoint = lexer.mark();
lexer.nextToken();
if (lexer.token == Token.COMMA || lexer.token == Token.EOF) {
lexer.reset(savePoint);
return expr;
}
SQLExpr rightExp = bitXor();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Modulus, rightExp, dbType);
expr = multiplicativeRest(expr);
}
return expr;
}
public SQLIntegerExpr integerExpr() {
SQLIntegerExpr intExpr = new SQLIntegerExpr(lexer.integerValue());
accept(Token.LITERAL_INT);
return intExpr;
}
public int parseIntValue() {
if (lexer.token == Token.LITERAL_INT) {
Number number = this.lexer.integerValue();
int intVal = ((Integer) number).intValue();
lexer.nextToken();
return intVal;
} else {
throw new ParserException("not int. " + lexer.info());
}
}
public SQLExpr primary() {
List<String> beforeComments = null;
if (lexer.isKeepComments() && lexer.hasComment()) {
beforeComments = lexer.readAndResetComments();
}
SQLExpr sqlExpr = null;
final Token tok = lexer.token;
switch (tok) {
case LPAREN:
lexer.nextToken();
sqlExpr = expr();
if (lexer.token == Token.COMMA) {
SQLListExpr listExpr = new SQLListExpr();
listExpr.addItem(sqlExpr);
do {
lexer.nextToken();
listExpr.addItem(expr());
} while (lexer.token == Token.COMMA);
sqlExpr = listExpr;
}
if (sqlExpr instanceof SQLBinaryOpExpr) {
((SQLBinaryOpExpr) sqlExpr).setBracket(true);
}
accept(Token.RPAREN);
if (lexer.token == Token.UNION && sqlExpr instanceof SQLQueryExpr) {
SQLQueryExpr queryExpr = (SQLQueryExpr) sqlExpr;
SQLSelectQuery query = this.createSelectParser().queryRest(queryExpr.getSubQuery().getQuery());
queryExpr.getSubQuery().setQuery(query);
}
//accept(Token.RPAREN) 在处理UNION 之前,导致 以下类型的语句解析异常
//select * from test_a where id=(select id from test_b where id = 1) union all select * from test_c .....
//会解析为 select * from select * from test_a where id=(select id from test_b where id = 1 union all select * from test_c .....
//所以需要将accept(Token.RPAREN) 移动到 处理 Union all 以及 子查询之后
break;
case INSERT:
lexer.nextToken();
if (lexer.token != Token.LPAREN) {
throw new ParserException("syntax error. " + lexer.info());
}
sqlExpr = new SQLIdentifierExpr("INSERT");
break;
case IDENTIFIER:
String ident = lexer.stringVal();
long hash_lower = lexer.hash_lower;
lexer.nextToken();
if (hash_lower == FnvHash.Constants.DATE
&& (lexer.token == Token.LITERAL_CHARS || lexer.token == Token.VARIANT)
&& (JdbcConstants.ORACLE.equals(dbType)
|| JdbcConstants.POSTGRESQL.equals(dbType)
|| JdbcConstants.MYSQL.equals(dbType))) {
SQLExpr literal = this.primary();
SQLDateExpr dateExpr = new SQLDateExpr();
dateExpr.setLiteral(literal);
sqlExpr = dateExpr;
} else if (hash_lower == FnvHash.Constants.TIMESTAMP
&& (lexer.token == Token.LITERAL_CHARS || lexer.token == Token.VARIANT)
&& !JdbcConstants.ORACLE.equals(dbType)) {
SQLTimestampExpr dateExpr = new SQLTimestampExpr(lexer.stringVal());
lexer.nextToken();
sqlExpr = dateExpr;
} else if (JdbcConstants.MYSQL.equalsIgnoreCase(dbType) && ident.startsWith("0x") && (ident.length() % 2) == 0) {
sqlExpr = new SQLHexExpr(ident.substring(2));
} else {
if (ident.charAt(0) == '`') {
if (lexer.isEnabled(SQLParserFeature.IgnoreNameQuotes)) {
ident = ident.substring(1, ident.length() - 1);
}
hash_lower = FnvHash.hashCode64(ident);
}
sqlExpr = new SQLIdentifierExpr(ident, hash_lower);
}
break;
case NEW:
throw new ParserException("TODO " + lexer.info());
case LITERAL_INT:
sqlExpr = new SQLIntegerExpr(lexer.integerValue());
lexer.nextToken();
break;
case LITERAL_FLOAT:
sqlExpr = lexer.numberExpr();
lexer.nextToken();
break;
case LITERAL_CHARS: {
sqlExpr = new SQLCharExpr(lexer.stringVal());
if (JdbcConstants.MYSQL.equals(dbType)) {
lexer.nextTokenValue();
for (; ; ) {
if (lexer.token == Token.LITERAL_ALIAS) {
String concat = ((SQLCharExpr) sqlExpr).getText();
concat += lexer.stringVal();
lexer.nextTokenValue();
sqlExpr = new SQLCharExpr(concat);
} else if (lexer.token == Token.LITERAL_CHARS || lexer.token == Token.LITERAL_NCHARS) {
String concat = ((SQLCharExpr) sqlExpr).getText();
concat += lexer.stringVal();
lexer.nextTokenValue();
sqlExpr = new SQLCharExpr(concat);
} else {
break;
}
}
} else {
lexer.nextToken();
}
break;
} case LITERAL_NCHARS:
sqlExpr = new SQLNCharExpr(lexer.stringVal());
lexer.nextToken();
if (JdbcConstants.MYSQL.equals(dbType)) {
SQLMethodInvokeExpr concat = null;
for (; ; ) {
if (lexer.token == Token.LITERAL_ALIAS) {
if (concat == null) {
concat = new SQLMethodInvokeExpr("CONCAT");
concat.addParameter(sqlExpr);
sqlExpr = concat;
}
String alias = lexer.stringVal();
lexer.nextToken();
SQLCharExpr concat_right = new SQLCharExpr(alias.substring(1, alias.length() - 1));
concat.addParameter(concat_right);
} else if (lexer.token == Token.LITERAL_CHARS || lexer.token == Token.LITERAL_NCHARS) {
if (concat == null) {
concat = new SQLMethodInvokeExpr("CONCAT");
concat.addParameter(sqlExpr);
sqlExpr = concat;
}
String chars = lexer.stringVal();
lexer.nextToken();
SQLCharExpr concat_right = new SQLCharExpr(chars);
concat.addParameter(concat_right);
} else {
break;
}
}
}
break;
case VARIANT: {
String varName = lexer.stringVal();
lexer.nextToken();
if (varName.equals(":") && lexer.token == Token.IDENTIFIER && JdbcConstants.ORACLE.equals(dbType)) {
String part2 = lexer.stringVal();
lexer.nextToken();
varName += part2;
}
SQLVariantRefExpr varRefExpr = new SQLVariantRefExpr(varName);
if (varName.startsWith(":")) {
varRefExpr.setIndex(lexer.nextVarIndex());
}
if (varRefExpr.getName().equals("@") && lexer.token == Token.LITERAL_CHARS) {
varRefExpr.setName("@'" + lexer.stringVal() + "'");
lexer.nextToken();
} else if (varRefExpr.getName().equals("@@") && lexer.token == Token.LITERAL_CHARS) {
varRefExpr.setName("@@'" + lexer.stringVal() + "'");
lexer.nextToken();
}
sqlExpr = varRefExpr;
}
break;
case DEFAULT:
sqlExpr = new SQLDefaultExpr();
lexer.nextToken();
break;
case DUAL:
case KEY:
case LIMIT:
case SCHEMA:
case COLUMN:
case IF:
case END:
case COMMENT:
case COMPUTE:
case ENABLE:
case DISABLE:
case INITIALLY:
case SEQUENCE:
case USER:
case EXPLAIN:
case WITH:
case GRANT:
case REPLACE:
case INDEX:
case MODEL:
case PCTFREE:
case INITRANS:
case MAXTRANS:
case SEGMENT:
case CREATION:
case IMMEDIATE:
case DEFERRED:
case STORAGE:
case NEXT:
case MINEXTENTS:
case MAXEXTENTS:
case MAXSIZE:
case PCTINCREASE:
case FLASH_CACHE:
case CELL_FLASH_CACHE:
case NONE:
case LOB:
case STORE:
case ROW:
case CHUNK:
case CACHE:
case NOCACHE:
case LOGGING:
case NOCOMPRESS:
case KEEP_DUPLICATES:
case EXCEPTIONS:
case PURGE:
case FULL:
case TO:
case IDENTIFIED:
case PASSWORD:
case BINARY:
case WINDOW:
case OFFSET:
case SHARE:
case START:
case CONNECT:
case MATCHED:
case ERRORS:
case REJECT:
case UNLIMITED:
case BEGIN:
case EXCLUSIVE:
case MODE:
case ADVISE:
case VIEW:
case ESCAPE:
case OVER:
case ORDER:
case CONSTRAINT:
case TYPE:
case OPEN:
case REPEAT:
case TABLE:
case TRUNCATE:
case EXCEPTION:
case FUNCTION:
case IDENTITY:
case EXTRACT:
case DESC:
case DO:
case GROUP:
case MOD:
case CONCAT:
sqlExpr = new SQLIdentifierExpr(lexer.stringVal());
lexer.nextToken();
break;
case CASE:
SQLCaseExpr caseExpr = new SQLCaseExpr();
lexer.nextToken();
if (lexer.token != Token.WHEN) {
caseExpr.setValueExpr(expr());
}
accept(Token.WHEN);
SQLExpr testExpr = expr();
accept(Token.THEN);
SQLExpr valueExpr = expr();
SQLCaseExpr.Item caseItem = new SQLCaseExpr.Item(testExpr, valueExpr);
caseExpr.addItem(caseItem);
while (lexer.token == Token.WHEN) {
lexer.nextToken();
testExpr = expr();
accept(Token.THEN);
valueExpr = expr();
caseItem = new SQLCaseExpr.Item(testExpr, valueExpr);
caseExpr.addItem(caseItem);
}
if (lexer.token == Token.ELSE) {
lexer.nextToken();
caseExpr.setElseExpr(expr());
}
accept(Token.END);
sqlExpr = caseExpr;
break;
case EXISTS:
lexer.nextToken();
accept(Token.LPAREN);
sqlExpr = new SQLExistsExpr(createSelectParser().select());
accept(Token.RPAREN);
break;
case NOT:
lexer.nextToken();
if (lexer.token == Token.EXISTS) {
lexer.nextToken();
accept(Token.LPAREN);
sqlExpr = new SQLExistsExpr(createSelectParser().select(), true);
accept(Token.RPAREN);
} else if (lexer.token == Token.LPAREN) {
lexer.nextToken();
SQLExpr notTarget = expr();
accept(Token.RPAREN);
notTarget = relationalRest(notTarget);
sqlExpr = new SQLNotExpr(notTarget);
return primaryRest(sqlExpr);
} else {
SQLExpr restExpr = relational();
sqlExpr = new SQLNotExpr(restExpr);
}
break;
case SELECT:
SQLQueryExpr queryExpr = new SQLQueryExpr(
createSelectParser()
.select());
sqlExpr = queryExpr;
break;
case CAST:
lexer.nextToken();
accept(Token.LPAREN);
SQLCastExpr cast = new SQLCastExpr();
cast.setExpr(expr());
accept(Token.AS);
cast.setDataType(parseDataType(false));
accept(Token.RPAREN);
sqlExpr = cast;
break;
case SUB:
lexer.nextToken();
switch (lexer.token) {
case LITERAL_INT:
Number integerValue = lexer.integerValue();
if (integerValue instanceof Integer) {
int intVal = ((Integer) integerValue).intValue();
if (intVal == Integer.MIN_VALUE) {
integerValue = Long.valueOf(((long) intVal) * -1);
} else {
integerValue = Integer.valueOf(intVal * -1);
}
} else if (integerValue instanceof Long) {
long longVal = ((Long) integerValue).longValue();
if (longVal == 2147483648L) {
integerValue = Integer.valueOf((int) (((long) longVal) * -1));
} else {
integerValue = Long.valueOf(longVal * -1);
}
} else {
integerValue = ((BigInteger) integerValue).negate();
}
sqlExpr = new SQLIntegerExpr(integerValue);
lexer.nextToken();
break;
case LITERAL_FLOAT:
sqlExpr = lexer.numberExpr(true);
lexer.nextToken();
break;
case IDENTIFIER: // 当负号后面为字段的情况
case LITERAL_CHARS:
case LITERAL_ALIAS:
sqlExpr = new SQLIdentifierExpr(lexer.stringVal());
lexer.nextToken();
if (lexer.token == Token.LPAREN || lexer.token == Token.LBRACKET) {
sqlExpr = primaryRest(sqlExpr);
}
sqlExpr = new SQLUnaryExpr(SQLUnaryOperator.Negative, sqlExpr);
break;
case QUES: {
SQLVariantRefExpr variantRefExpr = new SQLVariantRefExpr("?");
variantRefExpr.setIndex(lexer.nextVarIndex());
sqlExpr = new SQLUnaryExpr(SQLUnaryOperator.Negative, variantRefExpr);
lexer.nextToken();
break;
}
case LPAREN:
lexer.nextToken();
sqlExpr = expr();
accept(Token.RPAREN);
sqlExpr = new SQLUnaryExpr(SQLUnaryOperator.Negative, sqlExpr);
break;
case BANG:
case CAST:
sqlExpr = expr();
sqlExpr = new SQLUnaryExpr(SQLUnaryOperator.Negative, sqlExpr);
break;
default:
throw new ParserException("TODO : " + lexer.info());
}
break;
case PLUS:
lexer.nextToken();
switch (lexer.token) {
case LITERAL_INT:
sqlExpr = new SQLIntegerExpr(lexer.integerValue());
lexer.nextToken();
break;
case LITERAL_FLOAT:
sqlExpr = lexer.numberExpr();
lexer.nextToken();
break;
case IDENTIFIER: // 当+号后面为字段的情况
case LITERAL_CHARS:
case LITERAL_ALIAS:
sqlExpr = new SQLIdentifierExpr(lexer.stringVal());
sqlExpr = new SQLUnaryExpr(SQLUnaryOperator.Plus, sqlExpr);
lexer.nextToken();
break;
case LPAREN:
lexer.nextToken();
sqlExpr = expr();
accept(Token.RPAREN);
sqlExpr = new SQLUnaryExpr(SQLUnaryOperator.Plus, sqlExpr);
break;
case SUB:
case CAST:
sqlExpr = expr();
sqlExpr = new SQLUnaryExpr(SQLUnaryOperator.Plus, sqlExpr);
break;
default:
throw new ParserException("TODO " + lexer.info());
}
break;
case TILDE:
lexer.nextToken();
SQLExpr unaryValueExpr = primary();
SQLUnaryExpr unary = new SQLUnaryExpr(SQLUnaryOperator.Compl, unaryValueExpr);
sqlExpr = unary;
break;
case QUES:
if (JdbcConstants.MYSQL.equals(dbType)) {
lexer.nextTokenValue();
} else {
lexer.nextToken();
}
SQLVariantRefExpr quesVarRefExpr = new SQLVariantRefExpr("?");
quesVarRefExpr.setIndex(lexer.nextVarIndex());
sqlExpr = quesVarRefExpr;
break;
case LEFT:
sqlExpr = new SQLIdentifierExpr("LEFT");
lexer.nextToken();
break;
case RIGHT:
sqlExpr = new SQLIdentifierExpr("RIGHT");
lexer.nextToken();
break;
case DATABASE:
sqlExpr = new SQLIdentifierExpr("DATABASE");
lexer.nextToken();
break;
case LOCK:
sqlExpr = new SQLIdentifierExpr("LOCK");
lexer.nextToken();
break;
case NULL:
sqlExpr = new SQLNullExpr();
lexer.nextToken();
break;
case BANG:
lexer.nextToken();
SQLExpr bangExpr = primary();
sqlExpr = new SQLUnaryExpr(SQLUnaryOperator.Not, bangExpr);
break;
case LITERAL_HEX:
String hex = lexer.hexString();
sqlExpr = new SQLHexExpr(hex);
lexer.nextToken();
break;
case INTERVAL:
sqlExpr = parseInterval();
break;
case COLON:
lexer.nextToken();
if (lexer.token == Token.LITERAL_ALIAS) {
sqlExpr = new SQLVariantRefExpr(":\"" + lexer.stringVal() + "\"");
lexer.nextToken();
}
break;
case ANY:
sqlExpr = parseAny();
break;
case SOME:
sqlExpr = parseSome();
break;
case ALL:
sqlExpr = parseAll();
break;
case LITERAL_ALIAS:
sqlExpr = parseAliasExpr(lexer.stringVal());
lexer.nextToken();
break;
case EOF:
throw new EOFParserException();
case TRUE:
lexer.nextToken();
sqlExpr = new SQLBooleanExpr(true);
break;
case FALSE:
lexer.nextToken();
sqlExpr = new SQLBooleanExpr(false);
break;
case BITS: {
String strVal = lexer.stringVal();
lexer.nextToken();
sqlExpr = new SQLBinaryExpr(strVal);
break;
}
case CONTAINS:
sqlExpr = inRest(null);
break;
case SET: {
Lexer.SavePoint savePoint = lexer.mark();
lexer.nextToken();
if (lexer.token() == Token.LPAREN) {
sqlExpr = new SQLIdentifierExpr("SET");
} else {
lexer.reset(savePoint);
throw new ParserException("ERROR. " + lexer.info());
}
break;
}
default:
throw new ParserException("ERROR. " + lexer.info());
}
SQLExpr expr = primaryRest(sqlExpr);
if (beforeComments != null) {
expr.addBeforeComment(beforeComments);
}
return expr;
}
protected SQLExpr parseAll() {
SQLExpr sqlExpr;
lexer.nextToken();
SQLAllExpr allExpr = new SQLAllExpr();
accept(Token.LPAREN);
SQLSelect allSubQuery = createSelectParser().select();
allExpr.setSubQuery(allSubQuery);
accept(Token.RPAREN);
allSubQuery.setParent(allExpr);
sqlExpr = allExpr;
return sqlExpr;
}
protected SQLExpr parseSome() {
SQLExpr sqlExpr;
lexer.nextToken();
SQLSomeExpr someExpr = new SQLSomeExpr();
accept(Token.LPAREN);
SQLSelect someSubQuery = createSelectParser().select();
someExpr.setSubQuery(someSubQuery);
accept(Token.RPAREN);
someSubQuery.setParent(someExpr);
sqlExpr = someExpr;
return sqlExpr;
}
protected SQLExpr parseAny() {
SQLExpr sqlExpr;
lexer.nextToken();
if (lexer.token == Token.LPAREN) {
accept(Token.LPAREN);
if (lexer.token == Token.ARRAY || lexer.token == Token.IDENTIFIER) {
SQLExpr expr = this.expr();
SQLMethodInvokeExpr methodInvokeExpr = new SQLMethodInvokeExpr("ANY");
methodInvokeExpr.addParameter(expr);
accept(Token.RPAREN);
return methodInvokeExpr;
}
SQLSelect anySubQuery = createSelectParser().select();
SQLAnyExpr anyExpr = new SQLAnyExpr(anySubQuery);
accept(Token.RPAREN);
sqlExpr = anyExpr;
} else {
sqlExpr = new SQLIdentifierExpr("ANY");
}
return sqlExpr;
}
protected SQLExpr parseAliasExpr(String alias) {
return new SQLIdentifierExpr(alias);
}
protected SQLExpr parseInterval() {
throw new ParserException("TODO. " + lexer.info());
}
public SQLSelectParser createSelectParser() {
return new SQLSelectParser(this);
}
public SQLExpr primaryRest(SQLExpr expr) {
if (expr == null) {
throw new IllegalArgumentException("expr");
}
Token token = lexer.token;
if (token == Token.OF) {
if (expr instanceof SQLIdentifierExpr) {
long hashCode64 = ((SQLIdentifierExpr) expr).hashCode64();
if (hashCode64 == FnvHash.Constants.CURRENT) {
lexer.nextToken();
SQLName cursorName = this.name();
return new SQLCurrentOfCursorExpr(cursorName);
}
}
} else if (token == Token.FOR) {
if (expr instanceof SQLIdentifierExpr) {
SQLIdentifierExpr idenExpr = (SQLIdentifierExpr) expr;
if (idenExpr.hashCode64() == FnvHash.Constants.NEXTVAL) {
lexer.nextToken();
SQLName seqName = this.name();
SQLSequenceExpr seqExpr = new SQLSequenceExpr(seqName, SQLSequenceExpr.Function.NextVal);
return seqExpr;
} else if (idenExpr.hashCode64() == FnvHash.Constants.CURRVAL) {
lexer.nextToken();
SQLName seqName = this.name();
SQLSequenceExpr seqExpr = new SQLSequenceExpr(seqName, SQLSequenceExpr.Function.CurrVal);
return seqExpr;
} else if (idenExpr.hashCode64() == FnvHash.Constants.PREVVAL) {
lexer.nextToken();
SQLName seqName = this.name();
SQLSequenceExpr seqExpr = new SQLSequenceExpr(seqName, SQLSequenceExpr.Function.PrevVal);
return seqExpr;
}
}
}
if (token == Token.DOT) {
lexer.nextToken();
if (expr instanceof SQLCharExpr) {
String text = ((SQLCharExpr) expr).getText();
expr = new SQLIdentifierExpr(text);
}
expr = dotRest(expr);
return primaryRest(expr);
} else if (lexer.identifierEquals(FnvHash.Constants.SETS) //
&& expr.getClass() == SQLIdentifierExpr.class //
&& "GROUPING".equalsIgnoreCase(((SQLIdentifierExpr) expr).getName())) {
SQLGroupingSetExpr groupingSets = new SQLGroupingSetExpr();
lexer.nextToken();
accept(Token.LPAREN);
for (; ; ) {
SQLExpr item;
if (lexer.token == Token.LPAREN) {
lexer.nextToken();
SQLListExpr listExpr = new SQLListExpr();
this.exprList(listExpr.getItems(), listExpr);
item = listExpr;
accept(Token.RPAREN);
} else {
item = this.expr();
}
item.setParent(groupingSets);
groupingSets.addParameter(item);
if (lexer.token == Token.RPAREN) {
break;
}
accept(Token.COMMA);
}
this.exprList(groupingSets.getParameters(), groupingSets);
accept(Token.RPAREN);
return groupingSets;
} else {
if (lexer.token == Token.LPAREN) {
return methodRest(expr, true);
}
}
return expr;
}
protected SQLExpr parseExtract() {
throw new ParserException("not supported.");
}
protected SQLExpr parsePosition() {
throw new ParserException("not supported.");
}
protected SQLExpr parseMatch() {
throw new ParserException("not supported.");
}
protected SQLExpr methodRest(SQLExpr expr, boolean acceptLPAREN) {
if (acceptLPAREN) {
accept(Token.LPAREN);
}
boolean distinct = false;
if (lexer.token == Token.DISTINCT) {
lexer.nextToken();
distinct = true;
if (lexer.token == Token.RPAREN || lexer.token == Token.COMMA) {
throw new ParserException(lexer.info());
}
}
String methodName = null;
String aggMethodName = null;
SQLMethodInvokeExpr methodInvokeExpr;
SQLExpr owner = null;
String trimOption = null;
long hash_lower = 0L;
if (expr instanceof SQLIdentifierExpr) {
SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) expr;
methodName = identifierExpr.getName();
hash_lower = identifierExpr.nameHashCode64();
if (allowIdentifierMethod) {
if (hash_lower == FnvHash.Constants.TRIM) {
if (lexer.identifierEquals(FnvHash.Constants.LEADING)) {
trimOption = lexer.stringVal();
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.BOTH)) {
trimOption = lexer.stringVal();
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.TRAILING)) {
trimOption = lexer.stringVal();
lexer.nextToken();
}
} else if (hash_lower == FnvHash.Constants.MATCH
&& (JdbcConstants.MYSQL.equals(dbType) || JdbcConstants.ALIYUN_ADS.equals(dbType))) {
return parseMatch();
} else if (hash_lower == FnvHash.Constants.EXTRACT
&& JdbcConstants.MYSQL.equals(dbType)) {
return parseExtract();
} else if (hash_lower == FnvHash.Constants.POSITION
&& JdbcConstants.MYSQL.equals(dbType)) {
return parsePosition();
}else if (hash_lower == FnvHash.Constants.INT4 && JdbcConstants.POSTGRESQL.equals(dbType)) {
PGTypeCastExpr castExpr = new PGTypeCastExpr();
castExpr.setExpr(this.expr());
castExpr.setDataType(new SQLDataTypeImpl(methodName));
accept(Token.RPAREN);
return castExpr;
} else if (hash_lower == FnvHash.Constants.VARBIT && JdbcConstants.POSTGRESQL.equals(dbType)) {
PGTypeCastExpr castExpr = new PGTypeCastExpr();
SQLExpr len = this.primary();
castExpr.setDataType(new SQLDataTypeImpl(methodName, len));
accept(Token.RPAREN);
castExpr.setExpr(this.expr());
return castExpr;
} else if (hash_lower == FnvHash.Constants.CONVERT && JdbcConstants.MYSQL.equals(dbType)) {
methodInvokeExpr = new SQLMethodInvokeExpr(methodName, hash_lower);
SQLExpr arg0 = this.expr();
// Fix for using.
Object exprUsing = arg0.getAttributes().get("USING");
if (exprUsing instanceof String) {
String charset = (String) exprUsing;
methodInvokeExpr.setUsing(new SQLIdentifierExpr(charset));
arg0.getAttributes().remove("USING");
}
methodInvokeExpr.addArgument(arg0);
if (lexer.token == Token.COMMA) {
lexer.nextToken();
SQLDataType dataType = this.parseDataType();
SQLDataTypeRefExpr dataTypeRefExpr = new SQLDataTypeRefExpr(dataType);
methodInvokeExpr.addArgument(dataTypeRefExpr);
}
if (lexer.token == Token.USING || lexer.identifierEquals(FnvHash.Constants.USING)) {
lexer.nextToken();
SQLExpr using;
if (lexer.token == Token.STAR) {
lexer.nextToken();
using = new SQLAllColumnExpr();
} else if (lexer.token == Token.BINARY) {
using = new SQLIdentifierExpr(lexer.stringVal());
lexer.nextToken();
} else {
using = this.primary();
}
methodInvokeExpr.setUsing(using);
}
accept(Token.RPAREN);
return primaryRest(methodInvokeExpr);
}
}
if (distinct) {
aggMethodName = methodName;
} else {
aggMethodName = getAggreateFunction(hash_lower);
}
} else if (expr instanceof SQLPropertyExpr) {
methodName = ((SQLPropertyExpr) expr).getSimpleName();
aggMethodName = SQLUtils.normalize(methodName);
hash_lower = FnvHash.fnv1a_64_lower(aggMethodName);
aggMethodName = getAggreateFunction(hash_lower);
owner = ((SQLPropertyExpr) expr).getOwner();
} else if (expr instanceof SQLDefaultExpr) {
methodName = "DEFAULT";
} else if (expr instanceof SQLCharExpr) {
methodName = ((SQLCharExpr) expr).getText();
if (isAggreateFunction(methodName)) {
aggMethodName = methodName;
}
}
if (aggMethodName != null) {
SQLAggregateExpr aggregateExpr = parseAggregateExpr(methodName);
if (distinct) {
aggregateExpr.setOption(SQLAggregateOption.DISTINCT);
}
return aggregateExpr;
}
methodInvokeExpr = new SQLMethodInvokeExpr(methodName, hash_lower);
if (owner != null) {
methodInvokeExpr.setOwner(owner);
}
if (trimOption != null) {
methodInvokeExpr.setTrimOption(trimOption);
}
Token token = lexer.token;
if (token != Token.RPAREN && token != Token.FROM) {
exprList(methodInvokeExpr.getArguments(), methodInvokeExpr);
}
if (hash_lower == FnvHash.Constants.EXIST
&& methodInvokeExpr.getArguments().size() == 1
&& methodInvokeExpr.getArguments().get(0) instanceof SQLQueryExpr) {
throw new ParserException("exists syntax error.");
}
if (lexer.token == Token.FROM) {
lexer.nextToken();
SQLExpr from = this.expr();
methodInvokeExpr.setFrom(from);
if (lexer.token == Token.FOR) {
lexer.nextToken();
SQLExpr forExpr = expr();
methodInvokeExpr.setFor(forExpr);
}
}
if (lexer.token == Token.USING || lexer.identifierEquals(FnvHash.Constants.USING)) {
lexer.nextToken();
SQLExpr using;
if (lexer.token == Token.STAR) {
lexer.nextToken();
using = new SQLAllColumnExpr();
} else if (lexer.token == Token.BINARY) {
using = new SQLIdentifierExpr(lexer.stringVal());
lexer.nextToken();
} else {
using = this.primary();
}
methodInvokeExpr.setUsing(using);
}
// mysql
if (hash_lower == FnvHash.Constants.WEIGHT_STRING) {
if (lexer.token == Token.AS) {
lexer.nextToken();
SQLDataType as = this.parseDataType();
methodInvokeExpr.putAttribute("as", as);
}
if (lexer.identifierEquals(FnvHash.Constants.LEVEL)) {
lexer.nextToken();
List<SQLSelectOrderByItem> levels = new ArrayList<SQLSelectOrderByItem>();
for (;;) {
SQLSelectOrderByItem level = this.parseSelectOrderByItem();
levels.add(level);
if (lexer.token == Token.COMMA) {
lexer.nextToken();
continue;
}
break;
}
methodInvokeExpr.putAttribute("levels", levels);
}
if (lexer.identifierEquals(FnvHash.Constants.REVERSE)) {
lexer.nextToken();
methodInvokeExpr.putAttribute("reverse", true);
}
}
SQLAggregateExpr aggregateExpr = null;
if (lexer.token == Token.ORDER) {
lexer.nextToken();
accept(Token.BY);
aggregateExpr = new SQLAggregateExpr(methodName);
aggregateExpr.getArguments().addAll(methodInvokeExpr.getArguments());
SQLOrderBy orderBy = new SQLOrderBy();
this.orderBy(orderBy.getItems(), orderBy);
aggregateExpr.setWithinGroup(orderBy);
}
accept(Token.RPAREN);
if (lexer.identifierEquals(FnvHash.Constants.FILTER)) {
if (aggregateExpr == null) {
Lexer.SavePoint mark = lexer.mark();
lexer.nextToken();
Token nextToken = lexer.token;
lexer.reset(mark);
if (nextToken == Token.LPAREN) {
aggregateExpr = new SQLAggregateExpr(methodName);
aggregateExpr.getArguments().addAll(methodInvokeExpr.getArguments());
filter(aggregateExpr);
}
} else {
filter(aggregateExpr);
}
}
if (lexer.token == Token.OVER) {
if (aggregateExpr == null) {
aggregateExpr = new SQLAggregateExpr(methodName);
aggregateExpr.getArguments().addAll(methodInvokeExpr.getArguments());
}
over(aggregateExpr);
}
if (aggregateExpr != null) {
return primaryRest(aggregateExpr);
}
if (lexer.token == Token.LPAREN) {
return methodInvokeExpr;
}
return primaryRest(methodInvokeExpr);
//throw new ParserException("not support token:" + lexer.token + ", " + lexer.info());
}
protected SQLExpr dotRest(SQLExpr expr) {
if (lexer.token == Token.STAR) {
lexer.nextToken();
expr = new SQLPropertyExpr(expr, "*");
} else {
String name;
long hash_lower = 0L;
if (lexer.token == Token.IDENTIFIER) {
name = lexer.stringVal();
hash_lower = lexer.hash_lower;
lexer.nextToken();
} else if (lexer.token == Token.LITERAL_CHARS
|| lexer.token == Token.LITERAL_ALIAS) {
name = lexer.stringVal();
lexer.nextToken();
} else if (lexer.getKeywods().containsValue(lexer.token)) {
name = lexer.stringVal();
lexer.nextToken();
} else {
throw new ParserException("error : " + lexer.info());
}
if (lexer.token == Token.LPAREN) {
boolean aggregate = hash_lower == FnvHash.Constants.WM_CONCAT
&& expr instanceof SQLIdentifierExpr
&& ((SQLIdentifierExpr) expr).nameHashCode64() == FnvHash.Constants.WMSYS;
expr = methodRest(expr, name, aggregate);
} else {
expr = new SQLPropertyExpr(expr, name, hash_lower);
}
}
expr = primaryRest(expr);
return expr;
}
private SQLExpr methodRest(SQLExpr expr, String name, boolean aggregate) {
lexer.nextToken();
if (lexer.token == Token.DISTINCT) {
lexer.nextToken();
String aggreateMethodName = expr.toString() + "." + name;
SQLAggregateExpr aggregateExpr = new SQLAggregateExpr(aggreateMethodName, SQLAggregateOption.DISTINCT);
if (lexer.token == Token.RPAREN) {
lexer.nextToken();
} else {
if (lexer.token == Token.PLUS) {
aggregateExpr.getArguments().add(new SQLIdentifierExpr("+"));
lexer.nextToken();
} else {
exprList(aggregateExpr.getArguments(), aggregateExpr);
}
accept(Token.RPAREN);
}
expr = aggregateExpr;
} else if (aggregate) {
SQLAggregateExpr methodInvokeExpr = new SQLAggregateExpr(name);
methodInvokeExpr.setMethodName(expr.toString() + "." + name);
if (lexer.token == Token.RPAREN) {
lexer.nextToken();
} else {
if (lexer.token == Token.PLUS) {
methodInvokeExpr.addArgument(new SQLIdentifierExpr("+"));
lexer.nextToken();
} else {
exprList(methodInvokeExpr.getArguments(), methodInvokeExpr);
}
accept(Token.RPAREN);
}
if (lexer.token == Token.OVER) {
over(methodInvokeExpr);
}
expr = methodInvokeExpr;
} else {
SQLMethodInvokeExpr methodInvokeExpr = new SQLMethodInvokeExpr(name);
methodInvokeExpr.setOwner(expr);
if (lexer.token == Token.RPAREN) {
lexer.nextToken();
} else {
if (lexer.token == Token.PLUS) {
methodInvokeExpr.addParameter(new SQLIdentifierExpr("+"));
lexer.nextToken();
} else {
exprList(methodInvokeExpr.getParameters(), methodInvokeExpr);
}
accept(Token.RPAREN);
}
expr = methodInvokeExpr;
}
return expr;
}
public final SQLExpr groupComparisionRest(SQLExpr expr) {
return expr;
}
public final void names(Collection<SQLName> exprCol) {
names(exprCol, null);
}
public final void names(Collection<SQLName> exprCol, SQLObject parent) {
if (lexer.token == Token.RBRACE) {
return;
}
if (lexer.token == Token.EOF) {
return;
}
SQLName name = name();
name.setParent(parent);
exprCol.add(name);
while (lexer.token == Token.COMMA) {
lexer.nextToken();
name = name();
name.setParent(parent);
exprCol.add(name);
}
}
@Deprecated
public final void exprList(Collection<SQLExpr> exprCol) {
exprList(exprCol, null);
}
public final void exprList(Collection<SQLExpr> exprCol, SQLObject parent) {
if (lexer.token == Token.RPAREN || lexer.token == Token.RBRACKET) {
return;
}
if (lexer.token == Token.EOF) {
return;
}
SQLExpr expr = expr();
expr.setParent(parent);
exprCol.add(expr);
while (lexer.token == Token.COMMA) {
lexer.nextToken();
expr = expr();
expr.setParent(parent);
exprCol.add(expr);
}
}
public SQLName name() {
String identName;
long hash = 0;
if (lexer.token == Token.LITERAL_ALIAS) {
identName = lexer.stringVal();
lexer.nextToken();
} else if (lexer.token == Token.IDENTIFIER) {
identName = lexer.stringVal();
char c0 = identName.charAt(0);
if (c0 != '[') {
hash = lexer.hash_lower();
}
lexer.nextToken();
} else if (lexer.token == Token.LITERAL_CHARS) {
identName = '\'' + lexer.stringVal() + '\'';
lexer.nextToken();
} else if (lexer.token == Token.VARIANT) {
identName = lexer.stringVal();
lexer.nextToken();
} else {
switch (lexer.token) {
case MODEL:
case PCTFREE:
case INITRANS:
case MAXTRANS:
case SEGMENT:
case CREATION:
case IMMEDIATE:
case DEFERRED:
case STORAGE:
case NEXT:
case MINEXTENTS:
case MAXEXTENTS:
case MAXSIZE:
case PCTINCREASE:
case FLASH_CACHE:
case CELL_FLASH_CACHE:
case NONE:
case LOB:
case STORE:
case ROW:
case CHUNK:
case CACHE:
case NOCACHE:
case LOGGING:
case NOCOMPRESS:
case KEEP_DUPLICATES:
case EXCEPTIONS:
case PURGE:
case INITIALLY:
case END:
case COMMENT:
case ENABLE:
case DISABLE:
case SEQUENCE:
case USER:
case ANALYZE:
case OPTIMIZE:
case GRANT:
case REVOKE:
// binary有很多含义,lexer识别了这个token,实际上应该当做普通IDENTIFIER
case BINARY:
case OVER:
case ORDER:
case DO:
case JOIN:
case TYPE:
case FUNCTION:
case KEY:
case SCHEMA:
case INTERVAL:
case EXPLAIN:
case PARTITION:
case SET:
case DEFAULT:
identName = lexer.stringVal();
lexer.nextToken();
break;
default:
throw new ParserException("error " + lexer.info());
}
}
SQLName name = new SQLIdentifierExpr(identName, hash);
name = nameRest(name);
return name;
}
public SQLName nameRest(SQLName name) {
if (lexer.token == Token.DOT) {
lexer.nextToken();
if (lexer.token == Token.KEY) {
name = new SQLPropertyExpr(name, "KEY");
lexer.nextToken();
return name;
}
if (lexer.token != Token.LITERAL_ALIAS && lexer.token != Token.IDENTIFIER
&& (!lexer.getKeywods().containsValue(lexer.token))) {
throw new ParserException("error, " + lexer.info());
}
if (lexer.token == Token.LITERAL_ALIAS) {
name = new SQLPropertyExpr(name, lexer.stringVal());
} else {
name = new SQLPropertyExpr(name, lexer.stringVal());
}
lexer.nextToken();
name = nameRest(name);
}
return name;
}
public boolean isAggreateFunction(String word) {
long hash_lower = FnvHash.fnv1a_64_lower(word);
return isAggreateFunction(hash_lower);
}
protected boolean isAggreateFunction(long hash_lower) {
return Arrays.binarySearch(aggregateFunctionHashCodes, hash_lower) >= 0;
}
protected String getAggreateFunction(long hash_lower) {
int index = Arrays.binarySearch(aggregateFunctionHashCodes, hash_lower);
if (index < 0) {
return null;
}
return aggregateFunctions[index];
}
protected SQLAggregateExpr parseAggregateExpr(String methodName) {
SQLAggregateExpr aggregateExpr;
if (lexer.token == Token.ALL) {
aggregateExpr = new SQLAggregateExpr(methodName, SQLAggregateOption.ALL);
lexer.nextToken();
} else if (lexer.token == Token.DISTINCT) {
aggregateExpr = new SQLAggregateExpr(methodName, SQLAggregateOption.DISTINCT);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.DEDUPLICATION)) { // just for nut
aggregateExpr = new SQLAggregateExpr(methodName, SQLAggregateOption.DEDUPLICATION);
lexer.nextToken();
} else {
aggregateExpr = new SQLAggregateExpr(methodName);
}
exprList(aggregateExpr.getArguments(), aggregateExpr);
if (lexer.token != Token.RPAREN) {
parseAggregateExprRest(aggregateExpr);
}
accept(Token.RPAREN);
if (lexer.identifierEquals(FnvHash.Constants.FILTER)) {
filter(aggregateExpr);
}
if (lexer.token == Token.OVER) {
over(aggregateExpr);
}
return aggregateExpr;
}
protected void filter(SQLAggregateExpr aggregateExpr) {
}
protected void over(SQLAggregateExpr aggregateExpr) {
lexer.nextToken();
if (lexer.token != Token.LPAREN) {
SQLName overRef = this.name();
aggregateExpr.setOverRef(overRef);
return;
}
SQLOver over = new SQLOver();
over(over);
aggregateExpr.setOver(over);
}
protected void over(SQLOver over) {
lexer.nextToken();
if (lexer.token == Token.PARTITION || lexer.identifierEquals("PARTITION")) {
lexer.nextToken();
accept(Token.BY);
if (lexer.token == (Token.LPAREN)) {
lexer.nextToken();
exprList(over.getPartitionBy(), over);
accept(Token.RPAREN);
} else {
exprList(over.getPartitionBy(), over);
}
}
over.setOrderBy(parseOrderBy());
if (lexer.token == Token.OF) {
lexer.nextToken();
SQLName of = this.name();
over.setOf(of);
}
SQLOver.WindowingType windowingType = null;
if (lexer.identifierEquals(FnvHash.Constants.ROWS) || lexer.token == Token.ROWS) {
windowingType = SQLOver.WindowingType.ROWS;
} else if (lexer.identifierEquals(FnvHash.Constants.RANGE)) {
windowingType = SQLOver.WindowingType.RANGE;
}
if (windowingType != null) {
over.setWindowingType(windowingType);
lexer.nextToken();
if (lexer.token == Token.BETWEEN) {
lexer.nextToken();
SQLExpr rowsBegin = this.primary();
over.setWindowingBetweenBegin(rowsBegin);
if (lexer.identifierEquals(FnvHash.Constants.PRECEDING)) {
over.setWindowingBetweenBeginPreceding(true);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.FOLLOWING)) {
over.setWindowingBetweenBeginFollowing(true);
lexer.nextToken();
}
accept(Token.AND);
SQLExpr betweenEnd;
if (lexer.identifierEquals(FnvHash.Constants.CURRENT) || lexer.token == Token.CURRENT) {
lexer.nextToken();
if (lexer.identifierEquals(FnvHash.Constants.ROW)) {
lexer.nextToken();
} else {
accept(Token.ROW);
}
betweenEnd = new SQLIdentifierExpr("CURRENT ROW");
} else {
betweenEnd = this.primary();
}
over.setWindowingBetweenEnd(betweenEnd);
if (lexer.identifierEquals(FnvHash.Constants.PRECEDING)) {
over.setWindowingBetweenEndPreceding(true);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.FOLLOWING)) {
over.setWindowingBetweenEndFollowing(true);
lexer.nextToken();
}
} else {
if (lexer.identifierEquals(FnvHash.Constants.CURRENT)) {
lexer.nextToken();
if (lexer.identifierEquals(FnvHash.Constants.ROW)) {
lexer.nextToken();
} else {
accept(Token.ROW);
}
over.setWindowing(new SQLIdentifierExpr("CURRENT ROW"));
} else if (lexer.identifierEquals(FnvHash.Constants.UNBOUNDED)) {
lexer.nextToken();
over.setWindowing(new SQLIdentifierExpr("UNBOUNDED"));
if (lexer.identifierEquals(FnvHash.Constants.PRECEDING)) {
over.setWindowingPreceding(true);
lexer.nextToken();
} else if (lexer.identifierEquals("FOLLOWING")) {
over.setWindowingFollowing(true);
lexer.nextToken();
}
} else {
SQLIntegerExpr rowsExpr = (SQLIntegerExpr) this.primary();
over.setWindowing(rowsExpr);
if (lexer.identifierEquals(FnvHash.Constants.PRECEDING)) {
over.setWindowingPreceding(true);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.FOLLOWING)) {
over.setWindowingFollowing(true);
lexer.nextToken();
}
}
}
}
accept(Token.RPAREN);
}
protected SQLAggregateExpr parseAggregateExprRest(SQLAggregateExpr aggregateExpr) {
return aggregateExpr;
}
public SQLOrderBy parseOrderBy() {
if (lexer.token == Token.ORDER) {
SQLOrderBy orderBy = new SQLOrderBy();
lexer.nextToken();
if (lexer.identifierEquals(FnvHash.Constants.SIBLINGS)) {
lexer.nextToken();
orderBy.setSibings(true);
}
accept(Token.BY);
orderBy(orderBy.getItems(), orderBy);
return orderBy;
}
return null;
}
public void orderBy(List<SQLSelectOrderByItem> items, SQLObject parent) {
SQLSelectOrderByItem item = parseSelectOrderByItem();
item.setParent(parent);
items.add(item);
while (lexer.token == Token.COMMA) {
lexer.nextToken();
item = parseSelectOrderByItem();
item.setParent(parent);
items.add(item);
}
}
public SQLSelectOrderByItem parseSelectOrderByItem() {
SQLSelectOrderByItem item = new SQLSelectOrderByItem();
item.setExpr(expr());
if (lexer.token == Token.ASC) {
lexer.nextToken();
item.setType(SQLOrderingSpecification.ASC);
} else if (lexer.token == Token.DESC) {
lexer.nextToken();
item.setType(SQLOrderingSpecification.DESC);
}
if (lexer.identifierEquals(FnvHash.Constants.NULLS)) {
lexer.nextToken();
if (lexer.identifierEquals(FnvHash.Constants.FIRST)) {
lexer.nextToken();
item.setNullsOrderType(SQLSelectOrderByItem.NullsOrderType.NullsFirst);
} else if (lexer.identifierEquals(FnvHash.Constants.LAST)) {
lexer.nextToken();
item.setNullsOrderType(SQLSelectOrderByItem.NullsOrderType.NullsLast);
} else {
throw new ParserException("TODO " + lexer.info());
}
}
return item;
}
public SQLUpdateSetItem parseUpdateSetItem() {
SQLUpdateSetItem item = new SQLUpdateSetItem();
if (lexer.token == (Token.LPAREN)) {
lexer.nextToken();
SQLListExpr list = new SQLListExpr();
this.exprList(list.getItems(), list);
accept(Token.RPAREN);
item.setColumn(list);
} else {
String identName;
long hash;
Token token = lexer.token();
if (token == Token.IDENTIFIER) {
identName = lexer.stringVal();
hash = lexer.hash_lower();
} else if (token == Token.LITERAL_CHARS) {
identName = '\'' + lexer.stringVal() + '\'';
hash = 0;
} else {
identName = lexer.stringVal();
hash = 0;
}
lexer.nextTokenEq();
SQLExpr expr = new SQLIdentifierExpr(identName, hash);
while (lexer.token() == Token.DOT) {
lexer.nextToken();
String propertyName = lexer.stringVal();
lexer.nextTokenEq();
expr = new SQLPropertyExpr(expr, propertyName);
}
item.setColumn(expr);
}
if (lexer.token == Token.COLONEQ) {
lexer.nextTokenValue();
} else if (lexer.token == Token.EQ) {
lexer.nextTokenValue();
} else {
throw new ParserException("syntax error, expect EQ, actual " + lexer.token + " "
+ lexer.info());
}
item.setValue(this.expr());
return item;
}
public final SQLExpr bitAnd() {
SQLExpr expr = shift();
return bitAndRest(expr);
}
public final SQLExpr bitAndRest(SQLExpr expr) {
while (lexer.token == Token.AMP) {
lexer.nextToken();
SQLExpr rightExp = shift();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.BitwiseAnd, rightExp, getDbType());
}
return expr;
}
public final SQLExpr bitOr() {
SQLExpr expr = bitAnd();
return bitOrRest(expr);
}
public final SQLExpr bitOrRest(SQLExpr expr) {
while (lexer.token == Token.BAR) {
lexer.nextToken();
SQLBinaryOperator op = SQLBinaryOperator.BitwiseOr;
if (lexer.token == Token.BAR) {
lexer.nextToken();
op = SQLBinaryOperator.Concat;
}
SQLExpr rightExp = bitAnd();
expr = new SQLBinaryOpExpr(expr, op, rightExp, getDbType());
expr = bitAndRest(expr);
}
return expr;
}
public final SQLExpr inRest(SQLExpr expr) {
if (lexer.token == Token.IN) {
lexer.nextTokenLParen();
SQLInListExpr inListExpr = new SQLInListExpr(expr);
List<SQLExpr> targetList = inListExpr.getTargetList();
if (lexer.token == Token.LPAREN) {
lexer.nextTokenValue();
if (lexer.token == Token.WITH) {
SQLSelect select = this.createSelectParser().select();
SQLInSubQueryExpr queryExpr = new SQLInSubQueryExpr(select);
queryExpr.setExpr(expr);
accept(Token.RPAREN);
return queryExpr;
}
for (;;) {
SQLExpr item;
if (lexer.token == Token.LITERAL_INT) {
item = new SQLIntegerExpr(lexer.integerValue());
lexer.nextToken();
if (lexer.token != Token.COMMA && lexer.token != Token.RPAREN) {
item = this.primaryRest(item);
item = this.exprRest(item);
}
} else {
item = this.expr();
}
item.setParent(inListExpr);
targetList.add(item);
if (lexer.token == Token.COMMA) {
lexer.nextTokenValue();
continue;
}
break;
}
accept(Token.RPAREN);
} else {
SQLExpr itemExpr = primary();
itemExpr.setParent(inListExpr);
targetList.add(itemExpr);
}
expr = inListExpr;
if (targetList.size() == 1) {
SQLExpr targetExpr = targetList.get(0);
if (targetExpr instanceof SQLQueryExpr) {
SQLInSubQueryExpr inSubQueryExpr = new SQLInSubQueryExpr();
inSubQueryExpr.setExpr(inListExpr.getExpr());
inSubQueryExpr.setSubQuery(((SQLQueryExpr) targetExpr).getSubQuery());
expr = inSubQueryExpr;
}
}
} else if (lexer.token == Token.CONTAINS) {
lexer.nextTokenLParen();
SQLContainsExpr containsExpr = new SQLContainsExpr(expr);
List<SQLExpr> targetList = containsExpr.getTargetList();
if (lexer.token == Token.LPAREN) {
lexer.nextTokenValue();
if (lexer.token == Token.WITH) {
SQLSelect select = this.createSelectParser().select();
SQLInSubQueryExpr queryExpr = new SQLInSubQueryExpr(select);
queryExpr.setExpr(expr);
accept(Token.RPAREN);
return queryExpr;
}
for (;;) {
SQLExpr item;
if (lexer.token == Token.LITERAL_INT) {
item = new SQLIntegerExpr(lexer.integerValue());
lexer.nextToken();
if (lexer.token != Token.COMMA && lexer.token != Token.RPAREN) {
item = this.primaryRest(item);
item = this.exprRest(item);
}
} else {
item = this.expr();
}
item.setParent(containsExpr);
targetList.add(item);
if (lexer.token == Token.COMMA) {
lexer.nextTokenValue();
continue;
}
break;
}
accept(Token.RPAREN);
} else {
SQLExpr itemExpr = primary();
itemExpr.setParent(containsExpr);
targetList.add(itemExpr);
}
expr = containsExpr;
}
return expr;
}
public final SQLExpr additive() {
SQLExpr expr = multiplicative();
if (lexer.token == Token.PLUS
|| lexer.token == Token.BARBAR
|| lexer.token == Token.CONCAT
|| lexer.token == Token.SUB) {
expr = additiveRest(expr);
}
return expr;
}
public SQLExpr additiveRest(SQLExpr expr) {
Token token = lexer.token;
if (token == Token.PLUS) {
lexer.nextToken();
SQLExpr rightExp = multiplicative();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Add, rightExp, dbType);
expr = additiveRest(expr);
} else if ((token == Token.BARBAR || token == Token.CONCAT)
&& (isEnabled(SQLParserFeature.PipesAsConcat) || !JdbcConstants.MYSQL.equals(dbType))) {
lexer.nextToken();
SQLExpr rightExp = multiplicative();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Concat, rightExp, dbType);
expr = additiveRest(expr);
} else if (token == Token.SUB) {
lexer.nextToken();
SQLExpr rightExp = multiplicative();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Subtract, rightExp, dbType);
expr = additiveRest(expr);
}
return expr;
}
public final SQLExpr shift() {
SQLExpr expr = additive();
return shiftRest(expr);
}
public SQLExpr shiftRest(SQLExpr expr) {
if (lexer.token == Token.LTLT) {
lexer.nextToken();
SQLExpr rightExp = additive();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.LeftShift, rightExp, dbType);
expr = shiftRest(expr);
} else if (lexer.token == Token.GTGT) {
lexer.nextToken();
SQLExpr rightExp = additive();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.RightShift, rightExp, dbType);
expr = shiftRest(expr);
}
return expr;
}
public SQLExpr and() {
SQLExpr expr = relational();
if (lexer.token == Token.AND || lexer.token == Token.AMPAMP) {
expr = andRest(expr);
}
return expr;
}
public SQLExpr andRest(SQLExpr expr) {
for (;;) {
Token token = lexer.token;
if (token == Token.AND) {
if (lexer.isKeepComments() && lexer.hasComment()) {
expr.addAfterComment(lexer.readAndResetComments());
}
lexer.nextToken();
SQLExpr rightExp = relational();
if (lexer.token == Token.AND
&& lexer.isEnabled(SQLParserFeature.EnableSQLBinaryOpExprGroup)) {
SQLBinaryOpExprGroup group = new SQLBinaryOpExprGroup(SQLBinaryOperator.BooleanAnd, dbType);
group.add(expr);
group.add(rightExp);
if (lexer.isKeepComments() && lexer.hasComment()) {
rightExp.addAfterComment(lexer.readAndResetComments());
}
for (;;) {
lexer.nextToken();
SQLExpr more = relational();
group.add(more);
if (lexer.token == Token.AND) {
if (lexer.isKeepComments() && lexer.hasComment()) {
more.addAfterComment(lexer.readAndResetComments());
}
continue;
}
break;
}
expr = group;
} else {
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.BooleanAnd, rightExp, dbType);
}
} else if (token == Token.AMPAMP) {
if (lexer.isKeepComments() && lexer.hasComment()) {
expr.addAfterComment(lexer.readAndResetComments());
}
lexer.nextToken();
SQLExpr rightExp = relational();
SQLBinaryOperator operator = JdbcConstants.POSTGRESQL.equals(dbType)
? SQLBinaryOperator.PG_And
: SQLBinaryOperator.BooleanAnd;
expr = new SQLBinaryOpExpr(expr, operator, rightExp, dbType);
} else {
break;
}
}
return expr;
}
public SQLExpr xor() {
SQLExpr expr = and();
if (lexer.token == Token.XOR) {
expr = xorRest(expr);
}
return expr;
}
public SQLExpr xorRest(SQLExpr expr) {
for (;;) {
if (lexer.token == Token.XOR) {
lexer.nextToken();
SQLExpr rightExp = and();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.BooleanXor, rightExp, dbType);
} else {
break;
}
}
return expr;
}
public SQLExpr or() {
SQLExpr expr = xor();
if (lexer.token == Token.OR || lexer.token == Token.BARBAR) {
expr = orRest(expr);
}
return expr;
}
public SQLExpr orRest(SQLExpr expr) {
for (;;) {
if (lexer.token == Token.OR) {
lexer.nextToken();
SQLExpr rightExp = xor();
if (lexer.token == Token.OR
&& lexer.isEnabled(SQLParserFeature.EnableSQLBinaryOpExprGroup)) {
SQLBinaryOpExprGroup group = new SQLBinaryOpExprGroup(SQLBinaryOperator.BooleanOr, dbType);
group.add(expr);
group.add(rightExp);
if (lexer.isKeepComments() && lexer.hasComment()) {
rightExp.addAfterComment(lexer.readAndResetComments());
}
for (;;) {
lexer.nextToken();
SQLExpr more = xor();
group.add(more);
if (lexer.token == Token.OR) {
if (lexer.isKeepComments() && lexer.hasComment()) {
more.addAfterComment(lexer.readAndResetComments());
}
continue;
}
break;
}
expr = group;
} else {
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.BooleanOr, rightExp, dbType);
}
} else if (lexer.token == Token.BARBAR) {
lexer.nextToken();
SQLExpr rightExp = xor();
SQLBinaryOperator op = JdbcConstants.MYSQL.equals(dbType) && !isEnabled(SQLParserFeature.PipesAsConcat)
? SQLBinaryOperator.BooleanOr
: SQLBinaryOperator.Concat;
expr = new SQLBinaryOpExpr(expr, op, rightExp, dbType);
} else {
break;
}
}
return expr;
}
public SQLExpr relational() {
SQLExpr expr = bitOr();
return relationalRest(expr);
}
public SQLExpr relationalRest(SQLExpr expr) {
SQLExpr rightExp;
Token token = lexer.token;
switch (token) {
case EQ:{
lexer.nextToken();
try {
rightExp = bitOr();
} catch (EOFParserException e) {
throw new ParserException("EOF, " + expr + "=", e);
}
if (lexer.token == Token.COLONEQ) {
lexer.nextToken();
SQLExpr colonExpr = expr();
rightExp = new SQLBinaryOpExpr(rightExp, SQLBinaryOperator.Assignment, colonExpr, dbType);
}
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Equality, rightExp, dbType);
}
break;
case IS: {
lexer.nextTokenNotOrNull();
SQLBinaryOperator op;
if (lexer.token == Token.NOT) {
op = SQLBinaryOperator.IsNot;
lexer.nextTokenNotOrNull();
} else {
op = SQLBinaryOperator.Is;
}
rightExp = primary();
expr = new SQLBinaryOpExpr(expr, op, rightExp, dbType);
}
break;
case EQGT: {
lexer.nextToken();
rightExp = expr();
String argumentName = ((SQLIdentifierExpr) expr).getName();
expr = new OracleArgumentExpr(argumentName, rightExp);
}
break;
case BANGEQ:
case CARETEQ: {
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.NotEqual, rightExp, dbType);
}
break;
case COLONEQ:{
lexer.nextToken();
rightExp = expr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Assignment, rightExp, dbType);
}
break;
case LT:{
SQLBinaryOperator op = SQLBinaryOperator.LessThan;
lexer.nextToken();
if (lexer.token == Token.EQ) {
lexer.nextToken();
op = SQLBinaryOperator.LessThanOrEqual;
}
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, op, rightExp, getDbType());
}
break;
case LTEQ: {
lexer.nextToken();
rightExp = bitOr();
// rightExp = relationalRest(rightExp);
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.LessThanOrEqual, rightExp, getDbType());
}
break;
case LTEQGT: {
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.LessThanOrEqualOrGreaterThan, rightExp, getDbType());
}
break;
case GT: {
SQLBinaryOperator op = SQLBinaryOperator.GreaterThan;
lexer.nextToken();
if (lexer.token == Token.EQ) {
lexer.nextToken();
op = SQLBinaryOperator.GreaterThanOrEqual;
}
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, op, rightExp, getDbType());
}
break;
case GTEQ:{
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.GreaterThanOrEqual, rightExp, getDbType());
}
break;
case BANGLT:{
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.NotLessThan, rightExp, getDbType());
}
break;
case BANGGT:
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.NotGreaterThan, rightExp, getDbType());
break;
case LTGT:
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.LessThanOrGreater, rightExp, getDbType());
break;
case LIKE:
lexer.nextTokenValue();
rightExp = bitOr();
if (rightExp.getClass() == SQLIdentifierExpr.class) {
String name = ((SQLIdentifierExpr) rightExp).getName();
int length = name.length();
if(length > 1 && name.charAt(0) == name.charAt(length -1 )) {
rightExp = new SQLCharExpr(name.substring(1, length - 1));
}
}
// rightExp = relationalRest(rightExp);
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Like, rightExp, getDbType());
if (lexer.token == Token.ESCAPE) {
lexer.nextToken();
rightExp = primary();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Escape, rightExp, getDbType());
}
break;
case ILIKE:
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.ILike, rightExp, getDbType());
break;
case MONKEYS_AT_AT:
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.AT_AT, rightExp, getDbType());
break;
case MONKEYS_AT_GT:
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Array_Contains, rightExp, getDbType());
break;
case LT_MONKEYS_AT:
lexer.nextToken();
rightExp = bitOr();
rightExp = relationalRest(rightExp);
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Array_ContainedBy, rightExp, getDbType());
break;
case NOT:
lexer.nextToken();
expr = notRationalRest(expr);
break;
case BETWEEN:
lexer.nextToken();
SQLExpr beginExpr = relational();
accept(Token.AND);
SQLExpr endExpr = relational();
expr = new SQLBetweenExpr(expr, beginExpr, endExpr);
break;
case IN:
case CONTAINS:
expr = inRest(expr);
break;
case EQEQ:
if (JdbcConstants.ODPS.equals(dbType)) {
lexer.nextToken();
try {
rightExp = bitOr();
} catch (EOFParserException e) {
throw new ParserException("EOF, " + expr + "=", e);
}
if (lexer.token == Token.COLONEQ) {
lexer.nextToken();
SQLExpr colonExpr = expr();
rightExp = new SQLBinaryOpExpr(rightExp, SQLBinaryOperator.Assignment, colonExpr, dbType);
}
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Equality, rightExp, dbType);
} else {
return expr;
}
break;
case TILDE:
if (JdbcConstants.POSTGRESQL.equals(lexer.dbType)) {
lexer.nextToken();
rightExp = relational();
rightExp = relationalRest(rightExp);
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.POSIX_Regular_Match, rightExp, getDbType());
} else {
return expr;
}
break;
case TILDE_STAR:
if (JdbcConstants.POSTGRESQL.equals(lexer.dbType)) {
lexer.nextToken();
rightExp = relational();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.POSIX_Regular_Match_Insensitive, rightExp, getDbType());
} else {
return expr;
}
break;
case BANG_TILDE:
if (JdbcConstants.POSTGRESQL.equals(lexer.dbType)) {
lexer.nextToken();
rightExp = relational();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.POSIX_Regular_Not_Match, rightExp, getDbType());
} else {
return expr;
}
break;
case BANG_TILDE_STAR:
if (JdbcConstants.POSTGRESQL.equals(lexer.dbType)) {
lexer.nextToken();
rightExp = relational();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.POSIX_Regular_Not_Match_POSIX_Regular_Match_Insensitive, rightExp, getDbType());
} else {
return expr;
}
break;
case TILDE_EQ:
if (JdbcConstants.POSTGRESQL.equals(lexer.dbType)) {
lexer.nextToken();
rightExp = relational();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.SAME_AS, rightExp, getDbType());
} else {
return expr;
}
break;
case RLIKE:
lexer.nextToken();
rightExp = relational();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.RLike, rightExp, getDbType());
break;
case IDENTIFIER:
long hash = lexer.hash_lower;
if (hash == FnvHash.Constants.SOUNDS) {
lexer.nextToken();
accept(Token.LIKE);
rightExp = relational();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.SoudsLike, rightExp, getDbType());
} else if (hash == FnvHash.Constants.REGEXP) {
lexer.nextToken();
rightExp = relational();
return new SQLBinaryOpExpr(expr, SQLBinaryOperator.RegExp, rightExp, JdbcConstants.MYSQL);
} else if (hash == FnvHash.Constants.SIMILAR && JdbcConstants.POSTGRESQL.equals(lexer.dbType)) {
lexer.nextToken();
accept(Token.TO);
rightExp = relational();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.SIMILAR_TO, rightExp, getDbType());
} else {
return expr;
}
break;
default:
break;
}
switch (lexer.token) {
case BETWEEN:
case IS:
case EQ:
case IN:
case CONTAINS:
case BANG_TILDE_STAR:
case TILDE_EQ:
case LT:
case LTEQ:
case LTEQGT:
case GT:
case GTEQ:
case LTGT:
case BANGEQ:
case LIKE:
case NOT:
expr = relationalRest(expr);
break;
default:
break;
}
return expr;
}
public SQLExpr notRationalRest(SQLExpr expr) {
switch (lexer.token) {
case LIKE:
lexer.nextTokenValue();
SQLExpr rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.NotLike, rightExp, getDbType());
if (lexer.token == Token.ESCAPE) {
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.Escape, rightExp, getDbType());
}
break;
case IN:
lexer.nextToken();
SQLInListExpr inListExpr = new SQLInListExpr(expr, true);
if (lexer.token == Token.LPAREN) {
lexer.nextToken();
exprList(inListExpr.getTargetList(), inListExpr);
expr = inListExpr;
accept(Token.RPAREN);
} else {
SQLExpr valueExpr = this.primary();
valueExpr.setParent(inListExpr);
inListExpr.getTargetList().add(valueExpr);
expr = inListExpr;
}
if (inListExpr.getTargetList().size() == 1) {
SQLExpr targetExpr = inListExpr.getTargetList().get(0);
if (targetExpr instanceof SQLQueryExpr) {
SQLInSubQueryExpr inSubQueryExpr = new SQLInSubQueryExpr();
inSubQueryExpr.setNot(true);
inSubQueryExpr.setExpr(inListExpr.getExpr());
inSubQueryExpr.setSubQuery(((SQLQueryExpr) targetExpr).getSubQuery());
expr = inSubQueryExpr;
}
}
break;
case CONTAINS:
lexer.nextToken();
SQLContainsExpr containsExpr = new SQLContainsExpr(expr, true);
if (lexer.token == Token.LPAREN) {
lexer.nextToken();
exprList(containsExpr.getTargetList(), containsExpr);
expr = containsExpr;
accept(Token.RPAREN);
} else {
SQLExpr valueExpr = this.primary();
valueExpr.setParent(containsExpr);
containsExpr.getTargetList().add(valueExpr);
expr = containsExpr;
}
if (containsExpr.getTargetList().size() == 1) {
SQLExpr targetExpr = containsExpr.getTargetList().get(0);
if (targetExpr instanceof SQLQueryExpr) {
SQLInSubQueryExpr inSubQueryExpr = new SQLInSubQueryExpr();
inSubQueryExpr.setNot(true);
inSubQueryExpr.setExpr(containsExpr.getExpr());
inSubQueryExpr.setSubQuery(((SQLQueryExpr) targetExpr).getSubQuery());
expr = inSubQueryExpr;
}
}
break;
case BETWEEN:
lexer.nextToken();
SQLExpr beginExpr = relational();
accept(Token.AND);
SQLExpr endExpr = relational();
expr = new SQLBetweenExpr(expr, true, beginExpr, endExpr);
break;
case ILIKE:
lexer.nextToken();
rightExp = bitOr();
return new SQLBinaryOpExpr(expr, SQLBinaryOperator.NotILike, rightExp, getDbType());
case LPAREN:
expr = this.primary();
break;
case RLIKE:
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.NotRLike, rightExp, getDbType());
break;
case IDENTIFIER:
long hash = lexer.hash_lower;
if (hash == FnvHash.Constants.REGEXP) {
lexer.nextToken();
rightExp = bitOr();
expr = new SQLBinaryOpExpr(expr, SQLBinaryOperator.NotRegExp, rightExp, getDbType());
}
break;
default:
throw new ParserException("TODO " + lexer.info());
}
return expr;
}
public SQLDataType parseDataType() {
return parseDataType(true);
}
public SQLDataType parseDataType(boolean restrict) {
Token token = lexer.token;
if (token == Token.DEFAULT || token == Token.NOT || token == Token.NULL) {
return null;
}
SQLName typeExpr = name();
final long typeNameHashCode = typeExpr.nameHashCode64();
String typeName = typeExpr.toString();
if (typeNameHashCode == FnvHash.Constants.LONG
&& lexer.identifierEquals(FnvHash.Constants.BYTE)
&& JdbcConstants.MYSQL.equals(getDbType()) //
) {
typeName += (' ' + lexer.stringVal());
lexer.nextToken();
} else if (typeNameHashCode == FnvHash.Constants.DOUBLE
&& JdbcConstants.POSTGRESQL.equals(getDbType()) //
) {
typeName += (' ' + lexer.stringVal());
lexer.nextToken();
}
if (typeNameHashCode == FnvHash.Constants.UNSIGNED) {
if (lexer.token == Token.IDENTIFIER) {
typeName += (' ' + lexer.stringVal());
lexer.nextToken();
}
}
if (isCharType(typeName)) {
SQLCharacterDataType charType = new SQLCharacterDataType(typeName);
if (lexer.token == Token.LPAREN) {
lexer.nextToken();
SQLExpr arg = this.expr();
arg.setParent(charType);
charType.addArgument(arg);
accept(Token.RPAREN);
}
charType = (SQLCharacterDataType) parseCharTypeRest(charType);
if (lexer.token == Token.HINT) {
List<SQLCommentHint> hints = this.parseHints();
charType.setHints(hints);
}
return charType;
}
if ("character".equalsIgnoreCase(typeName) && "varying".equalsIgnoreCase(lexer.stringVal())) {
typeName += ' ' + lexer.stringVal();
lexer.nextToken();
}
SQLDataType dataType = new SQLDataTypeImpl(typeName);
dataType.setDbType(dbType);
return parseDataTypeRest(dataType);
}
protected SQLDataType parseDataTypeRest(SQLDataType dataType) {
if (lexer.token == Token.LPAREN) {
lexer.nextToken();
exprList(dataType.getArguments(), dataType);
accept(Token.RPAREN);
}
if (lexer.identifierEquals(FnvHash.Constants.PRECISION)
&& dataType.nameHashCode64() == FnvHash.Constants.DOUBLE) {
lexer.nextToken();
dataType.setName("DOUBLE PRECISION");
}
if (FnvHash.Constants.TIMESTAMP == dataType.nameHashCode64()) {
if (lexer.identifierEquals(FnvHash.Constants.WITHOUT)) {
lexer.nextToken();
acceptIdentifier("TIME");
acceptIdentifier("ZONE");
dataType.setWithTimeZone(false);
} else if (lexer.token == Token.WITH) {
lexer.nextToken();
acceptIdentifier("TIME");
acceptIdentifier("ZONE");
dataType.setWithTimeZone(true);
}
}
return dataType;
}
protected boolean isCharType(String dataTypeName) {
long hash = FnvHash.hashCode64(dataTypeName);
return isCharType(hash);
}
protected boolean isCharType(long hash) {
return hash == FnvHash.Constants.CHAR
|| hash == FnvHash.Constants.VARCHAR
|| hash == FnvHash.Constants.NCHAR
|| hash == FnvHash.Constants.NVARCHAR
|| hash == FnvHash.Constants.TINYTEXT
|| hash == FnvHash.Constants.TEXT
|| hash == FnvHash.Constants.MEDIUMTEXT
|| hash == FnvHash.Constants.LONGTEXT
;
}
protected SQLDataType parseCharTypeRest(SQLCharacterDataType charType) {
if (lexer.token == Token.BINARY) {
charType.setHasBinary(true);
lexer.nextToken();
}
if (lexer.identifierEquals(FnvHash.Constants.CHARACTER)) {
lexer.nextToken();
accept(Token.SET);
if (lexer.token != Token.IDENTIFIER
&& lexer.token != Token.LITERAL_CHARS
&& lexer.token != Token.BINARY) {
throw new ParserException(lexer.info());
}
charType.setCharSetName(lexer.stringVal());
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.CHARSET)) {
lexer.nextToken();
if (lexer.token != Token.IDENTIFIER
&& lexer.token != Token.LITERAL_CHARS
&& lexer.token != Token.BINARY) {
throw new ParserException(lexer.info());
}
charType.setCharSetName(lexer.stringVal());
lexer.nextToken();
}
if (lexer.token == Token.BINARY) {
charType.setHasBinary(true);
lexer.nextToken();
}
if (lexer.identifierEquals(FnvHash.Constants.COLLATE)) {
lexer.nextToken();
if (lexer.token == Token.LITERAL_ALIAS) {
charType.setCollate(lexer.stringVal());
} else if (lexer.token == Token.IDENTIFIER) {
charType.setCollate(lexer.stringVal());
} else {
throw new ParserException();
}
lexer.nextToken();
}
return charType;
}
public void accept(Token token) {
if (lexer.token == token) {
lexer.nextToken();
} else {
throw new ParserException("syntax error, expect " + token + ", actual " + lexer.token + " "
+ lexer.info());
}
}
public SQLColumnDefinition parseColumn() {
SQLColumnDefinition column = createColumnDefinition();
column.setName(name());
final Token token = lexer.token;
if (token != Token.SET //
&& token != Token.DROP
&& token != Token.PRIMARY
&& token != Token.RPAREN) {
column.setDataType(parseDataType());
}
return parseColumnRest(column);
}
public SQLColumnDefinition createColumnDefinition() {
SQLColumnDefinition column = new SQLColumnDefinition();
column.setDbType(dbType);
return column;
}
public SQLColumnDefinition parseColumnRest(SQLColumnDefinition column) {
if (lexer.token == Token.DEFAULT) {
lexer.nextToken();
column.setDefaultExpr(bitOr());
return parseColumnRest(column);
}
if (lexer.token == Token.NOT) {
lexer.nextToken();
accept(Token.NULL);
SQLNotNullConstraint notNull = new SQLNotNullConstraint();
if (lexer.token == Token.HINT) {
List<SQLCommentHint> hints = this.parseHints();
notNull.setHints(hints);
}
column.addConstraint(notNull);
return parseColumnRest(column);
}
if (lexer.token == Token.NULL) {
lexer.nextToken();
column.getConstraints().add(new SQLNullConstraint());
return parseColumnRest(column);
}
if (lexer.token == Token.PRIMARY) {
lexer.nextToken();
accept(Token.KEY);
column.addConstraint(new SQLColumnPrimaryKey());
return parseColumnRest(column);
}
if (lexer.token == Token.UNIQUE) {
lexer.nextToken();
if (lexer.token == Token.KEY) {
lexer.nextToken();
}
column.addConstraint(new SQLColumnUniqueKey());
return parseColumnRest(column);
}
if (lexer.token == Token.KEY) {
lexer.nextToken();
column.addConstraint(new SQLColumnUniqueKey());
return parseColumnRest(column);
}
if (lexer.token == Token.REFERENCES) {
SQLColumnReference ref = parseReference();
column.addConstraint(ref);
return parseColumnRest(column);
}
if (lexer.token == Token.CONSTRAINT) {
lexer.nextToken();
SQLName name = this.name();
if (lexer.token == Token.PRIMARY) {
lexer.nextToken();
accept(Token.KEY);
SQLColumnPrimaryKey pk = new SQLColumnPrimaryKey();
pk.setName(name);
column.addConstraint(pk);
return parseColumnRest(column);
}
if (lexer.token == Token.UNIQUE) {
lexer.nextToken();
SQLColumnUniqueKey uk = new SQLColumnUniqueKey();
uk.setName(name);
column.addConstraint(uk);
return parseColumnRest(column);
}
if (lexer.token == Token.REFERENCES) {
SQLColumnReference ref = parseReference();
ref.setName(name);
column.addConstraint(ref);
return parseColumnRest(column);
}
if (lexer.token == Token.NOT) {
lexer.nextToken();
accept(Token.NULL);
SQLNotNullConstraint notNull = new SQLNotNullConstraint();
notNull.setName(name);
column.addConstraint(notNull);
return parseColumnRest(column);
}
if (lexer.token == Token.CHECK) {
SQLColumnCheck check = parseColumnCheck();
check.setName(name);
check.setParent(column);
column.addConstraint(check);
return parseColumnRest(column);
}
if (lexer.token == Token.DEFAULT) {
lexer.nextToken();
SQLExpr expr = this.expr();
column.setDefaultExpr(expr);
return parseColumnRest(column);
}
throw new ParserException("TODO : " + lexer.info());
}
if (lexer.token == Token.CHECK) {
SQLColumnCheck check = parseColumnCheck();
column.addConstraint(check);
return parseColumnRest(column);
}
if (lexer.token == Token.COMMENT) {
lexer.nextToken();
if (lexer.token == Token.LITERAL_ALIAS) {
String alias = lexer.stringVal();
if (alias.length() > 2 && alias.charAt(0) == '"' && alias.charAt(alias.length() - 1) == '"') {
alias = alias.substring(1, alias.length() - 1);
}
column.setComment(alias);
lexer.nextToken();
} else {
column.setComment(primary());
}
return parseColumnRest(column);
}
if (lexer.identifierEquals(FnvHash.Constants.AUTO_INCREMENT)) {
lexer.nextToken();
column.setAutoIncrement(true);
return parseColumnRest(column);
}
return column;
}
private SQLColumnReference parseReference() {
SQLColumnReference fk = new SQLColumnReference();
lexer.nextToken();
fk.setTable(this.name());
accept(Token.LPAREN);
this.names(fk.getColumns(), fk);
accept(Token.RPAREN);
if (lexer.identifierEquals(FnvHash.Constants.MATCH)) {
lexer.nextToken();
if (lexer.identifierEquals("FULL") || lexer.token() == Token.FULL) {
fk.setReferenceMatch(SQLForeignKeyImpl.Match.FULL);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.PARTIAL)) {
fk.setReferenceMatch(SQLForeignKeyImpl.Match.PARTIAL);
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.SIMPLE)) {
fk.setReferenceMatch(SQLForeignKeyImpl.Match.SIMPLE);
lexer.nextToken();
} else {
throw new ParserException("TODO : " + lexer.info());
}
}
while (lexer.token() == Token.ON) {
lexer.nextToken();
if (lexer.token() == Token.DELETE) {
lexer.nextToken();
SQLForeignKeyImpl.Option option = parseReferenceOption();
fk.setOnDelete(option);
} else if (lexer.token() == Token.UPDATE) {
lexer.nextToken();
SQLForeignKeyImpl.Option option = parseReferenceOption();
fk.setOnUpdate(option);
} else {
throw new ParserException("syntax error, expect DELETE or UPDATE, actual " + lexer.token() + " "
+ lexer.info());
}
}
return fk;
}
protected SQLForeignKeyImpl.Option parseReferenceOption() {
SQLForeignKeyImpl.Option option;
if (lexer.token() == Token.RESTRICT || lexer.identifierEquals(FnvHash.Constants.RESTRICT)) {
option = SQLForeignKeyImpl.Option.RESTRICT;
lexer.nextToken();
} else if (lexer.identifierEquals(FnvHash.Constants.CASCADE)) {
option = SQLForeignKeyImpl.Option.CASCADE;
lexer.nextToken();
} else if (lexer.token() == Token.SET) {
lexer.nextToken();
accept(Token.NULL);
option = SQLForeignKeyImpl.Option.SET_NULL;
} else if (lexer.identifierEquals(FnvHash.Constants.NO)) {
lexer.nextToken();
if (lexer.identifierEquals(FnvHash.Constants.ACTION)) {
option = SQLForeignKeyImpl.Option.NO_ACTION;
lexer.nextToken();
} else {
throw new ParserException("syntax error, expect ACTION, actual " + lexer.token() + " "
+ lexer.info());
}
} else {
throw new ParserException("syntax error, expect ACTION, actual " + lexer.token() + " "
+ lexer.info());
}
return option;
}
protected SQLColumnCheck parseColumnCheck() {
lexer.nextToken();
SQLExpr expr = this.expr();
SQLColumnCheck check = new SQLColumnCheck(expr);
if (lexer.token == Token.DISABLE) {
lexer.nextToken();
check.setEnable(false);
} else if (lexer.token == Token.ENABLE) {
lexer.nextToken();
check.setEnable(true);
} else if (lexer.identifierEquals(FnvHash.Constants.VALIDATE)) {
lexer.nextToken();
check.setValidate(Boolean.TRUE);
} else if (lexer.identifierEquals(FnvHash.Constants.NOVALIDATE)) {
lexer.nextToken();
check.setValidate(Boolean.FALSE);
} else if (lexer.identifierEquals(FnvHash.Constants.RELY)) {
lexer.nextToken();
check.setRely(Boolean.TRUE);
} else if (lexer.identifierEquals(FnvHash.Constants.NORELY)) {
lexer.nextToken();
check.setRely(Boolean.FALSE);
}
return check;
}
public SQLPrimaryKey parsePrimaryKey() {
accept(Token.PRIMARY);
accept(Token.KEY);
SQLPrimaryKeyImpl pk = new SQLPrimaryKeyImpl();
if (lexer.identifierEquals(FnvHash.Constants.CLUSTERED)) {
lexer.nextToken();
pk.setClustered(true);
}
accept(Token.LPAREN);
orderBy(pk.getColumns(), pk);
accept(Token.RPAREN);
return pk;
}
public SQLUnique parseUnique() {
accept(Token.UNIQUE);
SQLUnique unique = new SQLUnique();
accept(Token.LPAREN);
orderBy(unique.getColumns(), unique);
accept(Token.RPAREN);
if (lexer.token == Token.DISABLE) {
lexer.nextToken();
unique.setEnable(false);
} else if (lexer.token == Token.ENABLE) {
lexer.nextToken();
unique.setEnable(true);
} else if (lexer.identifierEquals(FnvHash.Constants.VALIDATE)) {
lexer.nextToken();
unique.setValidate(Boolean.TRUE);
} else if (lexer.identifierEquals(FnvHash.Constants.NOVALIDATE)) {
lexer.nextToken();
unique.setValidate(Boolean.FALSE);
} else if (lexer.identifierEquals(FnvHash.Constants.RELY)) {
lexer.nextToken();
unique.setRely(Boolean.TRUE);
} else if (lexer.identifierEquals(FnvHash.Constants.NORELY)) {
lexer.nextToken();
unique.setRely(Boolean.FALSE);
}
return unique;
}
public void parseAssignItem(List<SQLAssignItem> outList, SQLObject parent) {
accept(Token.LPAREN);
for (;;) {
SQLAssignItem item = this.parseAssignItem();
item.setParent(parent);
outList.add(item);
if (lexer.token() == Token.COMMA) {
lexer.nextToken();
continue;
}
break;
}
accept(Token.RPAREN);
}
public SQLAssignItem parseAssignItem() {
SQLAssignItem item = new SQLAssignItem();
SQLExpr var = primary();
if (var instanceof SQLIdentifierExpr) {
var = new SQLVariantRefExpr(((SQLIdentifierExpr) var).getName());
}
item.setTarget(var);
if (lexer.token == Token.COLONEQ) {
lexer.nextToken();
} else if (lexer.token == Token.TRUE || lexer.identifierEquals(FnvHash.Constants.TRUE)) {
lexer.nextToken();
item.setValue(new SQLBooleanExpr(true));
return item;
} else if (lexer.token == Token.ON) {
lexer.nextToken();
item.setValue(new SQLIdentifierExpr("ON"));
return item;
} else {
if (lexer.token == Token.EQ) {
lexer.nextToken();
} else if (JdbcConstants.DB2.equals(dbType)) {
// skip
} else {
accept(Token.EQ);
}
}
if (lexer.token == Token.ON) {
item.setValue(new SQLIdentifierExpr(lexer.stringVal()));
lexer.nextToken();
} else {
if (lexer.token == Token.ALL) {
item.setValue(new SQLIdentifierExpr(lexer.stringVal()));
lexer.nextToken();
} else {
SQLExpr expr = expr();
if (lexer.token == Token.COMMA && JdbcConstants.POSTGRESQL.equals(dbType)) {
SQLListExpr listExpr = new SQLListExpr();
listExpr.addItem(expr);
expr.setParent(listExpr);
do {
lexer.nextToken();
SQLExpr listItem = this.expr();
listItem.setParent(listExpr);
listExpr.addItem(listItem);
} while (lexer.token == Token.COMMA);
item.setValue(listExpr);
} else {
item.setValue(expr);
}
}
}
return item;
}
public List<SQLCommentHint> parseHints() {
List<SQLCommentHint> hints = new ArrayList<SQLCommentHint>();
parseHints(hints);
return hints;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void parseHints(List hints) {
if (lexer.token == Token.HINT) {
SQLCommentHint hint = new SQLCommentHint(lexer.stringVal());
if (lexer.commentCount > 0) {
hint.addBeforeComment(lexer.comments);
}
hints.add(hint);
lexer.nextToken();
}
}
public SQLConstraint parseConstaint() {
SQLName name = null;
if (lexer.token == Token.CONSTRAINT) {
lexer.nextToken();
name = this.name();
}
SQLConstraint constraint;
if (lexer.token == Token.PRIMARY) {
constraint = parsePrimaryKey();
} else if (lexer.token == Token.UNIQUE) {
constraint = parseUnique();
} else if (lexer.token == Token.KEY) {
constraint = parseUnique();
} else if (lexer.token == Token.FOREIGN) {
constraint = parseForeignKey();
} else if (lexer.token == Token.CHECK) {
constraint = parseCheck();
} else {
throw new ParserException("TODO : " + lexer.info());
}
constraint.setName(name);
return constraint;
}
public SQLCheck parseCheck() {
accept(Token.CHECK);
SQLCheck check = createCheck();
accept(Token.LPAREN);
check.setExpr(this.expr());
accept(Token.RPAREN);
return check;
}
protected SQLCheck createCheck() {
return new SQLCheck();
}
public SQLForeignKeyConstraint parseForeignKey() {
accept(Token.FOREIGN);
accept(Token.KEY);
SQLForeignKeyImpl fk = createForeignKey();
accept(Token.LPAREN);
this.names(fk.getReferencingColumns(), fk);
accept(Token.RPAREN);
accept(Token.REFERENCES);
fk.setReferencedTableName(this.name());
if (lexer.token == Token.LPAREN) {
lexer.nextToken();
this.names(fk.getReferencedColumns(), fk);
accept(Token.RPAREN);
}
if (lexer.token == Token.ON) {
lexer.nextToken();
accept(Token.DELETE);
if (lexer.identifierEquals(FnvHash.Constants.CASCADE)) {
lexer.nextToken();
fk.setOnDeleteCascade(true);
} else {
accept(Token.SET);
accept(Token.NULL);
fk.setOnDeleteSetNull(true);
}
}
return fk;
}
protected SQLForeignKeyImpl createForeignKey() {
return new SQLForeignKeyImpl();
}
public SQLSelectItem parseSelectItem() {
SQLExpr expr;
boolean connectByRoot = false;
Token token = lexer.token;
if (token == Token.IDENTIFIER) {
String ident = lexer.stringVal();
long hash_lower = lexer.hash_lower();
lexer.nextTokenComma();
if (hash_lower == FnvHash.Constants.CONNECT_BY_ROOT) {
connectByRoot = lexer.token != Token.LPAREN;
if (connectByRoot) {
expr = new SQLIdentifierExpr(lexer.stringVal());
lexer.nextToken();
} else {
expr = new SQLIdentifierExpr(ident);
}
} else if (FnvHash.Constants.DATE == hash_lower
&& lexer.token == Token.LITERAL_CHARS
&& (JdbcConstants.ORACLE.equals(getDbType())
|| JdbcConstants.POSTGRESQL.equals(getDbType()))) {
String literal = lexer.stringVal();
lexer.nextToken();
SQLDateExpr dateExpr = new SQLDateExpr();
dateExpr.setLiteral(literal);
expr = dateExpr;
} else {
expr = new SQLIdentifierExpr(ident, hash_lower);
}
token = lexer.token;
if (token == Token.DOT) {
lexer.nextTokenIdent();
String name;
long name_hash_lower;
if (lexer.token == Token.STAR) {
name = "*";
name_hash_lower = FnvHash.Constants.STAR;
} else {
name = lexer.stringVal();
name_hash_lower = lexer.hash_lower();
}
lexer.nextTokenComma();
token = lexer.token;
if (token == Token.LPAREN) {
boolean aggregate = hash_lower == FnvHash.Constants.WMSYS && name_hash_lower == FnvHash.Constants.WM_CONCAT;
expr = methodRest(expr, name, aggregate);
token = lexer.token;
} else {
if (name_hash_lower == FnvHash.Constants.NEXTVAL) {
expr = new SQLSequenceExpr((SQLIdentifierExpr) expr, SQLSequenceExpr.Function.NextVal);
} else if (name_hash_lower == FnvHash.Constants.CURRVAL) {
expr = new SQLSequenceExpr((SQLIdentifierExpr) expr, SQLSequenceExpr.Function.CurrVal);
} else if (name_hash_lower == FnvHash.Constants.PREVVAL) {
expr = new SQLSequenceExpr((SQLIdentifierExpr) expr, SQLSequenceExpr.Function.PrevVal);
} else {
expr = new SQLPropertyExpr(expr, name, name_hash_lower);
}
}
}
if (token == Token.COMMA) {
return new SQLSelectItem(expr, null, connectByRoot);
}
if (token == Token.AS) {
lexer.nextToken();
String as = null;
if (lexer.token != Token.COMMA && lexer.token != Token.FROM) {
as = lexer.stringVal();
lexer.nextTokenComma();
if (lexer.token == Token.DOT) {
lexer.nextToken();
as += '.' + lexer.stringVal();
lexer.nextToken();
}
}
return new SQLSelectItem(expr, as, connectByRoot);
}
if (token == Token.LITERAL_ALIAS) {
String as = lexer.stringVal();
lexer.nextTokenComma();
return new SQLSelectItem(expr, as, connectByRoot);
}
if ((token == Token.IDENTIFIER && hash_lower != FnvHash.Constants.CURRENT)
|| token == Token.MODEL) {
String as;
if (lexer.hash_lower == FnvHash.Constants.FORCE && JdbcConstants.MYSQL.equals(dbType)) {
String force = lexer.stringVal();
Lexer.SavePoint savePoint = lexer.mark();
lexer.nextToken();
if (lexer.token == Token.PARTITION) {
lexer.reset(savePoint);
as = null;
} else {
as = force;
lexer.nextTokenComma();
}
} else {
as = lexer.stringVal();
lexer.nextTokenComma();
}
return new SQLSelectItem(expr, as, connectByRoot);
}
if (token == Token.LPAREN) {
lexer.nextToken();
expr = this.methodRest(expr, false);
} else {
expr = this.primaryRest(expr);
}
expr = this.exprRest(expr);
} else if (token == Token.STAR) {
expr = new SQLAllColumnExpr();
lexer.nextToken();
return new SQLSelectItem(expr, null, connectByRoot);
} else if (token == Token.DO || token == Token.JOIN) {
expr = this.name();
expr = this.exprRest(expr);
} else {
expr = expr();
}
final String alias;
switch (lexer.token) {
case FULL:
case MODEL:
case TABLESPACE:
alias = lexer.stringVal();
lexer.nextToken();
break;
default:
alias = as();
break;
}
SQLSelectItem selectItem = new SQLSelectItem(expr, alias, connectByRoot);
if (lexer.token == Token.HINT && !lexer.isEnabled(SQLParserFeature.StrictForWall)) {
String comment = "/*" + lexer.stringVal() + "*/";
selectItem.addAfterComment(comment);
lexer.nextToken();
}
return selectItem;
}
public SQLExpr parseGroupingSet() {
String tmp = lexer.stringVal();
acceptIdentifier("GROUPING");
SQLGroupingSetExpr expr = new SQLGroupingSetExpr();
if (lexer.token == Token.SET || lexer.identifierEquals(FnvHash.Constants.SET)) {
lexer.nextToken();
} else {
return new SQLIdentifierExpr(tmp);
}
accept(Token.LPAREN);
this.exprList(expr.getParameters(), expr);
accept(Token.RPAREN);
return expr;
}
protected SQLPartition parsePartition() {
throw new ParserException("TODO");
}
protected SQLPartitionBy parsePartitionBy() {
throw new ParserException("TODO");
}
public SQLPartitionValue parsePartitionValues() {
if (lexer.token != Token.VALUES) {
return null;
}
lexer.nextToken();
SQLPartitionValue values = null;
if (lexer.token == Token.IN) {
lexer.nextToken();
values = new SQLPartitionValue(SQLPartitionValue.Operator.In);
accept(Token.LPAREN);
this.exprList(values.getItems(), values);
accept(Token.RPAREN);
} else if (lexer.identifierEquals(FnvHash.Constants.LESS)) {
lexer.nextToken();
acceptIdentifier("THAN");
values = new SQLPartitionValue(SQLPartitionValue.Operator.LessThan);
if (lexer.identifierEquals(FnvHash.Constants.MAXVALUE)) {
SQLIdentifierExpr maxValue = new SQLIdentifierExpr(lexer.stringVal());
lexer.nextToken();
maxValue.setParent(values);
values.addItem(maxValue);
} else {
accept(Token.LPAREN);
this.exprList(values.getItems(), values);
accept(Token.RPAREN);
}
} else if (lexer.token == Token.LPAREN) {
values = new SQLPartitionValue(SQLPartitionValue.Operator.List);
lexer.nextToken();
this.exprList(values.getItems(), values);
accept(Token.RPAREN);
}
return values;
}
protected static boolean isIdent(SQLExpr expr, String name) {
if (expr instanceof SQLIdentifierExpr) {
SQLIdentifierExpr identExpr = (SQLIdentifierExpr) expr;
return identExpr.getName().equalsIgnoreCase(name);
}
return false;
}
public SQLLimit parseLimit() {
if (lexer.token == Token.LIMIT) {
lexer.nextTokenValue();
SQLLimit limit = new SQLLimit();
SQLExpr temp;
if (lexer.token == Token.LITERAL_INT) {
temp = new SQLIntegerExpr(lexer.integerValue());
lexer.nextTokenComma();
if (lexer.token != Token.COMMA && lexer.token != Token.EOF && lexer.token != Token.IDENTIFIER) {
temp = this.primaryRest(temp);
temp = this.exprRest(temp);
}
} else {
temp = this.expr();
}
if (lexer.token == (Token.COMMA)) {
limit.setOffset(temp);
lexer.nextTokenValue();
SQLExpr rowCount;
if (lexer.token == Token.LITERAL_INT) {
rowCount = new SQLIntegerExpr(lexer.integerValue());
lexer.nextToken();
if (lexer.token != Token.EOF && lexer.token != Token.IDENTIFIER) {
rowCount = this.primaryRest(rowCount);
rowCount = this.exprRest(rowCount);
}
} else {
rowCount = this.expr();
}
limit.setRowCount(rowCount);
} else if (lexer.identifierEquals(FnvHash.Constants.OFFSET)) {
limit.setRowCount(temp);
lexer.nextToken();
limit.setOffset(this.expr());
} else {
limit.setRowCount(temp);
}
return limit;
}
return null;
}
}
| [
"[email protected]"
] | |
e67eab1ee61fdc31c818da808c23192909bb2474 | 40f71c5b790deeb88f4a473e3fa57008742c8f76 | /cms-wenjiaquan/src/main/java/com/wenjiaquan/cms/pojo/Category.java | 96d3ce5d440d27aa5abf8bccaa730d4d02ab544a | [] | no_license | wenjiaquan/cms-wenjiaquan | 3eae3e26956ae02e780aa888a22f09fb759d9e02 | a7c380326c31c30d84933069d6e53b177e551857 | refs/heads/master | 2022-12-29T10:24:18.104189 | 2020-02-20T10:27:42 | 2020-02-20T10:27:42 | 227,094,046 | 0 | 0 | null | 2022-12-16T04:54:09 | 2019-12-10T10:45:38 | JavaScript | UTF-8 | Java | false | false | 834 | java | package com.wenjiaquan.cms.pojo;
public class Category {
private Integer id;
private String name;
private Integer channel_id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getChannel_id() {
return channel_id;
}
public void setChannel_id(Integer channel_id) {
this.channel_id = channel_id;
}
@Override
public String toString() {
return "Category [id=" + id + ", name=" + name + ", channel_id=" + channel_id + "]";
}
public Category(Integer id, String name, Integer channel_id) {
super();
this.id = id;
this.name = name;
this.channel_id = channel_id;
}
public Category() {
super();
}
}
| [
"[email protected]"
] | |
5fe2bcc3d37ca397c1836900c417477812fa7fef | 4ba09e3574f5652ed29b37afe7770c2205fbda1a | /src/main/java/com/github/mummyding/ymbase/widget/textcounter/Counter.java | 42eb0e9b0d4b4b1c85d18bd0a7fc5840909c829b | [
"MIT"
] | permissive | MummyDing/YM-Base | c1f6aa764d3a76d7ef008f0f7790105eb6985521 | 13de974f7768148b825beca2cf5298ed1fac213d | refs/heads/master | 2021-01-23T07:38:05.187617 | 2017-04-13T09:07:24 | 2017-04-13T09:07:24 | 86,434,646 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,397 | java | package com.github.mummyding.ymbase.widget.textcounter;
/**
* Created by prem on 10/28/14.
*
* Class that handles the counting up/down of the text value
*/
class Counter implements Runnable {
final CounterView view;
final float increment, startValue, endValue;
final long interval;
float currentValue, newValue;
Counter(CounterView view, float startValue, float endValue, long interval, float increment) {
this.view = view;
this.startValue = startValue;
this.endValue = endValue;
this.interval = interval;
this.increment = increment;
this.newValue = this.startValue;
this.currentValue = this.startValue - increment;
}
@Override
public void run() {
if (valuesAreCorrect()) {
float valueToSet;
if (newValue <= endValue) {
valueToSet = newValue;
} else {
valueToSet = endValue;
}
view.setCurrentTextValue(valueToSet);
currentValue = newValue;
newValue += increment;
view.removeCallbacks(Counter.this);
view.postDelayed(Counter.this, interval);
}
}
private boolean valuesAreCorrect() {
if(increment >= 0) {
return newValue >= currentValue;
} else {
return newValue <= currentValue;
}
}
}
| [
"[email protected]"
] | |
f1cec48372b3b2e225dd650a87924a911e76795b | 579ce161c5922e9eb5694d603e4ef7c4ed6f7fd8 | /src/br/senai/informatica/leansurvey/controller/GenderController.java | 3b1f2bad67c5479a579e292b567ff4f6bf581ad5 | [
"MIT"
] | permissive | HenriqueRulez/Senai-LS | 3f33da65245efc04634358c213be5d421abd7523 | 8df345edc24ae07a37721a360053330a61f8dd6b | refs/heads/master | 2021-01-11T06:46:46.936539 | 2016-10-22T19:23:29 | 2016-10-22T19:23:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,455 | java | package br.senai.informatica.leansurvey.controller;
import java.net.URI;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import br.senai.informatica.leansurvey.dao.GenderDao;
import br.senai.informatica.leansurvey.model.Gender;
@RestController
public class GenderController {
@Autowired
private GenderDao genderDao;
@RequestMapping(value="/gender", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Gender> insert(@RequestBody Gender gender){
try {
genderDao.insertGenderDao(gender);
URI location = new URI ("/gender/"+ gender.getId());
return ResponseEntity.created(location).body(gender);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@RequestMapping(value="/gender/{id}", method=RequestMethod.PUT, consumes=MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Gender> update (@PathVariable long id, @RequestBody Gender gender){
try {
genderDao.updateGender(gender.getDescription(), id);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@RequestMapping(value="/gender/{id}", method=RequestMethod.DELETE)
public ResponseEntity<Void> deleteGender(@PathVariable("id") long idGender){
genderDao.deleteGender(idGender);
return ResponseEntity.noContent().build();
}
@RequestMapping(value="/gender", method=RequestMethod.GET, consumes=MediaType.APPLICATION_JSON_UTF8_VALUE)
public List<Gender> findGender(){
return genderDao.findGender();
}
@RequestMapping(value="/gender/{id}", method=RequestMethod.GET, consumes=MediaType.APPLICATION_JSON_UTF8_VALUE)
public List<Gender> findGenderById(@PathVariable("id") long idGender){
return genderDao.findGenderById(idGender);
}
}
| [
"[email protected]"
] | |
9064964b7204179ff143140bfd67ace8f09033fa | 4637d7a54df5dcecc42faa226e17c7ceba192e62 | /trees/PreOrderIterative.java | 26c3d6fa8f10d0973eec99ed70c1a9b4a632fda9 | [] | no_license | DishantGudlani/DSA | c27a43612597d334bdbed462788fb86c21995d86 | f7031237526fbe21d566e3589f555b65edc171c2 | refs/heads/master | 2022-10-14T23:21:34.389786 | 2020-06-16T12:25:07 | 2020-06-16T12:25:07 | 268,698,913 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,056 | java | import java.util.Stack;
class Node
{
int data;
Node left, right;
Node(int data)
{
this.data = data;
left = right = null;
}
}
class BinaryTree
{
Node root;
void preOrder(Node node)
{
if(node == null)
return;
Stack<Node> stack = new Stack<Node>();
stack.push(root);
while(!stack.empty())
{
Node current = stack.pop();
System.out.print(current.data + " ");
if(current.right != null)
stack.push(current.right);
if(current.left != null)
stack.push(current.left);
}
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(8);
tree.root.right = new Node(2);
tree.root.left.left = new Node(3);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(2);
tree.preOrder(tree.root);
}
} | [
"[email protected]"
] | |
5f1367a9d5aff2f01edaf87167062986832c8e23 | a83455ba8474617a84960695d4efb1064255ba55 | /app/src/test/java/com/epsi/myproject/ExampleUnitTest.java | 13c6792cd85cb6ec08f1c1cfcf4f705c3a9933cb | [] | no_license | Sirikaa/PFR_android | 12243352c836c59e02b03f9ddd43b954294027fe | a640a49e0667909e479c41e4e5a3a6eac9f71ac0 | refs/heads/master | 2020-08-03T09:38:41.346247 | 2019-10-13T10:24:24 | 2019-10-13T10:24:24 | 211,705,053 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 379 | java | package com.epsi.myproject;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
b2a97beec916cc68a5d0a87cff97a272a30726a6 | 34e5959512f43e0ba98a179463d8aca1cef03e5f | /简单工厂模式14-1/src/com/practice/SimpleFactory/Hero.java | dd1f69c6323e7e28420661878121f44ab73eefa2 | [] | no_license | miaowu169/Factory-Method-Pattern | 42bb8440ded279cc9a874155ecc1aff077fb70e1 | 39ce251204e32f87532ea8a9edc0dc9c804d8581 | refs/heads/master | 2020-12-04T02:42:59.421009 | 2020-01-03T11:45:50 | 2020-01-03T11:45:50 | 231,576,201 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 85 | java | package com.practice.SimpleFactory;
public interface Hero {
void display();
}
| [
"[email protected]"
] | |
d1ea52b0fbe1f7d70b06d0faa2e8b6b546165c05 | e093178a277b2269be0eac7b4669164ac2f01179 | /testsuites/rio/src/main/java/org/openrdf/rio/datatypes/AbstractDatatypeHandlerTest.java | 25c75c7d4ee161e06ded6556d11c5a668b1fdca5 | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | obidea/semantika-http-sesame | bf9f28f39313b3c750dba686071588a29d1c634d | 45ef62ad2d2f45ce521861f87d9d49b67e15ba4b | refs/heads/semantika-http-1.2.1 | 2022-10-07T01:37:37.347940 | 2015-10-25T23:42:17 | 2015-10-25T23:42:17 | 44,924,746 | 0 | 1 | null | 2022-09-22T18:22:36 | 2015-10-25T19:02:21 | Java | UTF-8 | Java | false | false | 9,676 | java | /*
* Licensed to Aduna under one or more contributor license agreements.
* See the NOTICE.txt file distributed with this work for additional
* information regarding copyright ownership.
*
* Aduna licenses this file to you under the terms of the Aduna BSD
* License (the "License"); you may not use this file except in compliance
* with the License. See the LICENSE.txt file distributed with this work
* for the full License.
*
* 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.openrdf.rio.datatypes;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.openrdf.model.Literal;
import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.util.LiteralUtilException;
import org.openrdf.rio.DatatypeHandler;
/**
* Abstract test for DatatypeHandler interface.
*
* @author Peter Ansell
*/
public abstract class AbstractDatatypeHandlerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Generates a new instance of the {@link DatatypeHandler} implementation in
* question and returns it.
*
* @return A new instance of the {@link DatatypeHandler} implementation being
* tested.
*/
protected abstract DatatypeHandler getNewDatatypeHandler();
/**
* @return A URI that must return true from
* {@link DatatypeHandler#isRecognizedDatatype(URI)} and not throw an
* exception if used with a valid value when calling
* {@link DatatypeHandler#verifyDatatype(String, URI)} and
* {@link DatatypeHandler#normalizeDatatype(String, URI, ValueFactory)}
* .
*/
protected abstract URI getRecognisedDatatypeUri();
/**
* @return A URI that must return false from
* {@link DatatypeHandler#isRecognizedDatatype(URI)} and throw an
* exception if used with
* {@link DatatypeHandler#verifyDatatype(String, URI)} and
* {@link DatatypeHandler#normalizeDatatype(String, URI, ValueFactory)}
* .
*/
protected abstract URI getUnrecognisedDatatypeUri();
/**
* @return A string value that does match the recognised datatype URI, and
* will succeed when used with both
* {@link DatatypeHandler#verifyDatatype(String, URI)} and
* {@link DatatypeHandler#normalizeDatatype(String, URI, ValueFactory)}
* .
*/
protected abstract String getValueMatchingRecognisedDatatypeUri();
/**
* @return A string value that does not match the recognised datatype URI,
* and will fail when used with both
* {@link DatatypeHandler#verifyDatatype(String, URI)} and
* {@link DatatypeHandler#normalizeDatatype(String, URI, ValueFactory)}
* .
*/
protected abstract String getValueNotMatchingRecognisedDatatypeUri();
/**
* @return An instance of {@link Literal} that is equal to the expected
* output from a successful call to
* {@link DatatypeHandler#normalizeDatatype(String, URI, org.openrdf.model.ValueFactory)}
* ;
*/
protected abstract Literal getNormalisedLiteralForRecognisedDatatypeAndValue();
/**
* @return An instance of {@link ValueFactory} that can be used to produce a
* normalised literal.
*/
protected abstract ValueFactory getValueFactory();
/**
* @return The key that is expected to be returned for
* {@link DatatypeHandler#getKey()} to identify the service.
*/
protected abstract String getExpectedKey();
private DatatypeHandler testHandler;
private ValueFactory vf;
@Before
public void setUp()
throws Exception
{
testHandler = getNewDatatypeHandler();
vf = getValueFactory();
}
@After
public void tearDown()
throws Exception
{
testHandler = null;
vf = null;
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#isRecognizedDatatype(org.openrdf.model.URI)}
* .
*/
@Test
public void testIsRecognizedDatatypeNull()
throws Exception
{
thrown.expect(NullPointerException.class);
testHandler.isRecognizedDatatype(null);
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#isRecognizedDatatype(org.openrdf.model.URI)}
* .
*/
@Test
public void testIsRecognizedDatatypeTrue()
throws Exception
{
assertTrue(testHandler.isRecognizedDatatype(getRecognisedDatatypeUri()));
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#isRecognizedDatatype(org.openrdf.model.URI)}
* .
*/
@Test
public void testIsRecognizedDatatypeFalse()
throws Exception
{
assertFalse(testHandler.isRecognizedDatatype(getUnrecognisedDatatypeUri()));
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.openrdf.model.URI)}
* .
*/
@Test
public void testVerifyDatatypeNullDatatypeUri()
throws Exception
{
thrown.expect(NullPointerException.class);
testHandler.verifyDatatype(getValueMatchingRecognisedDatatypeUri(), null);
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.openrdf.model.URI)}
* .
*/
@Test
public void testVerifyDatatypeNullValueRecognised()
throws Exception
{
thrown.expect(NullPointerException.class);
testHandler.verifyDatatype(null, getRecognisedDatatypeUri());
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.openrdf.model.URI)}
* .
*/
@Test
public void testVerifyDatatypeNullValueUnrecognised()
throws Exception
{
thrown.expect(LiteralUtilException.class);
testHandler.verifyDatatype(null, getUnrecognisedDatatypeUri());
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.openrdf.model.URI)}
* .
*/
@Test
public void testVerifyDatatypeUnrecognisedDatatypeUri()
throws Exception
{
thrown.expect(LiteralUtilException.class);
testHandler.verifyDatatype(getValueMatchingRecognisedDatatypeUri(), getUnrecognisedDatatypeUri());
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.openrdf.model.URI)}
* .
*/
@Test
public void testVerifyDatatypeInvalidValue()
throws Exception
{
assertFalse(testHandler.verifyDatatype(getValueNotMatchingRecognisedDatatypeUri(),
getRecognisedDatatypeUri()));
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#verifyDatatype(java.lang.String, org.openrdf.model.URI)}
* .
*/
@Test
public void testVerifyDatatypeValidValue()
throws Exception
{
assertTrue(testHandler.verifyDatatype(getValueMatchingRecognisedDatatypeUri(),
getRecognisedDatatypeUri()));
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#normalizeDatatype(java.lang.String, org.openrdf.model.URI, org.openrdf.model.ValueFactory)}
* .
*/
@Test
public void testNormalizeDatatypeNullDatatypeUri()
throws Exception
{
thrown.expect(NullPointerException.class);
testHandler.normalizeDatatype(getValueMatchingRecognisedDatatypeUri(), null, vf);
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#normalizeDatatype(java.lang.String, org.openrdf.model.URI, org.openrdf.model.ValueFactory)}
* .
*/
@Test
public void testNormalizeDatatypeNullValue()
throws Exception
{
thrown.expect(NullPointerException.class);
testHandler.normalizeDatatype(null, getRecognisedDatatypeUri(), vf);
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#normalizeDatatype(java.lang.String, org.openrdf.model.URI, org.openrdf.model.ValueFactory)}
* .
*/
@Test
public void testNormalizeDatatypeUnrecognisedDatatypeUri()
throws Exception
{
thrown.expect(LiteralUtilException.class);
testHandler.normalizeDatatype(getValueMatchingRecognisedDatatypeUri(), getUnrecognisedDatatypeUri(), vf);
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#normalizeDatatype(java.lang.String, org.openrdf.model.URI, org.openrdf.model.ValueFactory)}
* .
*/
@Test
public void testNormalizeDatatypeInvalidValue()
throws Exception
{
thrown.expect(LiteralUtilException.class);
testHandler.normalizeDatatype(getValueNotMatchingRecognisedDatatypeUri(), getRecognisedDatatypeUri(),
vf);
}
/**
* Test method for
* {@link org.openrdf.rio.DatatypeHandler#normalizeDatatype(java.lang.String, org.openrdf.model.URI, org.openrdf.model.ValueFactory)}
* .
*/
@Test
public void testNormalizeDatatypeValidValue()
throws Exception
{
Literal result = testHandler.normalizeDatatype(getValueMatchingRecognisedDatatypeUri(),
getRecognisedDatatypeUri(), vf);
Literal expectedResult = getNormalisedLiteralForRecognisedDatatypeAndValue();
assertNotNull(expectedResult.getDatatype());
assertNotNull(expectedResult.getLabel());
assertNull(expectedResult.getLanguage());
assertEquals(expectedResult.getDatatype(), result.getDatatype());
assertEquals(expectedResult.getLabel(), result.getLabel());
assertEquals(expectedResult.getLanguage(), result.getLanguage());
}
/**
* Test method for {@link org.openrdf.rio.DatatypeHandler#getKey()}.
*/
@Test
public void testGetKey()
throws Exception
{
String result = testHandler.getKey();
String expectedResult = getExpectedKey();
assertEquals(expectedResult, result);
}
}
| [
"[email protected]"
] | |
700fab8db3280582e6c61817ecd4e11f8a3bf4f0 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/24/24_12eab67db75e8e015a98891b676f5482882f2918/PlayerInjectionHandler/24_12eab67db75e8e015a98891b676f5482882f2918_PlayerInjectionHandler_s.java | 91af5b590439f1c61bf15169c1898fc3ad21998f | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 9,666 | java | package com.comphenix.protocol.injector.player;
import java.io.DataInputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.server.Packet;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketListener;
import com.comphenix.protocol.injector.ListenerInvoker;
import com.comphenix.protocol.injector.PlayerLoggedOutException;
import com.comphenix.protocol.injector.PacketFilterManager.PlayerInjectHooks;
import com.google.common.collect.ImmutableSet;
/**
* Responsible for injecting into a player's sendPacket method.
*
* @author Kristian
*/
public class PlayerInjectionHandler {
// Server connection injection
private InjectedServerConnection serverInjection;
// The last successful player hook
private PlayerInjector lastSuccessfulHook;
// Player injection
private Map<DataInputStream, Player> connectionLookup = new ConcurrentHashMap<DataInputStream, Player>();
private Map<Player, PlayerInjector> playerInjection = new HashMap<Player, PlayerInjector>();
// Player injection type
private PlayerInjectHooks playerHook = PlayerInjectHooks.NETWORK_SERVER_OBJECT;
// Error logger
private Logger logger;
// Whether or not we're closing
private boolean hasClosed;
// Used to invoke events
private ListenerInvoker invoker;
// Enabled packet filters
private Set<Integer> sendingFilters = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>());
// The class loader we're using
private ClassLoader classLoader;
public PlayerInjectionHandler(ClassLoader classLoader, Logger logger, ListenerInvoker invoker, Server server) {
this.classLoader = classLoader;
this.logger = logger;
this.invoker = invoker;
this.serverInjection = new InjectedServerConnection(logger, server);
}
/**
* Retrieves how the server packets are read.
* @return Injection method for reading server packets.
*/
public PlayerInjectHooks getPlayerHook() {
return playerHook;
}
/**
* Add an underlying packet handler of the given ID.
* @param packetID - packet ID to register.
*/
public void addPacketHandler(int packetID) {
sendingFilters.add(packetID);
}
/**
* Remove an underlying packet handler of ths ID.
* @param packetID - packet ID to unregister.
*/
public void removePacketHandler(int packetID) {
sendingFilters.remove(packetID);
}
/**
* Sets how the server packets are read.
* @param playerHook - the new injection method for reading server packets.
*/
public void setPlayerHook(PlayerInjectHooks playerHook) {
this.playerHook = playerHook;
}
/**
* Used to construct a player hook.
* @param player - the player to hook.
* @param hook - the hook type.
* @return A new player hoook
* @throws IllegalAccessException Unable to do our reflection magic.
*/
private PlayerInjector getHookInstance(Player player, PlayerInjectHooks hook) throws IllegalAccessException {
// Construct the correct player hook
switch (hook) {
case NETWORK_HANDLER_FIELDS:
return new NetworkFieldInjector(classLoader, logger, player, invoker, sendingFilters);
case NETWORK_MANAGER_OBJECT:
return new NetworkObjectInjector(logger, player, invoker, sendingFilters);
case NETWORK_SERVER_OBJECT:
return new NetworkServerInjector(classLoader, logger, player, invoker, sendingFilters, serverInjection);
default:
throw new IllegalArgumentException("Cannot construct a player injector.");
}
}
public Player getPlayerByConnection(DataInputStream inputStream) {
return connectionLookup.get(inputStream);
}
/**
* Initialize a player hook, allowing us to read server packets.
* @param manager - the main packet filter manager.
* @param player - player to hook.
*/
public void injectPlayer(Player player) {
PlayerInjector injector = null;
PlayerInjectHooks currentHook = playerHook;
boolean firstPlayer = lastSuccessfulHook == null;
// Don't inject if the class has closed
if (!hasClosed && player != null && !playerInjection.containsKey(player)) {
while (true) {
try {
injector = getHookInstance(player, currentHook);
injector.initialize();
injector.injectManager();
DataInputStream inputStream = injector.getInputStream(false);
if (!player.isOnline() || inputStream == null) {
throw new PlayerLoggedOutException();
}
playerInjection.put(player, injector);
connectionLookup.put(inputStream, player);
break;
} catch (PlayerLoggedOutException e) {
throw e;
} catch (Exception e) {
// Mark this injection attempt as a failure
logger.log(Level.SEVERE, "Player hook " + currentHook.toString() + " failed.", e);
// Clean up as much as possible
try {
if (injector != null)
injector.cleanupAll();
} catch (Exception e2) {
logger.log(Level.WARNING, "Cleaing up after player hook failed.", e);
}
if (currentHook.ordinal() > 0) {
// Choose the previous player hook type
currentHook = PlayerInjectHooks.values()[currentHook.ordinal() - 1];
logger.log(Level.INFO, "Switching to " + currentHook.toString() + " instead.");
} else {
// UTTER FAILURE
playerInjection.put(player, null);
return;
}
}
}
// Update values
if (injector != null)
lastSuccessfulHook = injector;
if (currentHook != playerHook || firstPlayer)
setPlayerHook(currentHook);
}
}
/**
* Unregisters the given player.
* @param player - player to unregister.
*/
public void uninjectPlayer(Player player) {
if (!hasClosed && player != null) {
PlayerInjector injector = playerInjection.get(player);
if (injector != null) {
DataInputStream input = injector.getInputStream(true);
injector.cleanupAll();
playerInjection.remove(player);
connectionLookup.remove(input);
}
}
}
public void sendServerPacket(Player reciever, PacketContainer packet, boolean filters) throws InvocationTargetException {
getInjector(reciever).sendServerPacket(packet.getHandle(), filters);
}
private PlayerInjector getInjector(Player player) {
if (!playerInjection.containsKey(player)) {
// What? Try to inject again.
injectPlayer(player);
}
PlayerInjector injector = playerInjection.get(player);
// Check that the injector was sucessfully added
if (injector != null)
return injector;
else
throw new IllegalArgumentException("Player has no injected handler.");
}
/**
* Determine if the given listeners are valid.
* @param listeners - listeners to check.
*/
public void checkListener(Set<PacketListener> listeners) {
// Make sure the current listeners are compatible
if (lastSuccessfulHook != null) {
for (PacketListener listener : listeners) {
try {
checkListener(listener);
} catch (IllegalStateException e) {
logger.log(Level.WARNING, "Unsupported listener.", e);
}
}
}
}
/**
* Determine if a listener is valid or not.
* @param listener - listener to check.
* @throws IllegalStateException If the given listener's whitelist cannot be fulfilled.
*/
public void checkListener(PacketListener listener) {
try {
if (lastSuccessfulHook != null)
lastSuccessfulHook.checkListener(listener);
} catch (Exception e) {
throw new IllegalStateException("Registering listener " + PacketAdapter.getPluginName(listener) + " failed", e);
}
}
/**
* Process a packet as if it were sent by the given player.
* @param player - the sender.
* @param mcPacket - the packet to process.
* @throws IllegalAccessException If the reflection machinery failed.
* @throws InvocationTargetException If the underlying method caused an error.
*/
public void processPacket(Player player, Packet mcPacket) throws IllegalAccessException, InvocationTargetException {
PlayerInjector injector = getInjector(player);
injector.processPacket(mcPacket);
}
/**
* Retrieve the current list of registered sending listeners.
* @return List of the sending listeners's packet IDs.
*/
public Set<Integer> getSendingFilters() {
return ImmutableSet.copyOf(sendingFilters);
}
/**
* Retrieve the current logger.
* @return Error logger.
*/
public Logger getLogger() {
return logger;
}
public void close() {
// Guard
if (hasClosed || playerInjection == null)
return;
// Remove everything
for (PlayerInjector injection : playerInjection.values()) {
if (injection != null) {
injection.cleanupAll();
}
}
// Remove server handler
serverInjection.cleanupAll();
hasClosed = true;
playerInjection.clear();
connectionLookup.clear();
invoker = null;
}
}
| [
"[email protected]"
] | |
6d1d2d965711e81f1b811cf2263c2d94e21ea025 | bde8d7184fa1cd3dee1c5fe2e7a3985ab2f3ad1a | /src/string/Print1ToMaxOfNDigits.java | 722fd27bfcbda40682ea9c610a47044cf3a7e2c5 | [] | no_license | chenlihuang/RealTest | ad2befcd47b51cfd18918b57eeabfde2cd23ba00 | 7e46e653d66634839452a34beee40ee7a7495e32 | refs/heads/master | 2021-09-30T23:44:24.207754 | 2018-11-26T02:33:27 | 2018-11-26T02:33:27 | 100,439,325 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,616 | java | package string;
/**
* 打印从1到最大的n位数,在字符串上模拟加法.
*/
public class Print1ToMaxOfNDigits {
public static void print1ToMaxOfNDigits(int num) {
if (num <= 0) {
return;
}
StringBuilder number = new StringBuilder(num);
for (int i = 0; i < num; i++) { //将字符串各位初始化为0
number.append('0');
}
while (increment(number)) {
printNumber(number);
}
}
/**
* 加一.
*
* @param str 字符串
* @return 字符串实现加一后
*/
public static boolean increment(StringBuilder str) {
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) < '9' && str.charAt(i) >= '0') {
str.setCharAt(i, (char) (str.charAt(i) + 1));
return true;
} else if (str.charAt(i) == '9') {
str.setCharAt(i, '0');
} else {
return false;
}
}
return false;
}
/**
* 输出字符串代表的数字.
* @param number 字符串
*/
public static void printNumber(StringBuilder number) {
boolean flag = false; //判断哪一位为开始位,比如输入为4,0012,需要判断输出为12,不是0012
for (int i = 0; i < number.length(); i++) {
if (flag) {
System.out.print(number.charAt(i));
} else {
if (number.charAt(i) != '0') {
flag = true;
System.out.print(number.charAt(i));
}
}
}
System.out.println();
}
/**
* 主程序入口.
*
* @param args 命令行输入传入
*/
public static void main(String[] args) {
print1ToMaxOfNDigits(2);
}
}
| [
"[email protected]"
] | |
86048263c0e8ae7c0cffafa9f706e91e366f0fce | 8d81f776e5e9d05508238e363a7510923bc796a1 | /src/main/general/gui/GUIListTextElement.java | 06db3666950970634928343277835b09b8f99f58 | [] | no_license | Itschotsch/BaschtelGame | b119839ab953eb3a70a4b1c6a69d6159d8773710 | 3fabc754123fcf3e480be295f514093cb1357454 | refs/heads/master | 2021-01-25T04:35:30.942305 | 2017-06-06T01:31:43 | 2017-06-06T01:31:43 | 93,451,007 | 0 | 0 | null | 2017-06-05T22:01:33 | 2017-06-05T22:01:33 | null | UTF-8 | Java | false | false | 2,008 | java | package main.general.gui;
import org.lwjgl.util.vector.Matrix4f;
import main.engine.graphics.geometry.G;
import main.engine.graphics.shaders.Shaders;
import main.general.S;
public class GUIListTextElement extends GUIListElement {
String text;
float textX, textY;
int padding;
public GUIListTextElement(GUIListTextElement other) {
super(other);
this.text = other.text;
this.textX = other.textX;
this.textY = other.textY;
this.padding = other.padding;
}
public GUIListTextElement(String text) {
super(text);
}
public GUIListTextElement(Object value) {
super(value);
}
public GUIListTextElement(Object... values) {
super(values);
}
protected void init(String text) {
this.text = text;
this.padding = S.uX(0.01f);
this.textX = this.padding;
this.textY = (this.getHeight() - S.getSmallStringHeight() * 0.65f) / 2f + S.getSmallStringHeight() * 0.65f;
}
@Override
public void setValues(Object... valueArray) {
this.init(valueArray[0].toString());
}
@Override
public Object[] getValues() {
return new String[]{this.text};
}
@Override
public float getHeight() {
return S.getSmallStringHeight() + 2 * padding;
}
@Override
public void updateInput(int i) {
}
@Override
public void update(int i) {
}
@Override
public void render(int i, float x, float y, float width, float height, Matrix4f projectionMatrix, Matrix4f viewMatrix) {
Shaders.bindColorGUI();
Shaders.getCurrentlyBoundShader().passProjectionMatrix(projectionMatrix);
Shaders.getCurrentlyBoundShader().passViewMatrix(viewMatrix);
if (this.selected == true) {
S.foregroundColor4.bind();
} else if (i % 2 == 0) {
S.foregroundColor1.bind();
} else {
S.foregroundColor2.bind();
}
G.drawColoredQuad(x, y, width, height);
Shaders.unbind();
S.drawSmallString(this.text, x + this.textX, y + this.textY);
}
public GUIListTextElement copy() {
GUIListTextElement element = new GUIListTextElement(this);
return element;
}
}
| [
"[email protected]"
] | |
5f9decbc4e73c5c898997b17ff68bf47b1f6142e | 363c936f4a89b7d3f5f4fb588e8ca20c527f6022 | /AL-Game/src/com/aionemu/gameserver/network/aion/serverpackets/SM_BLOCK_RESPONSE.java | 6b39ad545987d766a5b4b8005634e6f627072947 | [] | no_license | G-Robson26/AionServer-4.9F | d628ccb4307aa0589a70b293b311422019088858 | 3376c78b8d90bd4d859a7cfc25c5edc775e51cbf | refs/heads/master | 2023-09-04T00:46:47.954822 | 2017-08-09T13:23:03 | 2017-08-09T13:23:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,167 | java | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.network.aion.serverpackets;
import com.aionemu.gameserver.network.aion.AionConnection;
import com.aionemu.gameserver.network.aion.AionServerPacket;
/**
* Responses to block list related requests
*
* @author Ben
*/
public class SM_BLOCK_RESPONSE extends AionServerPacket {
/**
* You have blocked %0
*/
public static final int BLOCK_SUCCESSFUL = 0;
/**
* You have unblocked %0
*/
public static final int UNBLOCK_SUCCESSFUL = 1;
/**
* That character does not exist.
*/
public static final int TARGET_NOT_FOUND = 2;
/**
* Your Block List is full.
*/
public static final int LIST_FULL = 3;
/**
* You cannot block yourself.
*/
public static final int CANT_BLOCK_SELF = 4;
private int code;
private String playerName;
/**
* Constructs a new block request response packet
*
* @param code Message code to use - see class constants
* @param playerName Parameters inserted into message. Usually the target
* player's name
*/
public SM_BLOCK_RESPONSE(int code, String playerName) {
this.code = code;
this.playerName = playerName;
}
@Override
protected void writeImpl(AionConnection con) {
writeS(playerName);
writeD(code);
}
}
| [
"falke34@a70f7278-c47d-401d-a0e4-c9401b7f63ed"
] | falke34@a70f7278-c47d-401d-a0e4-c9401b7f63ed |
3f9b1c000637dc2da5eff061b45f87d6259e37b1 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/28/28_6d1103c461d718bd207456a1548dcd04bee6e5aa/Utils/28_6d1103c461d718bd207456a1548dcd04bee6e5aa_Utils_s.java | 0a231738628919dbfeed1110083ed15482b30667 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 20,129 | java | /*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import java.awt.RenderingHints;
import java.io.*;
import java.nio.*;
import java.util.prefs.*;
import java.util.*;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.image.BufferedImage;
public class Utils {
public static final java.nio.charset.Charset utf8 = java.nio.charset.Charset.forName("UTF-8");
public static final java.nio.charset.Charset ascii = java.nio.charset.Charset.forName("US-ASCII");
public static final java.awt.image.ColorModel rgbm = java.awt.image.ColorModel.getRGBdefault();
private static Preferences prefs = null;
private static Background bgworker = null;
static Coord imgsz(BufferedImage img) {
return(new Coord(img.getWidth(), img.getHeight()));
}
public static class Background extends HackThread {
Queue<Runnable> q = new LinkedList<Runnable>();
public Background() {
super("Haven deferred procedure thread");
setDaemon(true);
start();
}
public void run() {
try {
while(true) {
Runnable cur;
synchronized(q) {
while((cur = q.poll()) == null)
q.wait();
}
cur.run();
cur = null;
}
} catch(InterruptedException e) {}
}
public void defer(Runnable r) {
synchronized(q) {
q.add(r);
q.notify();
}
}
}
public static void defer(Runnable r) {
synchronized(Utils.class) {
if(bgworker == null)
bgworker = new Background();
}
bgworker.defer(r);
}
static void drawgay(BufferedImage t, BufferedImage img, Coord c) {
Coord sz = imgsz(img);
for(int y = 0; y < sz.y; y++) {
for(int x = 0; x < sz.x; x++) {
int p = img.getRGB(x, y);
if(Utils.rgbm.getAlpha(p) > 128) {
if((p & 0x00ffffff) == 0x00ff0080)
t.setRGB(x + c.x, y + c.y, 0);
else
t.setRGB(x + c.x, y + c.y, p);
}
}
}
}
public static int drawtext(Graphics g, String text, Coord c) {
java.awt.FontMetrics m = g.getFontMetrics();
g.drawString(text, c.x, c.y + m.getAscent());
return(m.getHeight());
}
static Coord textsz(Graphics g, String text) {
java.awt.FontMetrics m = g.getFontMetrics();
java.awt.geom.Rectangle2D ts = m.getStringBounds(text, g);
return(new Coord((int)ts.getWidth(), (int)ts.getHeight()));
}
static void aligntext(Graphics g, String text, Coord c, double ax, double ay) {
java.awt.FontMetrics m = g.getFontMetrics();
java.awt.geom.Rectangle2D ts = m.getStringBounds(text, g);
g.drawString(text, (int)(c.x - ts.getWidth() * ax), (int)(c.y + m.getAscent() - ts.getHeight() * ay));
}
static void line(Graphics g, Coord c1, Coord c2) {
g.drawLine(c1.x, c1.y, c2.x, c2.y);
}
static void AA(Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
static synchronized Preferences prefs() {
if(prefs == null) {
Preferences node = Preferences.userNodeForPackage(Utils.class);
if(Config.prefspec != null)
node = node.node(Config.prefspec);
prefs = node;
}
return(prefs);
}
static String getpref(String prefname, String def) {
try {
return(prefs().get(prefname, def));
} catch(SecurityException e) {
return(def);
}
}
static void setpref(String prefname, String val) {
try {
prefs().put(prefname, val);
} catch(SecurityException e) {
}
}
static boolean getprefb(String prefname, boolean def) {
try {
return(prefs().getBoolean(prefname, def));
} catch(SecurityException e) {
return(def);
}
}
static void setprefb(String prefname, boolean val) {
try {
prefs().putBoolean(prefname, val);
} catch(SecurityException e) {
}
}
static Coord getprefc(String prefname, Coord def) {
try {
String val = prefs().get(prefname, null);
if(val == null)
return(def);
int x = val.indexOf('x');
if(x < 0)
return(def);
return(new Coord(Integer.parseInt(val.substring(0, x)), Integer.parseInt(val.substring(x + 1))));
} catch(SecurityException e) {
return(def);
}
}
static void setprefc(String prefname, Coord val) {
try {
prefs().put(prefname, val.x + "x" + val.y);
} catch(SecurityException e) {
}
}
static byte[] getprefb(String prefname, byte[] def) {
try {
return(prefs().getByteArray(prefname, def));
} catch(SecurityException e) {
return(def);
}
}
static void setprefb(String prefname, byte[] val) {
try {
prefs().putByteArray(prefname, val);
} catch(SecurityException e) {
}
}
public static String getprop(String propname, String def) {
try {
return(System.getProperty(propname, def));
} catch(SecurityException e) {
return(def);
}
}
static int ub(byte b) {
if(b < 0)
return(256 + b);
else
return(b);
}
static byte sb(int b) {
if(b > 127)
return((byte)(-256 + b));
else
return((byte)b);
}
static int uint16d(byte[] buf, int off) {
return(ub(buf[off]) + (ub(buf[off + 1]) * 256));
}
static int int16d(byte[] buf, int off) {
int u = uint16d(buf, off);
if(u > 32767)
return(-65536 + u);
else
return(u);
}
static long uint32d(byte[] buf, int off) {
return(ub(buf[off]) + (ub(buf[off + 1]) * 256) + (ub(buf[off + 2]) * 65536) + (ub(buf[off + 3]) * 16777216l));
}
static void uint32e(long num, byte[] buf, int off) {
buf[off] = sb((int)(num & 0xff));
buf[off + 1] = sb((int)((num & 0xff00) >> 8));
buf[off + 2] = sb((int)((num & 0xff0000) >> 16));
buf[off + 3] = sb((int)((num & 0xff000000) >> 24));
}
static int int32d(byte[] buf, int off) {
long u = uint32d(buf, off);
if(u > 0x7fffffffL)
return((int)(u - 0x100000000L));
else
return((int)u);
}
public static long int64d(byte[] buf, int off) {
long b = 0;
for(int i = 0; i < 7; i++)
b |= ((long)ub(buf[i])) << (i * 8);
int h = ub(buf[7]);
if(h < 128)
return(b | ((long)h << 56));
else
return(0L + ((long)(-255 + h) * 0x0100000000000000L) + (-0x0100000000000000L + b));
}
static void int32e(int num, byte[] buf, int off) {
if(num < 0)
uint32e(0x100000000L + ((long)num), buf, off);
else
uint32e(num, buf, off);
}
static void uint16e(int num, byte[] buf, int off) {
buf[off] = sb(num & 0xff);
buf[off + 1] = sb((num & 0xff00) >> 8);
}
static String strd(byte[] buf, int[] off) {
int i;
for(i = off[0]; buf[i] != 0; i++);
String ret;
try {
ret = new String(buf, off[0], i - off[0], "utf-8");
} catch(UnsupportedEncodingException e) {
throw(new IllegalArgumentException(e));
}
off[0] = i + 1;
return(ret);
}
static double floatd(byte[] buf, int off) {
int e = buf[off];
long t = uint32d(buf, off + 1);
int m = (int)(t & 0x7fffffffL);
boolean s = (t & 0x80000000L) != 0;
if(e == -128) {
if(m == 0)
return(0.0);
throw(new RuntimeException("Invalid special float encoded (" + m + ")"));
}
double v = (((double)m) / 2147483648.0) + 1.0;
if(s)
v = -v;
return(Math.pow(2.0, e) * v);
}
static char num2hex(int num) {
if(num < 10)
return((char)('0' + num));
else
return((char)('A' + num - 10));
}
static int hex2num(char hex) {
if((hex >= '0') && (hex <= '9'))
return(hex - '0');
else if((hex >= 'a') && (hex <= 'f'))
return(hex - 'a' + 10);
else if((hex >= 'A') && (hex <= 'F'))
return(hex - 'A' + 10);
else
throw(new IllegalArgumentException());
}
static String byte2hex(byte[] in) {
StringBuilder buf = new StringBuilder();
for(byte b : in) {
buf.append(num2hex((b & 0xf0) >> 4));
buf.append(num2hex(b & 0x0f));
}
return(buf.toString());
}
static byte[] hex2byte(String hex) {
if(hex.length() % 2 != 0)
throw(new IllegalArgumentException("Invalid hex-encoded string"));
byte[] ret = new byte[hex.length() / 2];
for(int i = 0, o = 0; i < hex.length(); i += 2, o++)
ret[o] = (byte)((hex2num(hex.charAt(i)) << 4) | hex2num(hex.charAt(i + 1)));
return(ret);
}
public static String[] splitwords(String text) {
ArrayList<String> words = new ArrayList<String>();
StringBuilder buf = new StringBuilder();
String st = "ws";
int i = 0;
while(i < text.length()) {
char c = text.charAt(i);
if(st == "ws") {
if(!Character.isWhitespace(c))
st = "word";
else
i++;
} else if(st == "word") {
if(c == '"') {
st = "quote";
i++;
} else if(c == '\\') {
st = "squote";
i++;
} else if(Character.isWhitespace(c)) {
words.add(buf.toString());
buf = new StringBuilder();
st = "ws";
} else {
buf.append(c);
i++;
}
} else if(st == "quote") {
if(c == '"') {
st = "word";
i++;
} else if(c == '\\') {
st = "sqquote";
i++;
} else {
buf.append(c);
i++;
}
} else if(st == "squote") {
buf.append(c);
i++;
st = "word";
} else if(st == "sqquote") {
buf.append(c);
i++;
st = "quote";
}
}
if(st == "word")
words.add(buf.toString());
if((st != "ws") && (st != "word"))
return(null);
return(words.toArray(new String[0]));
}
public static String[] splitlines(String text) {
ArrayList<String> ret = new ArrayList<String>();
int p = 0;
while(true) {
int p2 = text.indexOf('\n', p);
if(p2 < 0) {
ret.add(text.substring(p));
break;
}
ret.add(text.substring(p, p2));
p = p2 + 1;
}
return(ret.toArray(new String[0]));
}
static int atoi(String a) {
try {
return(Integer.parseInt(a));
} catch(NumberFormatException e) {
return(0);
}
}
static void readtileof(InputStream in) throws IOException {
byte[] buf = new byte[4096];
while(true) {
if(in.read(buf, 0, buf.length) < 0)
return;
}
}
static byte[] readall(InputStream in) throws IOException {
byte[] buf = new byte[4096];
int off = 0;
while(true) {
if(off == buf.length) {
byte[] n = new byte[buf.length * 2];
System.arraycopy(buf, 0, n, 0, buf.length);
buf = n;
}
int ret = in.read(buf, off, buf.length - off);
if(ret < 0) {
byte[] n = new byte[off];
System.arraycopy(buf, 0, n, 0, off);
return(n);
}
off += ret;
}
}
private static void dumptg(ThreadGroup tg, PrintWriter out, int indent) {
for(int o = 0; o < indent; o++)
out.print(" ");
out.println("G: \"" + tg.getName() + "\"");
Thread[] ths = new Thread[tg.activeCount() * 2];
ThreadGroup[] tgs = new ThreadGroup[tg.activeGroupCount() * 2];
int nt = tg.enumerate(ths, false);
int ng = tg.enumerate(tgs, false);
for(int i = 0; i < nt; i++) {
Thread ct = ths[i];
for(int o = 0; o < indent + 1; o++)
out.print(" ");
out.println("T: \"" + ct.getName() + "\"");
}
for(int i = 0; i < ng; i++) {
ThreadGroup cg = tgs[i];
dumptg(cg, out, indent + 1);
}
}
public static void dumptg(ThreadGroup tg, PrintWriter out) {
if(tg == null) {
tg = Thread.currentThread().getThreadGroup();
while(tg.getParent() != null)
tg = tg.getParent();
}
dumptg(tg, out, 0);
out.flush();
}
public static Resource myres(Class<?> c) {
ClassLoader cl = c.getClassLoader();
if(cl instanceof Resource.ResClassLoader) {
return(((Resource.ResClassLoader)cl).getres());
} else {
return(null);
}
}
public static String titlecase(String str) {
return(Character.toTitleCase(str.charAt(0)) + str.substring(1));
}
public static Color contrast(Color col) {
int max = Math.max(col.getRed(), Math.max(col.getGreen(), col.getBlue()));
if(max > 128) {
return(new Color(col.getRed() / 2, col.getGreen() / 2, col.getBlue() / 2, col.getAlpha()));
} else if(max == 0) {
return(Color.WHITE);
} else {
int f = 128 / max;
return(new Color(col.getRed() * f, col.getGreen() * f, col.getBlue() * f, col.getAlpha()));
}
}
public static Color clipcol(int r, int g, int b, int a) {
if(r < 0) r = 0;
if(r > 255) r = 255;
if(g < 0) g = 0;
if(g > 255) g = 255;
if(b < 0) b = 0;
if(b > 255) b = 255;
if(a < 0) a = 0;
if(a > 255) a = 255;
return(new Color(r, g, b, a));
}
public static BufferedImage outline(BufferedImage img, Color col) {
Coord sz = imgsz(img).add(2, 2);
BufferedImage ol = TexI.mkbuf(sz);
for(int y = 0; y < sz.y; y++) {
for(int x = 0; x < sz.x; x++) {
boolean t;
if((y == 0) || (x == 0) || (y == sz.y - 1) || (x == sz.x - 1)) {
t = true;
} else {
int cl = img.getRGB(x - 1, y - 1);
t = Utils.rgbm.getAlpha(cl) < 250;
}
if(!t)
continue;
if(((x > 1) && (y > 0) && (y < sz.y - 1) && (Utils.rgbm.getAlpha(img.getRGB(x - 2, y - 1)) >= 250)) ||
((x > 0) && (y > 1) && (x < sz.x - 1) && (Utils.rgbm.getAlpha(img.getRGB(x - 1, y - 2)) >= 250)) ||
((x < sz.x - 2) && (y > 0) && (y < sz.y - 1) && (Utils.rgbm.getAlpha(img.getRGB(x, y - 1)) >= 250)) ||
((x > 0) && (y < sz.y - 2) && (x < sz.x - 1) && (Utils.rgbm.getAlpha(img.getRGB(x - 1, y)) >= 250)))
ol.setRGB(x, y, col.getRGB());
}
}
return(ol);
}
public static BufferedImage outline2(BufferedImage img, Color col) {
BufferedImage ol = outline(img, col);
Graphics g = ol.getGraphics();
g.drawImage(img, 1, 1, null);
g.dispose();
return(ol);
}
public static BufferedImage monochromize(BufferedImage img, Color col) {
Coord sz = imgsz(img);
BufferedImage ret = TexI.mkbuf(sz);
int[] ob = new int[4];
for(int y = 0; y < sz.y; y++) {
for(int x = 0; x < sz.x; x++) {
int px = img.getRGB(x, y);
int r = rgbm.getRed(px),
g = rgbm.getGreen(px),
b = rgbm.getBlue(px),
a = rgbm.getAlpha(px);
int max = Math.max(r, Math.max(g, b)),
min = Math.min(r, Math.min(g, b));
int val = (max + min) / 2;
ob[0] = (col.getRed() * val) / 255;
ob[1] = (col.getGreen() * val) / 255;
ob[2] = (col.getBlue() * val) / 255;
ob[3] = a;
ret.setRGB(x, y, rgbm.getDataElement(ob, 0));
}
}
return(ret);
}
public static int floordiv(int a, int b) {
if(a < 0)
return(((a + 1) / b) - 1);
else
return(a / b);
}
public static int floormod(int a, int b) {
int r = a % b;
if(r < 0)
r += b;
return(r);
}
public static int floordiv(float a, float b) {
return((int)Math.floor(a / b));
}
public static float floormod(float a, float b) {
float r = a % b;
if(r < 0)
r += b;
return(r);
}
public static double clip(double d, double min, double max) {
if(d < min)
return(min);
if(d > max)
return(max);
return(d);
}
public static int clip(int i, int min, int max) {
if(i < min)
return(min);
if(i > max)
return(max);
return(i);
}
public static Color blendcol(Color in, Color bl) {
int f1 = bl.getAlpha();
int f2 = 255 - bl.getAlpha();
return(new Color(((in.getRed() * f2) + (bl.getRed() * f1)) / 255,
((in.getGreen() * f2) + (bl.getGreen() * f1)) / 255,
((in.getBlue() * f2) + (bl.getBlue() * f1)) / 255,
in.getAlpha()));
}
public static void serialize(Object obj, OutputStream out) throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(obj);
oout.flush();
}
public static byte[] serialize(Object obj) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
serialize(obj, out);
} catch(IOException e) {
throw(new RuntimeException(e));
}
return(out.toByteArray());
}
public static Object deserialize(InputStream in) throws IOException {
ObjectInputStream oin = new ObjectInputStream(in);
try {
return(oin.readObject());
} catch(ClassNotFoundException e) {
return(null);
}
}
public static Object deserialize(byte[] buf) {
if(buf == null)
return(null);
InputStream in = new ByteArrayInputStream(buf);
try {
return(deserialize(in));
} catch(IOException e) {
return(null);
}
}
public static boolean parsebool(String s, boolean def) {
if(s == null)
return(def);
else if(s.equalsIgnoreCase("1") || s.equalsIgnoreCase("on") || s.equalsIgnoreCase("true") || s.equalsIgnoreCase("yes"))
return(true);
else if(s.equalsIgnoreCase("0") || s.equalsIgnoreCase("off") || s.equalsIgnoreCase("false") || s.equalsIgnoreCase("no"))
return(false);
return(def);
}
/* Just in case anyone doubted that Java is stupid. :-/ */
public static FloatBuffer bufcp(float[] a) {
FloatBuffer b = mkfbuf(a.length);
b.put(a);
b.rewind();
return(b);
}
public static ShortBuffer bufcp(short[] a) {
ShortBuffer b = mksbuf(a.length);
b.put(a);
b.rewind();
return(b);
}
public static FloatBuffer mkfbuf(int n) {
return(ByteBuffer.allocateDirect(n * 4).order(ByteOrder.nativeOrder()).asFloatBuffer());
}
public static ShortBuffer mksbuf(int n) {
return(ByteBuffer.allocateDirect(n * 2).order(ByteOrder.nativeOrder()).asShortBuffer());
}
public static IntBuffer mkibuf(int n) {
return(ByteBuffer.allocateDirect(n * 4).order(ByteOrder.nativeOrder()).asIntBuffer());
}
public static float[] c2fa(Color c) {
return(new float[] {
((float)c.getRed() / 255.0f),
((float)c.getGreen() / 255.0f),
((float)c.getBlue() / 255.0f),
((float)c.getAlpha() / 255.0f)
});
}
@SuppressWarnings("unchecked")
public static <T> T[] splice(T[] src, int off, int len) {
T[] dst = (T[])java.lang.reflect.Array.newInstance(src.getClass().getComponentType(), len);
System.arraycopy(src, off, dst, 0, len);
return(dst);
}
public static <T> T[] splice(T[] src, int off) {
return(splice(src, off, src.length - off));
}
static {
Console.setscmd("die", new Console.Command() {
public void run(Console cons, String[] args) {
throw(new Error("Triggered death"));
}
});
Console.setscmd("threads", new Console.Command() {
public void run(Console cons, String[] args) {
Utils.dumptg(null, cons.out);
}
});
Console.setscmd("gc", new Console.Command() {
public void run(Console cons, String[] args) {
System.gc();
}
});
}
}
| [
"[email protected]"
] | |
2786a51b0582b30a1a86c726a789a477cfff05c1 | 8de393ed3cf3a3a4583d902f697c9ab3eb4d1528 | /src/test/java/com/Pierrot31/insa/PackageMust.java | 430b2ba8c976c4fada85cbb2c9b8d83d02522084 | [] | no_license | Pierrot31/calclatorprice | f70d38cca8ed62d87b6387a1e4167dce0c0a35c4 | 3d255ac1358c3c0932644522e512092f809a4f05 | refs/heads/master | 2021-08-15T23:28:38.225608 | 2017-11-18T14:41:25 | 2017-11-18T14:41:25 | 111,189,127 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,328 | java | package com.Pierrot31.insa;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static com.Pierrot31.insa.Test.testParameters;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
public class PackageMust {
private ByteArrayOutputStream out;
@Before
public void setUp(){
out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
}
@Test
public void premiereLigne(){
Object [ ] laPremiereLigneDuTableau = testParameters[0];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
Double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
Destination laDestination= Destination.valueOf(laDestinationAsText);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage, laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
String nbArrondi = df.format(calculate);
System.out.print(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
@Test
public void deuxiemeLigne(){
Object [ ] laPremiereLigneDuTableau = testParameters[1];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
Double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
Destination laDestination= Destination.valueOf(laDestinationAsText);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage,laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
String nbArrondi = df.format(calculate);
System.out.println(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
@Test
public void troisièmeLigne(){
Object [ ] laPremiereLigneDuTableau = testParameters[2];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
Double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
Destination laDestination= Destination.valueOf(laDestinationAsText);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage,laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
String nbArrondi = df.format(calculate);
System.out.println(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
@Test
public void quatrièmeLigne(){
Object [ ] laPremiereLigneDuTableau = testParameters[3];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
Double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
Destination laDestination= Destination.valueOf(laDestinationAsText);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage, laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
String nbArrondi = df.format(calculate);
System.out.println(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
@Test
public void cinquiemeLigne(){
Object [ ] laPremiereLigneDuTableau = testParameters[4];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
Destination laDestination= Destination.valueOf(laDestinationAsText);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage,laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
String nbArrondi = df.format(calculate);
System.out.println(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
@Test
public void sixiemeLigne(){
Object [ ] laPremiereLigneDuTableau = testParameters[5];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
Double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
Destination laDestination= Destination.valueOf(laDestinationAsText);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage,laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
String nbArrondi = df.format(calculate);
System.out.println(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
@Test
public void septiemeLigne(){
Object [ ] laPremiereLigneDuTableau = testParameters[6];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
Double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
Destination laDestination= Destination.valueOf(laDestinationAsText);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage,laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
String nbArrondi = df.format(calculate);
System.out.println(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
@Test
public void huitiemeLigne(){
Object [] laPremiereLigneDuTableau = testParameters[7];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
Double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
Destination laDestination= Destination.valueOf(laDestinationAsText);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage,laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
String nbArrondi = df.format(calculate);
System.out.println(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
@Test
public void neuviemeLigne(){
Object [ ] laPremiereLigneDuTableau = testParameters[8];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
Double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
String[] part = laDestinationAsText.split("/");
Destination laDestination= Destination.valueOf(part[0]+"_"+part[1]);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage,laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
String nbArrondi = df.format(calculate);
System.out.println(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
@Test
public void dixiemeLigne(){
Object [ ] laPremiereLigneDuTableau = testParameters[9];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
Double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
String[] part = laDestinationAsText.split("/");
Destination laDestination= Destination.valueOf(part[0]+"_"+part[1]);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage,laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
String nbArrondi = df.format(calculate);
System.out.println(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
@Test
public void onziemeLigne(){
Object [ ] laPremiereLigneDuTableau = testParameters[10];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
Double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
String[] part = laDestinationAsText.split("/");
Destination laDestination= Destination.valueOf(part[0]+"_"+part[1]);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage,laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
String nbArrondi = df.format(calculate);
System.out.println(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
@Test
public void douziemeLigne(){
Object [ ] laPremiereLigneDuTableau = testParameters[11];
String laLongueurAsText = laPremiereLigneDuTableau[0].toString();
int laLongueur = Integer.parseInt(laLongueurAsText);
String laProfondeurAsText = laPremiereLigneDuTableau[2].toString();
int laProfondeur = Integer.parseInt(laProfondeurAsText);
String laLargeurAsText = laPremiereLigneDuTableau[1].toString();
int laLargeur = Integer.parseInt(laLargeurAsText);
String lePoidsAsText = laPremiereLigneDuTableau[3].toString();
Double lePoids = Double.parseDouble(lePoidsAsText);
String laDestinationAsText = laPremiereLigneDuTableau[4].toString();
String[] part = laDestinationAsText.split("/");
Destination laDestination= Destination.valueOf(part[0]+"_"+part[1]);
String lePrixAsText = laPremiereLigneDuTableau[5].toString();
PackageFactory paquetAtester = new PackageFactory(laLongueur,laProfondeur,laLargeur,lePoids);
ShippingCostsCalculator scc = new ShippingCostsCalculator();
double calculate = scc.calculateShippingCost(paquetAtester.monPackage,laDestination);
java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
String nbArrondi = df.format(calculate);
System.out.println(nbArrondi);
String expectedOutput = lePrixAsText ;
assertThat(standardOutput(), containsString(expectedOutput));
}
private String standardOutput(){
return out.toString();
}
} | [
"[email protected]"
] | |
3bc2967d20241e4309a5b1a2256ab15e6ad24f10 | ace04f3c1212faffa2d4871204a11d647b304560 | /src/javaai/ann/output/EquilateralEncoding.java | 93245fba8e11c35af9c46cea4484816b215909e1 | [] | no_license | timhoangt/Artificial-Intelligence | 26afe814b1f299d9d1d4e6db6345e548bf2348c4 | e92216664644f616f637bf0e304bc768be6465b1 | refs/heads/master | 2023-02-05T06:16:02.365537 | 2020-12-27T22:52:57 | 2020-12-27T22:52:57 | 323,194,715 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,075 | java | /*
Copyright (c) Ron Coleman
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package javaai.ann.output;
import org.encog.mathutil.Equilateral;
import javaai.util.Helper;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This code demonstrates how to use equilateral encoding with the Iris data.
* See Heaton (2011), d.25-27 for more details.
* @author Ron.Coleman
*/
public class EquilateralEncoding {
/** Equilateral encoder */
public static Equilateral eq = null;
/** Nominal subtypes */
static List<String> subtypes = null;
/**
* Launch point for program.
* @param args Command line arguments.
*/
public static void main(String[] args) {
// Load the data
load();
// Output ideal values nominal as point in 2D (or subtypes.size()-1) hyperspace
for (int index = 0; index < subtypes.size(); index++) {
String subtype = subtypes.get(index);
System.out.print(subtype + ": {");
double[] encoding = eq.encode(index);
for (int k = 0; k < encoding.length; k++) {
if (k > 0) {
System.out.print(", ");
}
System.out.printf("%5.4f", encoding[k]);
}
System.out.println("}");
}
}
/**
* Loads the iris data with a default path.
*/
public static void load() {
EquilateralEncoding.load("iris.csv");
}
/**
* Loads the iris data at a specified path.
* @param path Path
*/
public static void load(String path) {
try {
// Load the data
Helper.loadCsv("iris.csv", Ontology.parsers);
// Use equilateral encoding for [-1, 1] range for TANH activation function.
subtypes = Helper.getNominalSubtypes(4);
eq = new Equilateral(subtypes.size(), 1, -1);
} catch (Exception ex) {
Logger.getLogger(EquilateralEncoding.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| [
"[email protected]"
] | |
af42af4c08fd59c3a6606f7d9b1cb6888be5788a | 53674648a97015aaff39485eea7cfd684f8f0b70 | /src/test/java/com/mycompany/myapp/web/rest/TicketResourceIT.java | 45c75899997a17c4694d246c2c94d58881218256 | [] | no_license | holoduck/BugTrackerJHipster | 91f3703b14616fa6b59c153096423001aecd44b5 | d9107486104ebe85733e2de68ffea5cd2068028f | refs/heads/master | 2022-12-25T03:38:44.800002 | 2019-11-15T22:49:41 | 2019-11-15T22:49:41 | 219,331,251 | 0 | 0 | null | 2022-12-16T04:40:50 | 2019-11-03T16:33:53 | Java | UTF-8 | Java | false | false | 14,138 | java | package com.mycompany.myapp.web.rest;
import static com.mycompany.myapp.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Validator;
import com.mycompany.myapp.BugTrackerJHipsterApp;
import com.mycompany.myapp.domain.Ticket;
import com.mycompany.myapp.repository.TicketRepository;
import com.mycompany.myapp.web.rest.errors.ExceptionTranslator;
/**
* Integration tests for the {@link TicketResource} REST controller.
*/
@SpringBootTest(classes = BugTrackerJHipsterApp.class)
public class TicketResourceIT {
private static final String DEFAULT_TITLE = "AAAAAAAAAA";
private static final String UPDATED_TITLE = "BBBBBBBBBB";
private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA";
private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB";
private static final LocalDate DEFAULT_DUE_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DUE_DATE = LocalDate.now(ZoneId.systemDefault());
private static final Boolean DEFAULT_DONE = false;
private static final Boolean UPDATED_DONE = true;
@Autowired
private TicketRepository ticketRepository;
@Mock
private TicketRepository ticketRepositoryMock;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private Validator validator;
private MockMvc restTicketMockMvc;
private Ticket ticket;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
final TicketResource ticketResource = new TicketResource(ticketRepository);
this.restTicketMockMvc = MockMvcBuilders.standaloneSetup(ticketResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Ticket createEntity(EntityManager em) {
Ticket ticket = new Ticket()
.title(DEFAULT_TITLE)
.description(DEFAULT_DESCRIPTION)
.dueDate(DEFAULT_DUE_DATE)
.done(DEFAULT_DONE);
return ticket;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Ticket createUpdatedEntity(EntityManager em) {
Ticket ticket = new Ticket()
.title(UPDATED_TITLE)
.description(UPDATED_DESCRIPTION)
.dueDate(UPDATED_DUE_DATE)
.done(UPDATED_DONE);
return ticket;
}
@BeforeEach
public void initTest() {
ticket = createEntity(em);
}
@Test
@Transactional
public void createTicket() throws Exception {
int databaseSizeBeforeCreate = ticketRepository.findAll().size();
// Create the Ticket
restTicketMockMvc.perform(post("/api/tickets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(ticket)))
.andExpect(status().isCreated());
// Validate the Ticket in the database
List<Ticket> ticketList = ticketRepository.findAll();
assertThat(ticketList).hasSize(databaseSizeBeforeCreate + 1);
Ticket testTicket = ticketList.get(ticketList.size() - 1);
assertThat(testTicket.getTitle()).isEqualTo(DEFAULT_TITLE);
assertThat(testTicket.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
assertThat(testTicket.getDueDate()).isEqualTo(DEFAULT_DUE_DATE);
assertThat(testTicket.isDone()).isEqualTo(DEFAULT_DONE);
}
@Test
@Transactional
public void createTicketWithExistingId() throws Exception {
int databaseSizeBeforeCreate = ticketRepository.findAll().size();
// Create the Ticket with an existing ID
ticket.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restTicketMockMvc.perform(post("/api/tickets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(ticket)))
.andExpect(status().isBadRequest());
// Validate the Ticket in the database
List<Ticket> ticketList = ticketRepository.findAll();
assertThat(ticketList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkTitleIsRequired() throws Exception {
int databaseSizeBeforeTest = ticketRepository.findAll().size();
// set the field null
ticket.setTitle(null);
// Create the Ticket, which fails.
restTicketMockMvc.perform(post("/api/tickets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(ticket)))
.andExpect(status().isBadRequest());
List<Ticket> ticketList = ticketRepository.findAll();
assertThat(ticketList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllTickets() throws Exception {
// Initialize the database
ticketRepository.saveAndFlush(ticket);
// Get all the ticketList
restTicketMockMvc.perform(get("/api/tickets?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(ticket.getId().intValue())))
.andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE)))
.andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION)))
.andExpect(jsonPath("$.[*].dueDate").value(hasItem(DEFAULT_DUE_DATE.toString())))
.andExpect(jsonPath("$.[*].done").value(hasItem(DEFAULT_DONE.booleanValue())));
}
@SuppressWarnings({"unchecked"})
public void getAllTicketsWithEagerRelationshipsIsEnabled() throws Exception {
TicketResource ticketResource = new TicketResource(ticketRepositoryMock);
when(ticketRepositoryMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));
MockMvc restTicketMockMvc = MockMvcBuilders.standaloneSetup(ticketResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
restTicketMockMvc.perform(get("/api/tickets?eagerload=true"))
.andExpect(status().isOk());
verify(ticketRepositoryMock, times(1)).findAllWithEagerRelationships(any());
}
@SuppressWarnings({"unchecked"})
public void getAllTicketsWithEagerRelationshipsIsNotEnabled() throws Exception {
TicketResource ticketResource = new TicketResource(ticketRepositoryMock);
when(ticketRepositoryMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));
MockMvc restTicketMockMvc = MockMvcBuilders.standaloneSetup(ticketResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
restTicketMockMvc.perform(get("/api/tickets?eagerload=true"))
.andExpect(status().isOk());
verify(ticketRepositoryMock, times(1)).findAllWithEagerRelationships(any());
}
@Test
@Transactional
public void getTicket() throws Exception {
// Initialize the database
ticketRepository.saveAndFlush(ticket);
// Get the ticket
restTicketMockMvc.perform(get("/api/tickets/{id}", ticket.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(ticket.getId().intValue()))
.andExpect(jsonPath("$.title").value(DEFAULT_TITLE))
.andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION))
.andExpect(jsonPath("$.dueDate").value(DEFAULT_DUE_DATE.toString()))
.andExpect(jsonPath("$.done").value(DEFAULT_DONE.booleanValue()));
}
@Test
@Transactional
public void getNonExistingTicket() throws Exception {
// Get the ticket
restTicketMockMvc.perform(get("/api/tickets/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateTicket() throws Exception {
// Initialize the database
ticketRepository.saveAndFlush(ticket);
int databaseSizeBeforeUpdate = ticketRepository.findAll().size();
// Update the ticket
Ticket updatedTicket = ticketRepository.findById(ticket.getId()).get();
// Disconnect from session so that the updates on updatedTicket are not directly saved in db
em.detach(updatedTicket);
updatedTicket
.title(UPDATED_TITLE)
.description(UPDATED_DESCRIPTION)
.dueDate(UPDATED_DUE_DATE)
.done(UPDATED_DONE);
restTicketMockMvc.perform(put("/api/tickets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedTicket)))
.andExpect(status().isOk());
// Validate the Ticket in the database
List<Ticket> ticketList = ticketRepository.findAll();
assertThat(ticketList).hasSize(databaseSizeBeforeUpdate);
Ticket testTicket = ticketList.get(ticketList.size() - 1);
assertThat(testTicket.getTitle()).isEqualTo(UPDATED_TITLE);
assertThat(testTicket.getDescription()).isEqualTo(UPDATED_DESCRIPTION);
assertThat(testTicket.getDueDate()).isEqualTo(UPDATED_DUE_DATE);
assertThat(testTicket.isDone()).isEqualTo(UPDATED_DONE);
}
@Test
@Transactional
public void updateNonExistingTicket() throws Exception {
int databaseSizeBeforeUpdate = ticketRepository.findAll().size();
// Create the Ticket
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restTicketMockMvc.perform(put("/api/tickets")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(ticket)))
.andExpect(status().isBadRequest());
// Validate the Ticket in the database
List<Ticket> ticketList = ticketRepository.findAll();
assertThat(ticketList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteTicket() throws Exception {
// Initialize the database
ticketRepository.saveAndFlush(ticket);
int databaseSizeBeforeDelete = ticketRepository.findAll().size();
// Delete the ticket
restTicketMockMvc.perform(delete("/api/tickets/{id}", ticket.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<Ticket> ticketList = ticketRepository.findAll();
assertThat(ticketList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Ticket.class);
Ticket ticket1 = new Ticket();
ticket1.setId(1L);
Ticket ticket2 = new Ticket();
ticket2.setId(ticket1.getId());
assertThat(ticket1).isEqualTo(ticket2);
ticket2.setId(2L);
assertThat(ticket1).isNotEqualTo(ticket2);
ticket1.setId(null);
assertThat(ticket1).isNotEqualTo(ticket2);
}
}
| [
"[email protected]"
] | |
eb190d18a72c9007d3ebbba2d698b5f0a83c78a9 | 3335161952e693057f5d779ab065065e1cdb524d | /src/com/javaex/api/objectclass/v2/LangClassTest.java | 916c3bda355626598af39d77d6e5c732e5a83d1b | [] | no_license | Kangchanseok/JavaEx | 2c0e824bea657a315381eb0d3665271cedfb8130 | 84ff6b460d93184589ff476ec68953af891b6063 | refs/heads/master | 2023-07-03T18:31:44.981688 | 2021-08-11T15:09:32 | 2021-08-11T15:09:32 | 386,480,163 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 429 | java | package com.javaex.api.objectclass.v2;
public class LangClassTest {
public static void main(String[] args) {
Point p = new Point(10, 20);
Point p2 = new Point(10, 20);
System.out.println("p와 p2는 같은 객체? " + (p == p2));
// == 는 참조 주소 비교
// .equals() 는 내부 값의 비교
System.out.println("p와 p2는 같은 값을 가졌나용? " + (p.equals(p2)));
}
}
| [
"[email protected]"
] | |
2b4123b9020ae728041b1b442feb1b1f0428cc57 | b0546b01ebe1d6527d8d58ffac5bfd27f1919603 | /history/SoyoMaker2/SoyoMaker/src/com/soyomaker/dialog/event/gameperformance/ShowCountDownDialog.java | 8f81d86de22c7ddc63a23571d2c2e348b86681ad | [] | no_license | heroyuy/systar | b71da2e44a7a3733c53a45bd5d9dd84e4a13f039 | ebce6ef8b95ee969244dcce76ebd79d7f0353aca | refs/heads/master | 2021-01-10T10:42:59.250335 | 2012-10-15T14:46:36 | 2012-10-15T14:46:36 | 47,677,163 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,993 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* CountDialog.java
*
* Created on 2011-6-12, 20:35:13
*/
package com.soyomaker.dialog.event.gameperformance;
import com.soyomaker.dialog.ScriptDialog;
/**
*
* @author Administrator
*/
public class ShowCountDownDialog extends javax.swing.JDialog {
/** Creates new form CountDialog
* @param parent
* @param modal
*/
public ShowCountDownDialog(ScriptDialog parent, boolean modal) {
super(parent, modal);
sd = parent;
initComponents();
setLocationRelativeTo(null);
}
private ScriptDialog sd;
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
secTextField = new javax.swing.JTextField();
okButton = new javax.swing.JButton();
cancleButton = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
jLabel1.setText("倒计时");
jLabel1.setName("jLabel1"); // NOI18N
secTextField.setText("0");
secTextField.setName("secTextField"); // NOI18N
okButton.setText("确定");
okButton.setName("okButton"); // NOI18N
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
cancleButton.setText("取消");
cancleButton.setName("cancleButton"); // NOI18N
cancleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancleButtonActionPerformed(evt);
}
});
jLabel2.setText("ms");
jLabel2.setName("jLabel2"); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(secTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addComponent(okButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cancleButton)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(secTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(okButton)
.addComponent(cancleButton))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
// TODO add your handling code here:
sd.insertScriptData(sd.npcPane.eventTable.getSelectedRow(),
"globalData.proxy:showTimer(" + secTextField.getText() + ")");
dispose();
}//GEN-LAST:event_okButtonActionPerformed
private void cancleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancleButtonActionPerformed
// TODO add your handling code here:
dispose();
}//GEN-LAST:event_cancleButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ShowCountDownDialog dialog = new ShowCountDownDialog(null, true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancleButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JButton okButton;
private javax.swing.JTextField secTextField;
// End of variables declaration//GEN-END:variables
}
| [
"[email protected]"
] | |
854b6cf8233aae75ed0ffca241c7139cec1362d7 | 3a6f00b87343e60e24f586dae176bdf010b5dcae | /sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/network/generated/SecurityRulesGetSamples.java | 989abb90c77adf7675a2780eac7e44f44fc95805 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"CC0-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later"
] | permissive | RaviTella/azure-sdk-for-java | 4c3267ea7a3ef17ffef89621c8add0a8b7dc72cb | d82d70fde49071ee2cefb4a69621c680dfafc793 | refs/heads/main | 2022-04-26T21:11:08.604986 | 2022-04-11T07:03:32 | 2022-04-11T07:03:32 | 394,745,792 | 0 | 0 | MIT | 2021-09-13T15:03:34 | 2021-08-10T18:25:18 | Java | UTF-8 | Java | false | false | 1,005 | java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.generated;
import com.azure.core.util.Context;
/** Samples for SecurityRules Get. */
public final class SecurityRulesGetSamples {
/*
* x-ms-original-file: specification/network/resource-manager/Microsoft.Network/stable/2021-05-01/examples/NetworkSecurityGroupRuleGet.json
*/
/**
* Sample code: Get network security rule in network security group.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void getNetworkSecurityRuleInNetworkSecurityGroup(
com.azure.resourcemanager.AzureResourceManager azure) {
azure
.networks()
.manager()
.serviceClient()
.getSecurityRules()
.getWithResponse("rg1", "testnsg", "rule1", Context.NONE);
}
}
| [
"[email protected]"
] | |
335e08d313e8d17f99e154b6a32471b81df489f6 | 1fdb53b2f2950e4de6a632e232aa8a223af35ec9 | /app/src/main/java/com/rcdz/medianewsapp/model/bean/CannalSationBean.java | 85cf2c9afff95dbd0bc2e8a1ba05869812778626 | [] | no_license | WJT983049539/MediaNewsApp | 0615f3fe5530ec88ee60c58d35f736853d0376b5 | 74f44f5cc7065fe702596e26da8051851a9607b7 | refs/heads/master | 2023-02-03T04:22:29.228700 | 2020-12-21T09:03:17 | 2020-12-21T09:03:17 | 306,205,822 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,568 | java | package com.rcdz.medianewsapp.model.bean;
import java.io.Serializable;
import java.util.List;
/**
* 作用: 频道栏目List
*
* @author:create by wjt
* 邮箱 [email protected]
* time 2020/10/19 10:15
*/
public class CannalSationBean implements Serializable {
/**
* code : 200
* message : null
* status : 0
* msg : null
* total : 9
* rows : [{"Id":12,"Name":"高清频道","Description":"高清频道","OpenShard":1,"OpenComment":0,"OpenLikes":1,"CreateID":1,"Creator":"超级管理员","CreateDate":"2020-02-02 00:00:00"},{"Id":11,"Name":"本地频道","Description":"本地频道","OpenShard":1,"OpenComment":0,"OpenLikes":1,"CreateID":1,"Creator":"超级管理员","CreateDate":"2020-02-02 00:00:00"},{"Id":10,"Name":"精品回看","Description":"精品回看","OpenShard":1,"OpenComment":0,"OpenLikes":1,"CreateID":1,"Creator":"超级管理员","CreateDate":"2020-02-02 00:00:00"},{"Id":9,"Name":"专题报道","Description":"专题报道","OpenShard":1,"OpenComment":0,"OpenLikes":1,"CreateID":1,"Creator":"超级管理员","CreateDate":"2020-02-02 00:00:00"},{"Id":8,"Name":"闻喜新闻","Description":"闻喜新闻","OpenShard":1,"OpenComment":0,"OpenLikes":1,"CreateID":1,"Creator":"超级管理员","CreateDate":"2020-02-02 00:00:00"},{"Id":7,"Name":"纪录片","Description":"纪录片","OpenShard":1,"OpenComment":0,"OpenLikes":1,"CreateID":1,"Creator":"超级管理员","CreateDate":"2020-02-02 00:00:00"},{"Id":6,"Name":"独家V视","Description":"独家V视","OpenShard":1,"OpenComment":0,"OpenLikes":1,"CreateID":1,"Creator":"超级管理员","CreateDate":"2020-02-02 00:00:00"},{"Id":5,"Name":"精品点播","Description":"精品点播","OpenShard":1,"OpenComment":0,"OpenLikes":1,"CreateID":1,"Creator":"超级管理员","CreateDate":"2020-02-02 00:00:00"},{"Id":1,"Name":"TV直播","Description":"TV直播","OpenShard":1,"OpenComment":0,"OpenLikes":1,"CreateID":1,"Creator":"超级管理员","CreateDate":"2020-02-02 00:00:00"}]
* summary : null
* extra : null
*/
private int code;
private Object message;
private int status;
private Object msg;
private int total;
private Object summary;
private Object extra;
private List<CannelSation> rows;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getMessage() {
return message;
}
public void setMessage(Object message) {
this.message = message;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Object getMsg() {
return msg;
}
public void setMsg(Object msg) {
this.msg = msg;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public Object getSummary() {
return summary;
}
public void setSummary(Object summary) {
this.summary = summary;
}
public Object getExtra() {
return extra;
}
public void setExtra(Object extra) {
this.extra = extra;
}
public List<CannelSation> getRows() {
return rows;
}
public void setRows(List<CannelSation> rows) {
this.rows = rows;
}
public static class CannelSation implements Serializable{
/**
* Id : 12
* Name : 高清频道
* Description : 高清频道
* OpenShard : 1
* OpenComment : 0
* OpenLikes : 1
* CreateID : 1
* Creator : 超级管理员
* CreateDate : 2020-02-02 00:00:00
*/
private int Id;
private String Name;
private String Description;
private int OpenShard;
private int OpenComment;
private int OpenLikes;
private int CreateID;
private String Creator;
private String CreateDate;
public int getId() {
return Id;
}
public void setId(int Id) {
this.Id = Id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getDescription() {
return Description;
}
public void setDescription(String Description) {
this.Description = Description;
}
public int getOpenShard() {
return OpenShard;
}
public void setOpenShard(int OpenShard) {
this.OpenShard = OpenShard;
}
public int getOpenComment() {
return OpenComment;
}
public void setOpenComment(int OpenComment) {
this.OpenComment = OpenComment;
}
public int getOpenLikes() {
return OpenLikes;
}
public void setOpenLikes(int OpenLikes) {
this.OpenLikes = OpenLikes;
}
public int getCreateID() {
return CreateID;
}
public void setCreateID(int CreateID) {
this.CreateID = CreateID;
}
public String getCreator() {
return Creator;
}
public void setCreator(String Creator) {
this.Creator = Creator;
}
public String getCreateDate() {
return CreateDate;
}
public void setCreateDate(String CreateDate) {
this.CreateDate = CreateDate;
}
}
}
| [
"[email protected]"
] | |
dd11d3113a0fc08eef761552c88a21de88d846bb | 3b5a307b1f048ed1d0c2f4a965a8b69ad9b79bf5 | /Exoflight/src/com/fasterlight/exo/seq/TimeWaitNode.java | 9785c4c11cf9821281508118a206b17f2ad16ac7 | [] | no_license | himanshugoel2797/exoflight | 5f2ea8020f7341bc6019b4c4e8d1ab408378582c | 0bd18f87093708ae5ff7dfe12870d182d859db96 | refs/heads/master | 2021-01-10T10:00:37.777705 | 2008-05-03T13:27:28 | 2008-05-03T13:27:28 | 46,279,028 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,142 | java | /********************************************************************
Copyright (c) 2000-2008 Steven E. Hugg.
This file is part of Exoflight.
Exoflight is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Exoflight is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Exoflight. If not, see <http://www.gnu.org/licenses/>.
*********************************************************************/
package com.fasterlight.exo.seq;
import com.fasterlight.exo.orbit.*;
import com.fasterlight.game.*;
import com.fasterlight.spif.*;
public class TimeWaitNode
extends SequencerNode
{
public static final int RELATIVE = 0;
public static final int ABSOLUTE = 1;
public static final int DURATION = 2;
private long time, targettime;
private int mode;
private GameEvent event;
private PropertyEvaluator time_prop;
//
public TimeWaitNode(long time, int mode)
{
this.time = time;
this.mode = mode;
}
public TimeWaitNode(String propkey, int mode)
{
this.time_prop = new PropertyEvaluator(propkey);
this.mode = mode;
}
public long getTicks()
{
if (time_prop != null)
return AstroUtil.dbl2tick(PropertyUtil.toDouble(time_prop.get(this)));
else
return time;
}
protected void startNode()
{
long tt = getTicks();
switch (mode)
{
case DURATION: tt += seq.getGame().time(); break;
case RELATIVE: tt += seq.getZeroTime(); break;
}
// if time is in the past,
// reset sequence time and continue
long curtime = seq.getGame().time();
if (tt < curtime)
{
seq.setZeroTime(curtime - getTicks());
tt = curtime;
// todo: issue warning
}
event = new TimeWaitEvent(tt);
seq.getGame().postEvent(event);
if (seq.debug)
System.out.println(tt + ", " + event);
}
protected void stopNode()
{
seq.getGame().cancelEvent(event);
event = null;
}
//
class TimeWaitEvent
extends GameEvent
{
TimeWaitEvent(long time)
{
super(time);
}
public void handleEvent(Game game)
{
event = null;
notifySeq(SUCCESS);
}
}
public String toString()
{
String desc = super.toString();
double dt = time*1d/Constants.TICKS_PER_SEC;
if (time_prop != null)
{
return desc+" (wait for `" + time_prop + "`)";
} else {
switch (mode)
{
case RELATIVE:
return desc+" (wait until " + AstroUtil.toTimeHMS(time) + ")";
case DURATION:
return desc+" (wait for " + AstroUtil.toDuration(dt) + ")";
case ABSOLUTE:
return desc+" (wait until " + AstroUtil.formatDate(AstroUtil.gameTickToJavaDate(time)) + ")";
default:
return "?";
}
}
}
}
| [
"sehugg@05812258-7f48-0410-9316-dfcb6471b382"
] | sehugg@05812258-7f48-0410-9316-dfcb6471b382 |
887cd9e272938fb92934ee74fdcdc7529e805809 | c8608e7ebb6fecd3cc7f213510017967ad2f40da | /app/src/test/java/com/stackbuffers/doctor_patient_project/ExampleUnitTest.java | d8a4594da25f2dacbde5b0ee5cad2ea8c6b682a1 | [] | no_license | hamzaamir749/Doctor-Patient | 9f7de04329502fba442f981f0b894f16a4e4df4e | fa320c90fe6e7b12aab80d4b76a466f191a31096 | refs/heads/master | 2023-01-06T07:47:48.539533 | 2020-10-13T10:56:41 | 2020-10-13T10:56:41 | 303,671,960 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 400 | java | package com.stackbuffers.doctor_patient_project;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
53814ae71c4e17b4ec8b1f183afc7b56660d3154 | ba62fa68d660d344f55bd3c5875e1e40ddb3827e | /loja/Mercadorias/MercadoriaSimples.java | e82786faba5a2b12404f4786074f8e21fc064c77 | [] | no_license | otavioalexandre1/TrabalhoPadroesProjeto | 834a32fa643760c4c412115abba64f80aa9540b5 | 469f33eec4ccd318954dd723def8792660f39d46 | refs/heads/master | 2023-04-14T21:03:07.085081 | 2017-10-17T00:14:45 | 2017-10-17T00:14:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 442 | java | package loja.Mercadorias;
public class MercadoriaSimples implements Mercadoria {
private String nome;
private Double preco;
public MercadoriaSimples(String nome, Double preco) {
this.nome = nome;
this.preco = preco;
}
@Override
public String getNome() {
return this.nome;
}
@Override
public double getPreco() {
return this.preco;
}
}
| [
"[email protected]"
] | |
c8cb84418b779a9d3c020b7c60ef34d8e8977541 | d1bf2c64473769d0159d461aa8eb081e1b0f99e2 | /src/main/java/io/github/ezforever/thatorthis/gui/ChoiceScreen.java | 352d5d9f9607c243a31a8734ad607fd2e5eaf08b | [
"MIT"
] | permissive | Blobanium/ThatOrThis | dca74c8ea9f532ccc701e66038e599be8ebbcccc | 440c2e32c522872273f275887a37b4d0a3a2edc3 | refs/heads/master | 2023-03-14T10:02:01.779404 | 2021-03-10T16:25:40 | 2021-03-10T16:25:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,184 | java | package io.github.ezforever.thatorthis.gui;
import io.github.ezforever.thatorthis.config.Config;
import io.github.ezforever.thatorthis.config.choice.Choice;
import io.github.ezforever.thatorthis.config.choice.ChoiceHolder;
import io.github.ezforever.thatorthis.config.choice.Choices;
import io.github.ezforever.thatorthis.config.rule.Rule;
import io.github.ezforever.thatorthis.config.rule.RuleHolder;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.ConfirmScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.LockButtonWidget;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.LiteralText;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.util.Objects;
import java.util.function.BiFunction;
@Environment(EnvType.CLIENT)
public class ChoiceScreen extends Screen {
private static final Logger LOGGER = LogManager.getLogger("thatorthis/gui");
public static Screen create(Screen parent) {
Config config;
try {
config = Config.getInstance();
} catch(RuntimeException e) {
LOGGER.error("Choice screen disabled due to config errors", e);
return new ConfirmScreen(
(boolean result) -> {
if(result) {
File logsDir = FabricLoader.getInstance()
.getGameDir().resolve("logs")
.toFile();
Util.getOperatingSystem().open(logsDir);
}
MinecraftClient.getInstance().openScreen(parent);
},
Texts.DISABLED_TITLE.get(),
Texts.DISABLED_MESSAGE.get()
);
}
return new ChoiceScreen(parent, config.rules, config.choices, (Choices choices, Screen parentScreen) -> {
config.choices = choices; //choices.copy();
config.save();
return new ConfirmScreen(
(boolean result) -> {
MinecraftClient minecraftClient = MinecraftClient.getInstance();
if(result)
minecraftClient.scheduleStop();
else
minecraftClient.openScreen(parentScreen);
},
Texts.CONFIRM_TITLE.get(),
Texts.CONFIRM_MESSAGE.get()
);
});
}
// ---
private final Screen parent;
private final RuleHolder ruleHolder;
private final Choices initialChoices;
private final BiFunction<Choices, Screen, Screen> callback;
private ChoiceHolder shownChoices;
private RuleButtonListWidget ruleButtons;
private ButtonWidget discardOrDefaultButton;
private LockButtonWidget disableButton;
private ButtonWidget doneButton;
private boolean dirty = false;
public ChoiceScreen(Screen parent,
RuleHolder ruleHolder, Choices initialChoices,
BiFunction<Choices, Screen, Screen> callback) {
super(ruleHolder.getScreenTitle());
this.parent = parent;
this.ruleHolder = ruleHolder;
this.initialChoices = initialChoices.copy();
this.callback = callback;
this.shownChoices = initialChoices.choices.copy();
}
private void setDirty(boolean value) {
dirty = value;
discardOrDefaultButton.setMessage((dirty ? Texts.DISCARD : Texts.DEFAULT).get());
}
private void renderWarpedTooltip(MatrixStack matrices, Text text, int mouseX, int mouseY) {
renderOrderedTooltip(
matrices,
Objects.requireNonNull(client).textRenderer
.wrapLines(text, Math.max(width / 2 - 43, 170)),
mouseX, mouseY
);
}
@Override
protected void init() {
super.init();
ruleButtons = new RuleButtonListWidget(this.client,
width, height, 32, height - 32, 25,
ruleHolder,
(Rule rule, SingleThreadFuture<Choice> choice) ->
choice.then((Choice result) -> {
shownChoices.put(rule.id, result);
if(!dirty)
setDirty(true);
})
);
ruleButtons.setChoices(shownChoices);
addChild(ruleButtons);
discardOrDefaultButton = new ButtonWidget(
width / 2 - 155, height - 27, 150 - 20, 20,
LiteralText.EMPTY,
(ButtonWidget button) -> {
shownChoices = (dirty ? initialChoices.choices : ruleHolder.getDefaultChoices()).copy();
ruleButtons.setChoices(shownChoices);
disableButton.setLocked(dirty && ruleHolder.canDisable() && initialChoices.disabled != null && initialChoices.disabled);
setDirty(!dirty);
}
);
setDirty(dirty); // Reset button caption
addButton(discardOrDefaultButton);
disableButton = new LockButtonWidget(
width / 2 - 155 + 150 - 20, height - 27,
(ButtonWidget button) -> {
LockButtonWidget self = (LockButtonWidget)button;
self.setLocked(!self.isLocked());
if(!dirty)
setDirty(true);
}
) {
@Override // Erase difficulty info in narration message
protected MutableText getNarrationMessage() {
return new TranslatableText("gui.narrate.button", getMessage());
}
@Override // Sync "locked"/"disabled" status to the buttons list
public void setLocked(boolean locked) {
super.setLocked(locked);
ruleButtons.setDisabled(locked);
}
};
disableButton.setMessage(Texts.LOCK.get());
disableButton.setLocked(ruleHolder.canDisable() && initialChoices.disabled != null && initialChoices.disabled);
disableButton.active = ruleHolder.canDisable();
addButton(disableButton);
doneButton = new ButtonWidget(width / 2 - 155 + 160, height - 27, 150, 20, Texts.DONE.get(), (ButtonWidget button) -> onClose());
addButton(doneButton);
}
@Override
public void onClose() {
Screen nextScreen;
if(dirty) {
setDirty(false);
nextScreen = callback.apply(new Choices(shownChoices, disableButton.isLocked()), parent);
} else {
nextScreen = parent;
}
Objects.requireNonNull(client).openScreen(nextScreen);
}
@Override
public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) {
ruleButtons.render(matrices, mouseX, mouseY, delta);
drawCenteredText(matrices, textRenderer, Texts.TITLE.get(), width / 2, 7, 0xffffff);
drawCenteredText(matrices, textRenderer, title, width / 2, 20, 0xffffff);
super.render(matrices, mouseX, mouseY, delta);
ruleButtons.getHoveredButton(mouseX, mouseY)
.ifPresent((RuleButtonWidget button) -> renderWarpedTooltip(matrices, button.getTooltip(), mouseX, mouseY));
if(disableButton.isHovered() && ruleHolder.canDisable()) {
Text tooltip = (disableButton.isLocked() ? Texts.LOCK_ON : Texts.LOCK_OFF).get();
renderWarpedTooltip(matrices, tooltip, mouseX, mouseY);
}
}
}
| [
"[email protected]"
] | |
0b5f446f890ad3bd200e95c0ff392fb60e401662 | ce0f4f1a5d8543952307ed1e4a17847bc478b2e8 | /src/test/java/fr/arolla/skocher/trainreservation/service/BookingReferenceServiceMockTest.java | fdb22b52fbc1f88a5e891bcfa15aa81b4aa5d65b | [] | no_license | s-kocher/kata-train-reservation | d32b340b8c71aa0341d04a4c62b7a3e9dbc04b70 | 7238f69ae4fae65a2845d667e242eaa4d1c88707 | refs/heads/master | 2023-05-16T14:13:00.715660 | 2021-06-09T23:18:06 | 2021-06-09T23:18:06 | 371,086,224 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 457 | java | package fr.arolla.skocher.trainreservation.service;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
public class BookingReferenceServiceMockTest {
@Test
public void should_get_a_not_empty_booking_id_from_service() {
BookingReferenceService refService = new BookingReferenceServiceMock();
String bookingId = refService.getNewBookingId();
Assertions.assertThat(bookingId).isNotEmpty();
}
} | [
"[email protected]"
] | |
2a448801484455657f2d366382e5b82987d94cb0 | a516851ba62bb24d03dace4b13ad7351ff7f9e6b | /src/main/java/ar/fiuba/tdd/tp0/node/Node.java | cbfa8fdf490330005e22fbeced576faabfbcb0a3 | [] | no_license | pgotuzzo/7510-Tecnicas-de-disenio-TP0 | bb51aac275853e2bd6793e9b8b8316d1c69c232b | 675f8abcc6920e283dd90cf4ba41e7fb9cabd5fe | refs/heads/master | 2020-12-11T09:31:01.595631 | 2016-09-01T23:43:11 | 2016-09-01T23:43:11 | 66,740,008 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 255 | java | package ar.fiuba.tdd.tp0.node;
interface Node<T> {
T getElement();
Node<T> getNext();
int count();
boolean isEmpty();
Node<T> setNext(Node<T> node);
void remove(Node<T> previous);
void setPrevious(Node<T> previous);
}
| [
"[email protected]"
] | |
44f5887bfcdfef0c35cb1e74728970022d96022a | 808647f9d93892bad200d3eeb26e58b536f8bf6d | /nowcoder/src/com/kanma/singleton/SingletonTest.java | e392ae3f8043cd499b6b91221ca3ebb9e639e560 | [] | no_license | carryma/kanma-java | 52b6b57b40d4eacbf0271354e76a6d1b2d4721fd | 0c3dacaef9f3318544589b8c98941ee005c39f8b | refs/heads/master | 2020-03-26T03:41:14.377059 | 2018-10-15T14:50:43 | 2018-10-15T14:50:43 | 144,466,298 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,041 | java | package com.kanma.singleton;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @ Desc :测试双检锁单例的线程安全性
* @ Author :MaKang
* @ Date :Created in 2018/8/24 13:50
*/
public class SingletonTest implements Runnable {
@Override
public void run() {
DCLSingleton myInstance = DCLSingleton.getInstance();
System.out.println(myInstance);
}
public static void main(String[] args) {
//DCLSingleton的测试
DCLSingleton myInstance1 = DCLSingleton.getInstance();
DCLSingleton myInstance2 = DCLSingleton.getInstance();
System.out.println(myInstance1 == myInstance2);
//多线程
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.execute(new SingletonTest());
executor.execute(new SingletonTest());
// Thread t1 = new Thread(new SingletonTest());
// Thread t2 = new Thread(new SingletonTest());
// t1.start();
// t2.start();
}
}
| [
"[email protected]"
] | |
5e4183830befed3a70fc7e10f6dc0b8cbfcd7b24 | 3e0d591f6d282226eae9995942a48c6eec62e2ac | /tests/e2e-test-app/app/src/main/java/com/microsoft/office365/test/integration/android/TestLogAdapter.java | d80ce1fa08a371a5d901573f67fd4084f9aa4677 | [
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | xiefkm/Office-365-SDK-for-Android | 840b89b9075154c0eed81331bdc590064a85a46b | 7a2281509e973a75e8933eb4a06985a1954063ac | refs/heads/master | 2020-12-23T15:52:17.530171 | 2015-11-20T16:16:31 | 2015-11-20T16:16:31 | 92,563,038 | 1 | 0 | null | 2017-05-27T02:07:08 | 2017-05-27T02:07:08 | null | UTF-8 | Java | false | false | 3,147 | java | /*
Copyright (c) Microsoft Open Technologies, Inc.
All Rights Reserved
Apache 2.0 License
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.
See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.office365.test.integration.android;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.microsoft.office365.test.integration.R;
import com.microsoft.office365.test.integration.framework.TestCase;
import com.microsoft.office365.test.integration.framework.TestLog;
import com.microsoft.office365.test.integration.framework.TestResult;
import com.microsoft.office365.test.integration.framework.TestStatus;
import junit.framework.Test;
/**
* Adapter to bind a ToDoItem List to a view
*/
public class TestLogAdapter extends ArrayAdapter<TestLog> {
/**
* Adapter mAuthContext
*/
Context mContext;
/**
* Adapter View layout
*/
int mLayoutResourceId;
public TestLogAdapter(Context context, int layoutResourceId) {
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
/**
* Returns the view for a specific item on the list
*/
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
final TestLog testResult = getItem(position);
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
final CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkTestLog);
String text = String.format("%s - %s", testResult.getName(), testResult.getTestStatus().toString());
if (testResult.getTestStatus() == TestStatus.Failed) {
checkBox.setTextColor(Color.RED);
} else if (testResult.getTestStatus() == TestStatus.Passed) {
checkBox.setTextColor(Color.GREEN);
} else {
checkBox.setTextColor(Color.GRAY);
}
checkBox.setText(text);
/*
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
testResult.getTestCase().setSelected(checkBox.isChecked());
}
});
*/
final TextView textView = (TextView) row.findViewById(R.id.textLog);
String errorMessage = testResult.getException() == null ? " - " : testResult.getException().getLocalizedMessage();
textView.setText(errorMessage);
return row;
}
}
| [
"[email protected]"
] | |
07e8e646232fc4227e9d9310d5a4d568117b67ae | ac46f6027e088759f4d306c56f71e076503301d0 | /app/src/main/java/comulez/github/jianreader/mvc/activity/BaseActivity.java | 7d6b02cae51b6fb7044cf6db27878ed75ce7f7d4 | [] | no_license | Ulez/JianReader | bca868eab9abe306e8dc6d3328311b5b5f37643d | 129c03594e159fd1bbac4909d3591e37914909b9 | refs/heads/master | 2021-01-18T08:12:41.379124 | 2017-05-18T05:41:13 | 2017-05-18T05:41:13 | 84,301,253 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,970 | java | package comulez.github.jianreader.mvc.activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Ulez on 2017/2/25.
* Email:[email protected]
*/
public abstract class BaseActivity extends AppCompatActivity {
protected Context appContext;
protected AppCompatActivity activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTransitionAni();
setContentView(getResId());
// if (Build.VERSION.SDK_INT >= 21) {
// View decorView = getWindow().getDecorView();
// int option = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
// decorView.setSystemUiVisibility(option);
// getWindow().setStatusBarColor(Color.TRANSPARENT);
// }
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null)
// actionBar.hide();
activity = this;
appContext = this.getApplicationContext();
}
protected void setTransitionAni() {
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
// if (hasFocus && Build.VERSION.SDK_INT >= 19) {
// View decorView = getWindow().getDecorView();
// decorView.setSystemUiVisibility(
// View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_FULLSCREEN
// | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
// }
}
public abstract int getResId();
}
| [
"[email protected]"
] | |
9d30331df32c63ce95f9e333c31aef58f18b13cf | 3efcaae4beceb2bc23c15cf0744424594d3fdf50 | /Java/CS361/jm76685_project2/ObjectManager.java | 345e2bb2ce753c7a01f6fd4e32f20ba270649912 | [] | no_license | MaddenJohn/archivedProjects | 3843d12e5ca250a79da08f5b16fd079a841eaa53 | cea762843d0b7c53a9f89623872ee02c507da687 | refs/heads/master | 2022-11-30T16:51:48.018503 | 2020-08-14T19:44:07 | 2020-08-14T19:44:07 | 192,224,877 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 305 | java | // objects modified through this manager
public class ObjectManager {
// Modifies the val stored in object to val
public void writeVal(int val, Object obj) {
obj.setVal(val);
}
// returns the value stored in the object
public int readVal(Object obj) {
return obj.getVal();
}
}
| [
"[email protected]"
] | |
a910ceca0862f8730978a1f1b761f76a3de289a1 | b2a50f92f359a63a4adf9c42e7d9734b1f87c50e | /src/main/java/com/epmresources/server/repository/PaymentTransactionsRepository.java | 48d351167cde8286934da840d0e905ced103ae02 | [] | no_license | thetlwinoo/epm-resources | a9dbc08bacd45a0e57c31c14aff3a3e5c6a82597 | 88f2918de8c07cd1c3a2f701c4adfa97305b974d | refs/heads/master | 2022-12-26T15:46:06.041561 | 2019-12-20T07:35:25 | 2019-12-20T07:35:25 | 220,428,422 | 0 | 0 | null | 2022-12-16T04:40:56 | 2019-11-08T09:06:17 | Java | UTF-8 | Java | false | false | 464 | java | package com.epmresources.server.repository;
import com.epmresources.server.domain.PaymentTransactions;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the PaymentTransactions entity.
*/
@SuppressWarnings("unused")
@Repository
public interface PaymentTransactionsRepository extends JpaRepository<PaymentTransactions, Long>, JpaSpecificationExecutor<PaymentTransactions> {
}
| [
"[email protected]"
] | |
728128173913581957423e30ac1cff72ea685b76 | 031346e3f93e330d2d6919539f7133e03bd26589 | /03shooter/day02_am/src/cn/tedu/shooter/FlyingObject.java | cac4fba01691ed3c5e3b45a1ef02c14ee2cc4784 | [] | no_license | fanouer/JavaLesson | 9e0dfe15ec3785c5b076812631a0700cfa8eebe7 | fd276660c87fb8291c0de190d61d73e1ec14b196 | refs/heads/master | 2021-01-18T20:54:39.479959 | 2017-04-02T16:48:33 | 2017-04-02T16:48:33 | 87,000,057 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 1,160 | java | package cn.tedu.shooter;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
/** 代表飞行物体 */
public abstract class FlyingObject {
protected int x;
protected int y;
protected int width;
protected int height;
/**
* 当前物体的显示图片,所有子类型都有各自的图片
*/
protected BufferedImage image;
/*
* 移动方法:
* 声明了飞行物体是可以移动的!
*/
public abstract void move();
/*
* 添加碰撞检查方法,子类自动继承这个方法
* 检查当前对象与另外一个飞行物对象是否发生
* 碰撞。数据来源:当前对象和参数(另外一个对象)
*/
public boolean duang(
FlyingObject other){
int x1=this.x - other.width;
int x2=this.x + this.width;
int y1=this.y - other.height;
int y2=this.y + this.height;
return x1<other.x && other.x<x2 &&
y1<other.y && other.y<y2;
}
/**
* 所有的飞行物都有绘制方法:好处所有的飞行物
* 都有绘制方法:蜜蜂,飞机等
* 天空的绘制不同:“重写” 一下即可
*/
public void paint(Graphics g){
g.drawImage(image, x, y, null);
}
}
| [
"[email protected]"
] | |
c0ccf4b494e3fc09f7bc91027e4da7ce654228ee | d584c1750ed29fea7d243e2a0ec8a7d14ae770a6 | /android/app/src/main/java/com/ionic/ocr/MainActivity.java | b7bef863575445e3c5c5fb177ba68ff80bc85636 | [] | no_license | ashik112/image-to-text-ionic-react | 19010873a8eb9f1042b0424b1a56e11d8b3b0cbe | 3662d6622e6a03d7142bbfbb723e8337491956b7 | refs/heads/master | 2020-09-23T22:03:20.829344 | 2019-12-03T11:53:46 | 2019-12-03T11:53:46 | 225,598,538 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 531 | java | package com.ionic.ocr;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.Plugin;
import java.util.ArrayList;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initializes the Bridge
this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
// Additional plugins you've installed go here
// Ex: add(TotallyAwesomePlugin.class);
}});
}
}
| [
"[email protected]"
] | |
f7d89c6a67649ef419346babfc3772b3346191b8 | da44a0352bcbe6bdfe0a5b5b2acff59b17734ffd | /Java/301-350/HouseRobber3.java | e3484fd86666c4a3b62c5213ddf781d4cdb45f34 | [] | no_license | cute-jumper/LeetCode | 3b7ecad52a392a1d662df586355ac5a760474bdc | ee00b089a4edcf0a27d64941245f8c6074071859 | refs/heads/master | 2021-11-11T18:27:08.681110 | 2021-06-13T22:31:07 | 2021-06-13T22:31:07 | 9,009,384 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 616 | java | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class HouseRobber3 {
public int rob(TreeNode root) {
int[] res = helper(root);
return Math.max(res[0], res[1]);
}
int[] helper(TreeNode root) {
if (root == null) return new int[] { 0, 0 };
int[] left = helper(root.left);
int[] right = helper(root.right);
return new int[] { root.val + left[1] + right[1], Math.max(left[0], left[1]) + Math.max(right[0], right[1]) };
}
}
| [
"[email protected]"
] | |
2d74fbb77b049e8da552df02aa73478bff445aa1 | 1156bb0d38093cf63c55fa23308c1a34cc7944e9 | /DiscreteEventSim/ShipmentMaker.java | fce455aa83df5320fd5dbe4d1b1276a620f40a20 | [] | no_license | xandercernek/javaprojects | ffefa14714d8ac631c6c9e08950fc2dbc18fd91e | b13302a5a4f328a72f9266bb9987e8032a297037 | refs/heads/master | 2021-01-22T06:12:04.741484 | 2017-05-26T16:39:59 | 2017-05-26T16:39:59 | 92,528,506 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,486 | java | //cerne010 and shahx252
//Class generates shipments
import java.util.Arrays;
public class ShipmentMaker implements Event{
private int portIndex; //ID of port
private static int shipCount; //Number of shipments
public ShipmentMaker(int portIndex){
this.portIndex = portIndex;
this.shipCount = 0;
}
public static int getShipCount(){
return shipCount;
}
public void run(){
if(portIndex == 6){ //0.1 percent chance to send to moon
int rand = (int) (Math.random() * 9 + 0);
if(rand != 6){
portIndex = rand;
}
}
shipCount ++;
double time = Main.agenda.getCurrentTime();
double check = (Math.random() * 100 + 1);
int shipPerDay;
switch (portIndex){ //how many shipments should be produced per day
case 0:
shipPerDay = 50;
break;
case 1:
shipPerDay = 50;
break;
case 2:
shipPerDay = 10;
break;
case 3:
shipPerDay = 100;
break;
case 4:
shipPerDay = 50;
break;
case 5:
shipPerDay = 100;
break;
case 6:
shipPerDay = 0;
break;
case 7:
shipPerDay = 50;
break;
case 8:
shipPerDay = 50;
break;
case 9:
shipPerDay = 100;
break;
default:
shipPerDay = -1;
break;
}
double mu = 1440.0/shipPerDay;
try { // random distribution model{
mu = 1440/shipPerDay;
}catch(java.lang.ArithmeticException e){
mu = 1;
}
if(time == 0 && mu <= 2) {
time = 1;
}else{
if(check<11){
time = time + (mu/4);
}else if(check>=11 || check <26){
time = time + (mu/2);
}else if(check>=26 || check<46){
time = time + (4*mu/5);
}else if(check>=46 || check<56){
time = time + (mu);
}else if(check>=56 || check<76){
time = time + (6*mu/5);
}else if(check>=76 || check<91){
time = time + (3*mu/2);
}else if(check>=91 || check<101){
time = time + (7*mu/4);
} //}
}
System.out.println("Adding a shipment at time " + time + " at port " + portIndex);
for(int i=0; i<Main.allShips.length; i++){
if(Main.allShips[i].idle == true && Main.allShips[i].getCurrentPort() == portIndex){ //check if ship is waiting to leave
Main.agenda.add(new VesselEvent(Main.allShips[i], Main.portArray[portIndex]), Main.agenda.getCurrentTime() + 1); //wake it up
}
}
if(Main.agenda.getCurrentTime() + time <= Main.day){
Main.agenda.add(new ShipmentMaker(portIndex), time); //make new event
}
Main.portArray[portIndex].getQ2().add(new Shipment()); //add shipment to port
Main.setTotalline( Main.portArray[portIndex].getQ2().length());
if(Main.getMaxline() < Main.portArray[portIndex].getQ2().length()){
Main.setMaxline( Main.portArray[portIndex].getQ2().length());
}
}
} | [
"[email protected]"
] | |
3437632c6c161c39ad9af8e233716c45545cd33f | ac48c2d7b75deb4ff5c78e4ba03ffdcc953c28d8 | /src/Fraction.java | 5f9c879c4c08bbc9dc0a209cdccc8591df6d2178 | [] | no_license | RockyCao23/Fraction-Class | 1490632d43b03a09c540b22a99d64925b6fd3380 | b09dd934a602834c206d4d02545745ecd08a0eaa | refs/heads/main | 2023-02-28T20:30:26.931794 | 2021-02-10T08:24:20 | 2021-02-10T08:24:20 | 337,660,060 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,963 | java | public class Fraction {
private int n, d;
public Fraction() {
this.n = 1;
this.d = 1;
}
public Fraction(int n, int d){
if (d == 0){
System.out.println("Error: Denominator zero exception");
this.n = 1;
this.d = 1;
}else {
this.n = n;
this.d = d;
}
}
public Fraction(String x){
int z;
int s = x.indexOf("/");
String num = x.substring(0,s);
String den = x.substring(s+1,x.length());
z = Integer.parseInt(den);
if (z == 0){
this.n = 1;
this.d = 1;
System.out.println("Error: Denominator zero exception");
}else {
this.n = Integer.parseInt(num);
this.d = Integer.parseInt(den);
}
}
public Fraction(Fraction x){
if (x.d == 0){
this.n = 1;
this.d = 1;
System.out.println("Error: Denominator zero exception");
}else {
this.n = x.n;
this.d = x.d;
}
}
public int getNum(){
return this.n;
}
public int getDen(){
return this.d;
}
public double toDouble(){
if (this.d != 0) {
double x = ((double) (this.n) / (double) this.d);
return x;
}else return 0.0;
}
public String toString(){
if (this.d != 0) {
return this.n + "/" + this.d;
}else return "Error: Denominator zero exception";
}
public static int GCF(int x, int y){
while (x != y){
if (x > y){
x = x - y;
}else if (y > x){
y = y - x;
}
}int GCF = x;
return GCF;
}
public void reduce(){
int gcf = GCF(this.n , this.d);
this.n = this.n / gcf;
this.d = this.d / gcf;
}
public void setNum(int x){
this.n = x;
}
public void setDen(int x){
this.d = x;
}
public static Fraction multiply(Fraction x, Fraction y){
int xn = x.n;
int xd = x.d;
int yn = y.n;
int yd = y.d;
int n = xn * yn;
int d = yn * yd;
Fraction ans = new Fraction(n, d);
return ans;
}
public static Fraction divide(Fraction x, Fraction y){
int xn = x.n;
int xd = x.d;
int yn = y.d;
int yd = y.n;
int n = xn * yn;
int d = xd * yd;
Fraction ans = new Fraction(n , d);
return ans;
}
public static Fraction add(Fraction x, Fraction y){
int n = x.n * y.d + y.n * x.d;
int d = y.d * x.d;
Fraction sum = new Fraction(n , d);
return sum;
}
public static Fraction subtract(Fraction x, Fraction y){
int n = x.n * y.d - y.n * x.d;
int d = y.d * x.d;
Fraction sum = new Fraction(n , d);
return sum;
}
}
| [
"[email protected]"
] | |
ed3c4f189266f092f8112ccb1c44b7945187e13d | a17dd1e9f5db1c06e960099c13a5b70474d90683 | /core/src/main/java/jp/co/sint/webshop/service/order/OrderHeadline.java | 3f998374b6b7b50582e1cf38261ec043d4cb96b3 | [] | no_license | giagiigi/ec_ps | 4e404afc0fc149c9614d0abf63ec2ed31d10bebb | 6eb19f4d14b6f3a08bfc2c68c33392015f344cdd | refs/heads/master | 2020-12-14T07:20:24.784195 | 2015-02-09T10:00:44 | 2015-02-09T10:00:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,789 | java | package jp.co.sint.webshop.service.order;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import jp.co.sint.webshop.utility.DateUtil;
public class OrderHeadline implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String orderNo;
private String shopCode;
private String addressLastName;
private String guestFlg;
private String customerName;
private String caution;
private String message;
private String phoneNumber;
// Add by V10-CH start
private String mobileNumber;
// Add by V10-CH end
private String orderDatetime;
private String paymentDate;
private Long paymentMethodNo;
private String paymentMethodName;
private String paymentMethodType;
private String shippingStatusSummary;
private String returnStatusSummary;
private String totalAmount;
private String orderStatus;
private Date updatedDatetime;
private BigDecimal usedPoint;
private BigDecimal paymentCommission;
private Date paymentLimitDate;
// 20120120 ysy add start
private String discountPrice;
// 20120120 ysy add end
// soukai add 2011/12/29 ob start
// 受注タイプ
private String orderType;
private String mobileComputerType;
private String tmallTid;
// 订单检查
private String orderFlg;
private String languageCode;
private String tmallBuyerMessage;
private String jdBuyerMessage;
private String BuyerMessage;
private String BuyId;
private String deliverySlipNo;
private BigDecimal giftCardUsePrice;
private BigDecimal outerCardUsePrice;
// soukai add 2011/12/29 ob end
/**
* paymentLimitDateを取得します。
*
* @return paymentLimitDate
*/
public Date getPaymentLimitDate() {
return DateUtil.immutableCopy(paymentLimitDate);
}
public String getMobileComputerType() {
return mobileComputerType;
}
public void setMobileComputerType(String mobileComputerType) {
this.mobileComputerType = mobileComputerType;
}
public String getTmallTid() {
return tmallTid;
}
public void setTmallTid(String tmallTid) {
this.tmallTid = tmallTid;
}
public String getDeliverySlipNo() {
return deliverySlipNo;
}
public void setDeliverySlipNo(String deliverySlipNo) {
this.deliverySlipNo = deliverySlipNo;
}
/**
* @return the discountPrice
*/
public String getDiscountPrice() {
return discountPrice;
}
/**
* @param discountPrice
* the discountPrice to set
*/
public void setDiscountPrice(String discountPrice) {
this.discountPrice = discountPrice;
}
/**
* paymentLimitDateを設定します。
*
* @param paymentLimitDate
* paymentLimitDate
*/
public void setPaymentLimitDate(Date paymentLimitDate) {
this.paymentLimitDate = DateUtil.immutableCopy(paymentLimitDate);
}
/**
* usedPointを返します。
*
* @return the usedPoint
*/
public BigDecimal getUsedPoint() {
return usedPoint;
}
/**
* usedPointを設定します。
*
* @param usedPoint
* 設定する usedPoint
*/
public void setUsedPoint(BigDecimal usedPoint) {
this.usedPoint = usedPoint;
}
/**
* @return the updatedDatetime
*/
public Date getUpdatedDatetime() {
return DateUtil.immutableCopy(updatedDatetime);
}
/**
* @param updatedDatetime
* the updatedDatetime to set
*/
public void setUpdatedDatetime(Date updatedDatetime) {
this.updatedDatetime = DateUtil.immutableCopy(updatedDatetime);
}
/**
* @return the orderStatus
*/
public String getOrderStatus() {
return orderStatus;
}
/**
* @param orderStatus
* the orderStatus to set
*/
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
/**
* @return the shippingStatusSummary
*/
public String getShippingStatusSummary() {
return shippingStatusSummary;
}
/**
* @param shippingStatusSummary
* the shippingStatusSummary to set
*/
public void setShippingStatusSummary(String shippingStatusSummary) {
this.shippingStatusSummary = shippingStatusSummary;
}
/**
* @return the totalAmount
*/
public String getTotalAmount() {
return totalAmount;
}
/**
* @param totalAmount
* the totalAmount to set
*/
public void setTotalAmount(String totalAmount) {
this.totalAmount = totalAmount;
}
/**
* @return the caution
*/
public String getCaution() {
return caution;
}
/**
* @param caution
* the caution to set
*/
public void setCaution(String caution) {
this.caution = caution;
}
/**
* @return the customerName
*/
public String getCustomerName() {
return customerName;
}
/**
* @param customerName
* the customerName to set
*/
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
/**
* @return the orderDatetime
*/
public String getOrderDatetime() {
return orderDatetime;
}
/**
* @param orderDatetime
* the orderDatetime to set
*/
public void setOrderDatetime(String orderDatetime) {
this.orderDatetime = orderDatetime;
}
/**
* @return the orderNo
*/
public String getOrderNo() {
return orderNo;
}
/**
* @param orderNo
* the orderNo to set
*/
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
/**
* @return the paymentDate
*/
public String getPaymentDate() {
return paymentDate;
}
/**
* @param paymentDate
* the paymentDate to set
*/
public void setPaymentDate(String paymentDate) {
this.paymentDate = paymentDate;
}
/**
* @return the paymentMethodName
*/
public String getPaymentMethodName() {
return paymentMethodName;
}
/**
* @param paymentMethodName
* the paymentMethodName to set
*/
public void setPaymentMethodName(String paymentMethodName) {
this.paymentMethodName = paymentMethodName;
}
/**
* @return the phoneNumber
*/
public String getPhoneNumber() {
return phoneNumber;
}
/**
* @param phoneNumber
* the phoneNumber to set
*/
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
* @return the paymentMethodNo
*/
public Long getPaymentMethodNo() {
return paymentMethodNo;
}
/**
* @param paymentMethodNo
* the paymentMethodNo to set
*/
public void setPaymentMethodNo(Long paymentMethodNo) {
this.paymentMethodNo = paymentMethodNo;
}
/**
* @return the shopCode
*/
public String getShopCode() {
return shopCode;
}
/**
* @param shopCode
* the shopCode to set
*/
public void setShopCode(String shopCode) {
this.shopCode = shopCode;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message
* the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the paymentMethodType
*/
public String getPaymentMethodType() {
return paymentMethodType;
}
/**
* @param paymentMethodType
* the paymentMethodType to set
*/
public void setPaymentMethodType(String paymentMethodType) {
this.paymentMethodType = paymentMethodType;
}
/**
* @return the returnStatusSummary
*/
public String getReturnStatusSummary() {
return returnStatusSummary;
}
/**
* @param returnStatusSummary
* the returnStatusSummary to set
*/
public void setReturnStatusSummary(String returnStatusSummary) {
this.returnStatusSummary = returnStatusSummary;
}
/**
* paymentCommissionを返します。
*
* @return the paymentCommission
*/
public BigDecimal getPaymentCommission() {
return paymentCommission;
}
/**
* paymentCommissionを設定します。
*
* @param paymentCommission
* 設定する paymentCommission
*/
public void setPaymentCommission(BigDecimal paymentCommission) {
this.paymentCommission = paymentCommission;
}
/**
* guestFlgを取得します。
*
* @return guestFlg
*/
public String getGuestFlg() {
return guestFlg;
}
/**
* guestFlgを設定します。
*
* @param guestFlg
* guestFlg
*/
public void setGuestFlg(String guestFlg) {
this.guestFlg = guestFlg;
}
/**
* mobileNumberを取得します。
*
* @return mobileNumber mobileNumber
*/
public String getMobileNumber() {
return mobileNumber;
}
/**
* mobileNumberを設定します。
*
* @param mobileNumber
* mobileNumber
*/
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
// soukai add 2011/12/29 ob start
/**
* 受注タイプを取得する
*
* @return the orderType
*/
public String getOrderType() {
return orderType;
}
/**
* 受注タイプを設定する
*
* @param orderType
* the orderType to set
*/
public void setOrderType(String orderType) {
this.orderType = orderType;
}
// soukai add 2011/12/29 ob end
/**
* @return the orderFlg
*/
public String getOrderFlg() {
return orderFlg;
}
/**
* @param orderFlg
* the orderFlg to set
*/
public void setOrderFlg(String orderFlg) {
this.orderFlg = orderFlg;
}
/**
* @return the tmallBuyerMessage
*/
public String getTmallBuyerMessage() {
return tmallBuyerMessage;
}
/**
* @param tmallBuyerMessage
* the tmallBuyerMessage to set
*/
public void setTmallBuyerMessage(String tmallBuyerMessage) {
this.tmallBuyerMessage = tmallBuyerMessage;
}
public String getLanguageCode() {
return languageCode;
}
public void setLanguageCode(String languageCode) {
this.languageCode = languageCode;
}
/**
* @return the giftCardUsePrice
*/
public BigDecimal getGiftCardUsePrice() {
return giftCardUsePrice;
}
/**
* @param giftCardUsePrice the giftCardUsePrice to set
*/
public void setGiftCardUsePrice(BigDecimal giftCardUsePrice) {
this.giftCardUsePrice = giftCardUsePrice;
}
/**
* @return the outerCardUsePrice
*/
public BigDecimal getOuterCardUsePrice() {
return outerCardUsePrice;
}
/**
* @param outerCardUsePrice the outerCardUsePrice to set
*/
public void setOuterCardUsePrice(BigDecimal outerCardUsePrice) {
this.outerCardUsePrice = outerCardUsePrice;
}
/**
* @return the buyerMessage
*/
public String getBuyerMessage() {
return BuyerMessage;
}
/**
* @return the buyId
*/
public String getBuyId() {
return BuyId;
}
/**
* @param buyerMessage the buyerMessage to set
*/
public void setBuyerMessage(String buyerMessage) {
BuyerMessage = buyerMessage;
}
/**
* @param buyId the buyId to set
*/
public void setBuyId(String buyId) {
BuyId = buyId;
}
/**
* @return the jdBuyerMessage
*/
public String getJdBuyerMessage() {
return jdBuyerMessage;
}
/**
* @param jdBuyerMessage the jdBuyerMessage to set
*/
public void setJdBuyerMessage(String jdBuyerMessage) {
this.jdBuyerMessage = jdBuyerMessage;
}
/**
* @return the addressLastName
*/
public String getAddressLastName() {
return addressLastName;
}
/**
* @param addressLastName the addressLastName to set
*/
public void setAddressLastName(String addressLastName) {
this.addressLastName = addressLastName;
}
}
| [
"[email protected]"
] | |
27264af6754fa71e62a8abe78c2cc4415e589e78 | ee9b173fc02cf6d2dd4f2dc52ce8a207c139431b | /WestcottHw7/src/com/example/westcotthw7/HomeScreen.java | 0fa52416708d523dcb767e914fc5f56e39753b4b | [] | no_license | TannerJWestcott/CS370 | bf75f3888cceb8ba8045a44756c8a5f1008d2f8f | c1a853eac2264a02709770a2af5deedee6aa1a4a | refs/heads/master | 2021-01-20T09:32:16.170185 | 2013-04-24T21:03:46 | 2013-04-24T21:03:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 984 | java | package com.example.westcotthw7;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class HomeScreen extends Activity {
protected static final int MANAGE_ASSIGNMENTS_REQUEST_CODE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
final Button assignmentsbutton = (Button) findViewById(R.id.manageButton);
// assuming that the id of the button is assignments, by the XML layout
assignmentsbutton.setOnClickListener( new Button.OnClickListener() {
public void onClick(View v) {
try {
startActivityForResult(new Intent(v.getContext(), HomeScreen.class),
MANAGE_ASSIGNMENTS_REQUEST_CODE);
} catch (Exception e) {
}
}
} ) ;
}}
| [
"[email protected]"
] | |
e7143fe5fe6eaa42fa32ca91fd7f2e53735a479a | fbf27d453d933352a2c8ef76e0445f59e6b5d304 | /gateway/src/com/fy/gamegateway/message/DO_HOSEE2OTHER_RES.java | c4c79f1c426840a33d57f4d14b99398afdce61a7 | [] | no_license | JoyPanda/wangxian_server | 0996a03d86fa12a5a884a4c792100b04980d3445 | d4a526ecb29dc1babffaf607859b2ed6947480bb | refs/heads/main | 2023-06-29T05:33:57.988077 | 2021-04-06T07:29:03 | 2021-04-06T07:29:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,949 | java | package com.fy.gamegateway.message;
import com.xuanzhi.tools.transport.*;
import java.nio.ByteBuffer;
/**
* 网络数据包,此数据包是由MessageComplier自动生成,请不要手动修改。<br>
* 版本号:null<br>
* <br>
* 数据包的格式如下:<br><br>
* <table border="0" cellpadding="0" cellspacing="1" width="100%" bgcolor="#000000" align="center">
* <tr bgcolor="#00FFFF" align="center"><td>字段名</td><td>数据类型</td><td>长度(字节数)</td><td>说明</td></tr> * <tr bgcolor="#FFFFFF" align="center"><td>length</td><td>int</td><td>getNumOfByteForMessageLength()个字节</td><td>包的整体长度,包头的一部分</td></tr>
* <tr bgcolor="#FAFAFA" align="center"><td>type</td><td>int</td><td>4个字节</td><td>包的类型,包头的一部分</td></tr>
* <tr bgcolor="#FFFFFF" align="center"><td>seqNum</td><td>int</td><td>4个字节</td><td>包的序列号,包头的一部分</td></tr>
* <tr bgcolor="#FAFAFA" align="center"><td>create</td><td>long</td><td>8个字节</td><td>配置的长度</td></tr>
* </table>
*/
public class DO_HOSEE2OTHER_RES implements ResponseMessage{
static GameMessageFactory mf = GameMessageFactory.getInstance();
long seqNum;
long create;
public DO_HOSEE2OTHER_RES(){
}
public DO_HOSEE2OTHER_RES(long seqNum,long create){
this.seqNum = seqNum;
this.create = create;
}
public DO_HOSEE2OTHER_RES(long seqNum,byte[] content,int offset,int size) throws Exception{
this.seqNum = seqNum;
create = (long)mf.byteArrayToNumber(content,offset,8);
offset += 8;
}
public int getType() {
return 0x80A3B05A;
}
public String getTypeDescription() {
return "DO_HOSEE2OTHER_RES";
}
public String getSequenceNumAsString() {
return String.valueOf(seqNum);
}
public long getSequnceNum(){
return seqNum;
}
private int packet_length = 0;
public int getLength() {
if(packet_length > 0) return packet_length;
int len = mf.getNumOfByteForMessageLength() + 4 + 4;
len += 8;
packet_length = len;
return len;
}
public int writeTo(ByteBuffer buffer) {
int messageLength = getLength();
if(buffer.remaining() < messageLength) return 0;
int oldPos = buffer.position();
buffer.mark();
try{
buffer.put(mf.numberToByteArray(messageLength,mf.getNumOfByteForMessageLength()));
buffer.putInt(getType());
buffer.putInt((int)seqNum);
buffer.putLong(create);
}catch(Exception e){
e.printStackTrace();
buffer.reset();
throw new RuntimeException("in writeTo method catch exception :",e);
}
int newPos = buffer.position();
buffer.position(oldPos);
buffer.put(mf.numberToByteArray(newPos-oldPos,mf.getNumOfByteForMessageLength()));
buffer.position(newPos);
return newPos-oldPos;
}
/**
* 获取属性:
* 无帮助说明
*/
public long getCreate(){
return create;
}
/**
* 设置属性:
* 无帮助说明
*/
public void setCreate(long create){
this.create = create;
}
} | [
"[email protected]"
] | |
b9cc0d32ee23b67623be034d6984c050d86585e6 | 663dc7e9f8b4970b491cfaaac4ac6839db006fb3 | /src/Frontend/Recepcionista/PanelInformacionFacturacion.java | 8bfad684a58e8c8fe866c11ea6f7d8913fb2e534 | [] | no_license | AlexanderLuther/Proyecto-1-IPC2 | f0b23b4160c3508cdf6db5910d930f8706c00583 | 43f4b91368ea07511bebb60c8b92da451ef55ed1 | refs/heads/master | 2021-07-06T06:35:49.681259 | 2019-08-26T20:06:45 | 2019-08-26T20:06:45 | 201,528,096 | 0 | 0 | null | 2020-11-12T05:56:06 | 2019-08-09T19:22:45 | Java | UTF-8 | Java | false | false | 18,876 | java | package Frontend.Recepcionista;
import Backend.Paquete;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author helmuthluther
*/
public class PanelInformacionFacturacion extends javax.swing.JDialog {
//Varaibles de la clase.
private double total;
private boolean aceptar;
private List<Paquete> listadoPaquetes;
public PanelInformacionFacturacion(java.awt.Frame parent, boolean modal) {
super(parent, modal);
this.listadoPaquetes = new ArrayList<>();
initComponents();
}
/*
Metodo encargado de llenar la informacion de las etiquetas de encabezado en base a los parametros recibidos.
*/
public void llenarInformacionEncabezado(String nombre, String apellido, String NIT, String direccion){
etiquetaNombre.setText(nombre + " " + apellido);
etiquetaNIT.setText(NIT);
etiquetaDireccion.setText(direccion);
}
/*
Metodo encargado de llenar la informacion del area de texto en base a los parametros recibidos.
*/
public void llenarInformacionFacturacion(List<Paquete> paquetes){
total = 0;
areaResumenPaquetes.setText("");
for(int i = 0; i < paquetes.size(); i++){
areaResumenPaquetes.setText(areaResumenPaquetes.getText() +"Paquete: " + paquetes.get(i).getCodigo() +" Peso: " + paquetes.get(i).getPeso() + "lb(s) Precio: Q" + paquetes.get(i).getPrecioTotal() + "\n");
total = total + paquetes.get(i).getPrecioTotal();
}
etiquetaTotal.setText(String.valueOf("Q" + total));
}
/*
Metodo encargado de devolver el valor almacenado en la variable aceptar.
*/
public boolean devolverRespuesta(){
return aceptar;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel3 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jLabel9 = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
etiquetaNombre = new javax.swing.JLabel();
etiquetaDireccion = new javax.swing.JLabel();
etiquetaNIT = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
botonCancelar = new rojerusan.RSButtonIconI();
botonAceptar = new rojerusan.RSButtonIconI();
jScrollPane1 = new javax.swing.JScrollPane();
areaResumenPaquetes = new javax.swing.JTextArea();
jLabel4 = new javax.swing.JLabel();
etiquetaTotal = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Informacion de Facturacion");
setMaximumSize(new java.awt.Dimension(682, 437));
setMinimumSize(new java.awt.Dimension(682, 437));
jPanel3.setBackground(new java.awt.Color(204, 204, 204));
jPanel3.setMaximumSize(new java.awt.Dimension(682, 593));
jPanel3.setMinimumSize(new java.awt.Dimension(682, 593));
jPanel3.setName(""); // NOI18N
jPanel4.setBackground(new java.awt.Color(0, 153, 255));
jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Frontend/Imagenes/factura.png"))); // NOI18N
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jLabel9)
.addContainerGap(21, Short.MAX_VALUE))
);
jPanel5.setBackground(new java.awt.Color(204, 204, 204));
jLabel3.setFont(new java.awt.Font("Roboto", 1, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(0, 102, 153));
jLabel3.setText("Direccion:");
jLabel5.setFont(new java.awt.Font("Roboto", 1, 14)); // NOI18N
jLabel5.setForeground(new java.awt.Color(0, 102, 153));
jLabel5.setText("Nombre:");
jLabel12.setFont(new java.awt.Font("Roboto", 1, 14)); // NOI18N
jLabel12.setForeground(new java.awt.Color(0, 102, 153));
jLabel12.setText("NIT:");
etiquetaNombre.setFont(new java.awt.Font("Roboto", 1, 14)); // NOI18N
etiquetaNombre.setForeground(new java.awt.Color(0, 102, 153));
etiquetaDireccion.setFont(new java.awt.Font("Roboto", 1, 14)); // NOI18N
etiquetaDireccion.setForeground(new java.awt.Color(0, 102, 153));
etiquetaNIT.setFont(new java.awt.Font("Roboto", 1, 14)); // NOI18N
etiquetaNIT.setForeground(new java.awt.Color(0, 102, 153));
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel12)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(etiquetaNIT, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
.addComponent(etiquetaDireccion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(etiquetaNombre, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(13, 13, 13)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(etiquetaNombre, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel12)
.addComponent(etiquetaNIT, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(etiquetaDireccion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel6.setBackground(new java.awt.Color(204, 204, 204));
botonCancelar.setBackground(new java.awt.Color(0, 153, 255));
botonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Frontend/Imagenes/cancelar.png"))); // NOI18N
botonCancelar.setText("CANCELAR");
botonCancelar.setColorHover(new java.awt.Color(153, 153, 153));
botonCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonCancelarActionPerformed(evt);
}
});
botonAceptar.setBackground(new java.awt.Color(0, 153, 255));
botonAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Frontend/Imagenes/aceptar.png"))); // NOI18N
botonAceptar.setText("ACEPTAR");
botonAceptar.setColorHover(new java.awt.Color(153, 153, 153));
botonAceptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonAceptarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(botonAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(botonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(botonCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(botonAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(32, Short.MAX_VALUE))
);
areaResumenPaquetes.setEditable(false);
areaResumenPaquetes.setColumns(20);
areaResumenPaquetes.setFont(new java.awt.Font("Roboto", 1, 14)); // NOI18N
areaResumenPaquetes.setForeground(new java.awt.Color(0, 102, 153));
areaResumenPaquetes.setRows(5);
jScrollPane1.setViewportView(areaResumenPaquetes);
jLabel4.setFont(new java.awt.Font("Roboto", 1, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(0, 102, 153));
jLabel4.setText("Total:");
etiquetaTotal.setFont(new java.awt.Font("Roboto", 1, 14)); // NOI18N
etiquetaTotal.setForeground(new java.awt.Color(0, 102, 153));
etiquetaTotal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(97, 97, 97)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 481, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(etiquetaTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(98, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(etiquetaTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/*
Metodo encargado de cerrar el JDialog y establecer en false el valor de la variable aceptar.
*/
private void botonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonCancelarActionPerformed
this.dispose();
aceptar = false;
}//GEN-LAST:event_botonCancelarActionPerformed
/*
Metodo encargado de cerrar el JDialog y establecer en true el valor de la variable aceptar.
*/
private void botonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAceptarActionPerformed
this.dispose();
//Aqui puedo mandar a exportar a HTML
aceptar = true;
}//GEN-LAST:event_botonAceptarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PanelInformacionFacturacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PanelInformacionFacturacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PanelInformacionFacturacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PanelInformacionFacturacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
PanelInformacionFacturacion dialog = new PanelInformacionFacturacion(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextArea areaResumenPaquetes;
private rojerusan.RSButtonIconI botonAceptar;
private rojerusan.RSButtonIconI botonCancelar;
private javax.swing.JLabel etiquetaDireccion;
private javax.swing.JLabel etiquetaNIT;
private javax.swing.JLabel etiquetaNombre;
private javax.swing.JLabel etiquetaTotal;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
| [
"[email protected]"
] | |
3c928d07489463b8c9885e3a0020d8079b934922 | 4d0ef12c537ead66fa37812a43a4305d660a4f69 | /app/src/main/java/com/developndesign/kcalculator/FragmentPage4.java | e42f4121537d27654ef1c58961fb3fcdeaaea94c | [] | no_license | kimgeunha/foodkcal | aab88257f3f3e7b0766a17e6050dc96afd43c94e | dc5dd4fa4b4ada2c9f247384e677799ca0b4f4f8 | refs/heads/master | 2023-03-19T07:28:41.375807 | 2021-03-09T10:54:10 | 2021-03-09T10:54:10 | 345,972,323 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 851 | java | package com.developndesign.kcalculator;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.developndesign.firebaseautomlvisionedge.R;
public class FragmentPage4 extends androidx.fragment.app.Fragment {
Button change;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_page_4, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
| [
"[email protected]"
] | |
d22583a10fbb39a4dae85b58cd5a67f8fc29a511 | 913b15056d6ebb7240b6bc133fc7f627d490552b | /src/main/java/org/asciidoc/intellij/psi/AsciiDocDescriptionItem.java | d6d0aabfd0c1e07e28f0b4a7fdb46a514df25f55 | [
"Apache-2.0"
] | permissive | jagedn/asciidoctor-intellij-plugin | 242b15e78abf7e1c50e8249d99c1e43a26521ad9 | c7b2bd9e5c5ded407a8337bb72978efb10b515b5 | refs/heads/main | 2023-08-22T13:01:01.690657 | 2021-10-11T23:03:55 | 2021-10-12T05:45:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,747 | java | package org.asciidoc.intellij.psi;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import icons.AsciiDocIcons;
import org.asciidoc.intellij.inspections.AsciiDocVisitor;
import org.asciidoc.intellij.lexer.AsciiDocTokenTypes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* @author Alexander Schwartz ([email protected])
*/
public class AsciiDocDescriptionItem extends ASTWrapperPsiElement implements AsciiDocBlock {
public AsciiDocDescriptionItem(@NotNull ASTNode node) {
super(node);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof AsciiDocVisitor) {
((AsciiDocVisitor) visitor).visitBlocks(this);
return;
}
super.accept(visitor);
}
@NotNull
@Override
public String getFoldedSummary() {
PsiElement child = getFirstSignificantChildForFolding();
if (child instanceof AsciiDocBlockAttributes) {
return "[" + getStyle() + "]";
}
if (child != null) {
StringBuilder sb = new StringBuilder();
while (child != null && child.getNode().getElementType() != AsciiDocTokenTypes.DESCRIPTION_END) {
sb.append(child.getText());
child = child.getNextSibling();
}
return sb.toString();
} else {
return "???";
}
}
@Override
public @Nullable String getTitle() {
String title = AsciiDocBlock.super.getTitle();
if (title == null) {
title = getFoldedSummary();
}
return title;
}
@Override
public Icon getIcon(int flags) {
return AsciiDocIcons.Structure.ITEM;
}
}
| [
"[email protected]"
] | |
319c3849df9b852cde472e6bd9b4b4b75b5669e0 | 39fc385ff3056bb4fded8f1a1f951421f574cbd0 | /src/test/java/com/view/tag/impl/NewTagLayoutImplTest.java | 6368dc1abbdd32bda92b36ecd93b59757e1ed6da | [] | no_license | ondrej-kvasnovsky/vaadin-model-view-presenter | ccb544e4802bf453a37c345ed9dd914222f080d2 | ce8f820062791973a102c7c7038369a716044ca2 | refs/heads/master | 2021-10-21T14:34:05.982290 | 2021-10-14T03:15:32 | 2021-10-14T03:15:32 | 8,390,615 | 8 | 1 | null | 2021-10-14T03:15:32 | 2013-02-24T12:50:38 | Java | UTF-8 | Java | false | false | 607 | java | package com.view.tag.impl;
import com.view.tag.TagViewHandler;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class NewTagLayoutImplTest {
private NewTagLayoutImpl layout;
private TagViewHandler handler;
@Before
public void setUp() {
layout = new NewTagLayoutImpl();
handler = mock(TagViewHandler.class);
layout.setHandler(handler);
layout.init();
}
@Test
public void isTagAddedAfterButtonIsClicked() {
layout.getBtnConfirm().click();
verify(handler, times(1)).addTag();
}
}
| [
"[email protected]"
] | |
69c85b1f8b04e9688e18f72d5e28a9754f287043 | 4b2eb01f2a4554f786048ade26ba33e0590f3ddc | /LMSSpringStarterRest/src/main/java/com/gcit/lms/LmsSpringStarterRestApplication.java | e2d3e637d529a12c9a8aaaee1f906600d3e4c51d | [] | no_license | coolbeings/LMSRestJPA | 2d5306470cf7b5db1d23481662a970435e60fb90 | a19ebda3f5f9093b82374d970dc731d5334dbd5e | refs/heads/master | 2020-03-26T22:33:36.657885 | 2018-08-20T20:51:24 | 2018-08-20T20:51:24 | 145,468,989 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 521 | java | package com.gcit.lms;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan("com.gcit.lms")
public class LmsSpringStarterRestApplication {
public static void main(String[] args) {
SpringApplication.run(LmsSpringStarterRestApplication.class, args);
}
}
| [
"[email protected]"
] | |
a02b85ecd2ccfd9fc87110f80a7c759617a91d6b | 46af9f0f3ee69bee9436361aab56ce3efcbdc1f2 | /java-backend/src/main/java/com/amos2020/javabackend/JavaBackendApplication.java | d1ab267b6c07b698e01e6e2b004de4d6bf5db485 | [
"MIT"
] | permissive | maxKernn/msg-audit-tool | a09eb82dc51a14b1f9ce573d1014d93acf33edd5 | 83f49892da047289c5546df5fd88576053647b55 | refs/heads/master | 2022-12-03T15:33:17.854317 | 2020-08-15T03:22:20 | 2020-08-15T03:22:20 | 287,669,407 | 0 | 0 | MIT | 2020-08-15T03:21:47 | 2020-08-15T03:21:46 | null | UTF-8 | Java | false | false | 339 | java | package com.amos2020.javabackend;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JavaBackendApplication {
public static void main(String[] args) {
SpringApplication.run(JavaBackendApplication.class, args);
}
}
| [
"[email protected]"
] | |
a662c6ab1e0bbfdcad4fdb768ffa749167dc3be4 | 0d02e44a830682664593390144b59ef550be9295 | /campaign/src/main/java/com/espire/campaign/contact/service/DesignationGroupService.java | 3262f4cf44fcbff49fb874458dc42b6b21006a18 | [] | no_license | OmAndSamrat/EspireCampaignTool | 733f79e0842c93a7d033a749d4e251faccd5c429 | 25c6c05a95967ec8a9a95399f0804f87e835d8ea | refs/heads/master | 2021-01-12T03:50:48.972289 | 2017-03-15T05:51:42 | 2017-03-15T05:51:42 | 78,272,516 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,618 | java | package com.espire.campaign.contact.service;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.log4j.Logger;
import com.espire.campaign.contact.dao.DesignationGroupDao;
import com.espire.campaign.exception.DBException;
import com.espire.domain.DesignationGroup;
@Stateless
@TransactionManagement(value=TransactionManagementType.CONTAINER)
@TransactionAttribute(value=TransactionAttributeType.REQUIRES_NEW)
public class DesignationGroupService {
final static Logger log = Logger.getLogger(DesignationGroupService.class);
@PersistenceContext(unitName = "campaign-pu")
EntityManager em;
DesignationGroupDao dgDao;
@PostConstruct
public void init(){
dgDao = new DesignationGroupDao(em);
}
public List<DesignationGroup> listDesignationGroups(Integer index , Integer count){
return dgDao.listDesignationGroups(index, count);
}
public DesignationGroup createDesignationGroup(DesignationGroup dom){
return dgDao.createDesignationGroup(dom);
}
public DesignationGroup getDesignationGroupById(Long domId){
DesignationGroup dg = dgDao.getDesignationGroupById(domId);
return dg;
}
public void updateDesignationGroup(Long domId , DesignationGroup dom) throws DBException{
dgDao.updateDesignationGroup(domId , dom);
}
}
| [
"[email protected]"
] | |
1db2d3f4b91c10c3d1531e5a0ec2b438894563f4 | 381df898393fc45217adba2a6c518c27fd2a91a8 | /src/Simulador/RegistradorTarea.java | ab3cd8c88b0906adc9aa64f180cbe433ad73c330 | [] | no_license | martinjedwabny/SimOil | 8ed202d293ec3938998b010edbefc2b201d77e30 | ddd6882269ccf07c074c0137fc9ce0df9c81cf3d | refs/heads/master | 2021-01-02T09:13:04.452999 | 2017-08-02T23:23:58 | 2017-08-02T23:23:58 | 99,168,881 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,323 | java | package Simulador;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import ProveedoraDeRigs.RIG;
import Tareas.CompraDeAgua;
import Tareas.PedidoPlanta;
import Tareas.PedidoRIG;
import Tareas.PedidoTanque;
import Tareas.TareaExcavacion;
import Tareas.TareaExtraccion;
import Tareas.TareaReinyeccion;
import Tareas.VentaDeGas;
import Tareas.VentaDePetroleo;
import Unidades.VolumenEnMetrosCubicos;
public class RegistradorTarea {
private float costos;
private float ventas;
private float precioCompraCombustible;
private float precioCompraAgua;
private float precioVentaGas;
private float precioVentaPetroleo;
private StockDePlantasSeparadoras plantasSeparadoras;
private StockDeTanques tanquesDeAgua;
private StockDeTanques tanquesDeGas;
private List<Pozo> pozos;
private Reservorio reservorio;
private Dictionary<PlantaSeparadora, VolumenEnMetrosCubicos> volumenSeparadoHoy;
public RegistradorTarea(
float precioCompraCombustible,
float precioCompraAgua,
float precioVentaGas,
float precioVentaPetroleo,
StockDePlantasSeparadoras plantasSeparadoras,
StockDeTanques tanquesDeAgua,
StockDeTanques tanquesDeGas,
List<Pozo> pozos,
Reservorio reservorio) {
this.precioCompraCombustible = precioCompraCombustible;
this.precioCompraAgua = precioCompraAgua;
this.precioVentaGas = precioVentaGas;
this.precioVentaPetroleo = precioVentaPetroleo;
this.plantasSeparadoras = plantasSeparadoras;
this.tanquesDeAgua = tanquesDeAgua;
this.tanquesDeGas = tanquesDeGas;
this.pozos = pozos;
this.reservorio = reservorio;
this.volumenSeparadoHoy = new Hashtable<PlantaSeparadora, VolumenEnMetrosCubicos>();
this.costos = 0f;
this.ventas = 0f;
}
public float getCostos() {
return costos;
}
public float getVentas() {
return ventas;
}
public float getSaldo() {
return ventas - costos;
}
public void registrarExtraccion(TareaExtraccion extraccion) {
if (extraccion.volumenAExtraer().dameVolumen() == 0f) return;
System.out.println(String.format("Extracción de volumen: %.10f litros, en Pozo: %d",
extraccion.volumenAExtraer().dameVolumen(),
extraccion.pozoAExtraer().hashCode()));
volumenSeparadoHoy.put(extraccion.plantaSeparadoraQueRecibeElVolumen(), extraccion.volumenAExtraer());
}
public void registrarExcavacion(TareaExcavacion excavacion) {
RIG rig = excavacion.rigAUtilizar();
float costoCombustible = rig.dameConsumoDiarioEnLitros() * precioCompraCombustible;
costos += costoCombustible;
}
public void registrarReinyeccion(TareaReinyeccion reinyeccion) {
if (reinyeccion.volumenAReinyectar().dameVolumen() == 0) return;
System.out.println(
String.format("Reinyección en Pozo: %d de volumen %.2f litros (sacados de Tanque: %d)",
reinyeccion.pozoAReinyectar().hashCode(),
reinyeccion.volumenAReinyectar().dameVolumen(),
reinyeccion.tanqueDeDondeSacarAgua().hashCode()));
}
public void registrarPedidoPlanta(PedidoPlanta pedido) {
float costoPedido = pedido.constructora().cotizarParaUn(pedido.volumenAConstruir());
costos += costoPedido;
System.out.println(
String.format("Se compra una Planta. Tiempo para finalizar: %d dias. El costo del pedido es: $ %.2f",
pedido.constructora().estimarTiempoEnDiasPara(pedido.volumenAConstruir()),
costoPedido));
}
public void registrarPedidoTanque(PedidoTanque pedido) {
float costoPedido = pedido.constructora().cotizarParaUn(pedido.volumenAConstruir());
costos += costoPedido;
System.out.println(String.format("Se compro un Tanque. Tiempo para finalizar: %d dias. Costo: %.2f",
pedido.constructora().estimarTiempoEnDiasPara(pedido.volumenAConstruir()),
costoPedido));
}
public void registrarCompraDeAgua(CompraDeAgua compra) {
float costoCompra = compra.volumenDeCompra().dameVolumen() * precioCompraAgua;
this.costos += costoCompra;
System.out.println(
String.format("Compra de Agua: %.2f litros. Costo: $%.2f",
compra.volumenDeCompra().dameVolumen(),
costoCompra));
}
public void registrarVentaDeGas(VentaDeGas venta) {
float gananciasVenta = venta.volumenDeVenta().dameVolumen() * precioVentaGas;
this.ventas += gananciasVenta;
System.out.println(
String.format("Venta de Gas: %.2f litros, por: $ %.2f",
venta.volumenDeVenta().dameVolumen(),
gananciasVenta));
}
public void registrarPedidoRIG(PedidoRIG pedido) {
float costoAlquiler = pedido.proveedoraDeRIGs().precioAlquierDiarioDe(pedido.rigAAlquilar()) * pedido.cantidadDeDiasDeAlquiler();
costos += costoAlquiler;
System.out.println(
String.format("Pedido de RIG para %d dias, costo: $ %.2f",
pedido.cantidadDeDiasDeAlquiler(),
costoAlquiler));
}
public void registrarVentaDePetroleo(VentaDePetroleo ventaDePetroleo) {
float gananciasDia = ventaDePetroleo.dameGanancias(precioVentaPetroleo);
ventas += gananciasDia;
System.out.println(
String.format("Venta de Pétroleo: $ %.2f",
gananciasDia));
}
public void registrarNuevoDia(int dia) {
System.out.println(String.format("\n-------------------------------------------------- Dia %d --------------------------------------------------\n", dia));
}
public void registrarEstadoGeneral() {
System.out.println(String.format("Estado general: "));
// plantas separadoras
System.out.println(String.format("- Hay %d Plantas Separadoras: (formato <Id, Volumen Procesado Hoy>)", plantasSeparadoras.damePlantasSeparadoras().size()));
for (PlantaSeparadora planta: plantasSeparadoras.damePlantasSeparadoras()) {
float separadoHoyPlanta = this.volumenSeparadoHoy.get(planta) == null ? 0f : this.volumenSeparadoHoy.get(planta).dameVolumen();
System.out.println(String.format("-- <Planta %d, %.2f litros, %.2f litros>",
planta.hashCode(),
planta.dameProcesamientoMaximoDiario().dameVolumen(),
separadoHoyPlanta));
}
this.volumenSeparadoHoy = new Hashtable<PlantaSeparadora, VolumenEnMetrosCubicos>();
// tanques de agua
if (tanquesDeAgua.dameTanques().isEmpty()) {
System.out.println(String.format("- Hay 0 Tanques de Agua"));
} else {
System.out.println(String.format("- Hay %d Tanques de Agua con capacidad maxima %.2f litros, y volumen ocupado:",
tanquesDeAgua.dameTanques().size(), tanquesDeAgua.dameTanques().get(0).dameVolumenMaximo().dameVolumen()));
System.out.print("[");
for (Tanque tanque: tanquesDeAgua.dameTanques()) {
System.out.print(String.format("%.2f, ",
tanque.dameVolumenOcupado().dameVolumen()));
}
System.out.println("]");
}
// tanques de gas
if (tanquesDeGas.dameTanques().isEmpty()) {
System.out.println(String.format("- Hay 0 Tanques de Gas"));
} else {
System.out.println(String.format("- Hay %d Tanques de Gas con capacidad maxima %.2f litros, y volumen ocupado:",
tanquesDeGas.dameTanques().size(), tanquesDeGas.dameTanques().get(0).dameVolumenMaximo().dameVolumen()));
System.out.print("[");
for (Tanque tanque: tanquesDeGas.dameTanques()) {
System.out.print(String.format("%.2f, ",
tanque.dameVolumenOcupado().dameVolumen()));
}
System.out.println("]");
}
// pozos
System.out.println(String.format("- Hay %d Pozos: (formato <Id, Presion actual en PSIA, Presion inicial en PSIA>)", pozos.size()));
for (Pozo pozo: pozos) {
System.out.println(String.format("-- <Pozo %d, %.2f, %.2f>",
pozo.hashCode(),
pozo.presionActual().damePresion(),
pozo.presionInicial().damePresion()));
}
// reservorio
System.out.println(String.format("- El reservorio tiene un compuesto actual: (petroleo: %.10f, agua: %.10f, gas: %.10f) y un volumen actual: %.2f (volumen inicial: %.2f)",
reservorio.dameCompuesto().damePorcentajeDePetroleoSobre100(),
reservorio.dameCompuesto().damePorcentajeDeAguaSobre100(),
reservorio.dameCompuesto().damePorcentajeDeGasSobre100(),
reservorio.dameVolumenActual().dameVolumen(),
reservorio.dameVolumenInicial().dameVolumen()));
}
public void registrarFinalizacion() {
System.out.println(String.format("\n---> Terminó\n"));
System.out.println(String.format("Costos totales: $ %.2f", costos));
System.out.println(String.format("Ventas totales: $ %.2f", ventas));
float saldo = getSaldo();
System.out.println(String.format("Saldo total: $ %.2f", saldo));
}
}
| [
"[email protected]"
] | |
90a0089f0ecd75e3053ca7c2ff768debecf30481 | 2f45b99b684f62b2e9413a302a22a7677c22580c | /cts/tests/tests/webkitsecurity/src/android/webkitsecurity/cts/WebkitTextBeforeTableColCrashTest.java | 2883d7ac65d3edeebe58254a48fdda1120c74d91 | [] | no_license | b2gdev/Android-JB-4.1.2 | 05e15a4668781cd9c9f63a1fa96bf08d9bdf91de | e66aea986bbf29ff70e5ec4440504ca24f8104e1 | refs/heads/user | 2020-04-06T05:44:17.217452 | 2018-04-13T15:43:57 | 2018-04-13T15:43:57 | 35,256,753 | 3 | 12 | null | 2020-03-09T00:08:24 | 2015-05-08T03:32:21 | null | UTF-8 | Java | false | false | 3,908 | java | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.webkitsecurity.cts;
import java.util.Date;
import android.net.Uri;
import android.util.Log;
import junit.framework.Assert;
import java.io.File;
import java.io.FileInputStream;
import android.webkit.WebView;
import android.webkit.WebSettings;
import android.webkit.MimeTypeMap;
import android.cts.util.PollingCheck;
import android.content.Context;
import android.content.res.AssetManager;
import android.test.UiThreadTest;
import android.test.ActivityInstrumentationTestCase2;
import android.webkitsecurity.cts.WebViewStubActivity;
/*
* This file acts as a template for the generation of other webkit tests.
*
* The contents of the assets/webkitsecuritytests directory will be scanned
* for html files, and for each one found a new class will be generated based
* on this template.
*
* The specific things that have to be done to this template are:
*
* 1. Change the name to Webkit + javify(testname) + Test
* 2. Change the private TEST_PATH value to the test's name
* 3. Change the logtag to shellify(testname)
* 4. Change the constructor name to <classname>
* 5. Save this as <classname>.java
* 6. TODO: Remove this comment
*
*/
public class WebkitTextBeforeTableColCrashTest extends ActivityInstrumentationTestCase2<WebViewStubActivity> {
private static final String LOGTAG = "WebkitTextBeforeTableColCrashTest";
private static final String TEST_PATH = "text-before-table-col-crash.html";
private static final int INITIAL_PROGRESS = 100;
private static long TEST_TIMEOUT = 20000L;
private static long TIME_FOR_LAYOUT = 1000L;
private WebView mWebView;
private boolean mIsUiThreadDone;
public WebkitTextBeforeTableColCrashTest() {
super("android.webkitsecurity.cts", WebViewStubActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mWebView = getActivity().getWebView();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
@UiThreadTest
public void testWebkitCrashes() throws Exception {
// set up the webview
mWebView = new WebView(getActivity());
getActivity().setContentView(mWebView);
// We need to be able to run JS for most of these tests
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
// Get the url for the test
Log.d(LOGTAG, TEST_PATH);
String url = "file:///android_asset/" + TEST_PATH;
Log.d(LOGTAG, url.toString());
// Run the test
assertLoadUrlSuccessfully(url);
}
private void assertLoadUrlSuccessfully(String url) {
mWebView.loadUrl(url);
waitForLoadComplete();
}
private void waitForLoadComplete() {
new PollingCheck(TEST_TIMEOUT) {
@Override
protected boolean check() {
return mWebView.getProgress() == 100;
}
}.run();
try {
Thread.sleep(TIME_FOR_LAYOUT);
} catch (InterruptedException e) {
Log.w(LOGTAG, "waitForLoadComplete() interrupted while sleeping for layout delay.");
}
}
}
| [
"[email protected]"
] | |
473fd5a9d52d7b939260d83c56fcdc8b1adaa87b | 849177b17d51e49da90d4216390a0a6df9d827a5 | /shp/2SS/src/com/New/servlet/AddNewsServlet.java | fd7f6e36d468db01cc206261820cd5df570772fb | [] | no_license | ashleyshi/shp | 7450a511e9e40e70d89d91a2b21bd55eeceb5ea0 | c60501125734dfb32f33ef9f283f0a248e62011c | refs/heads/master | 2020-12-03T08:14:35.827955 | 2017-06-28T15:23:40 | 2017-06-28T15:23:40 | 95,673,726 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,145 | java | package com.New.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.New.filter.*;
import com.New.dao.NewDao;
import com.New.entity.News;
public class AddNewsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");//设置request的编码方式
response.setCharacterEncoding("UTF-8");//设置response的编码方式
PrintWriter out=response.getWriter();
/*int id= Integer.parseInt(request.getParameter("id"));//获得页面传递过来的id
*/ String title = request.getParameter("title");//获得页面传递过来的title
//System.out.println("title:"+title);
String content = request.getParameter("content");//获得页面传递过来的content
//System.out.println("content:"+content);
String create_date=request.getParameter("create_date");//获得页面传递过来的time
// System.out.println("create_date:"+create_date);
String type = request.getParameter("type");
// System.out.println("type:"+type);
News news = new News();//申明一个News对象,把获得的参数放入该对象中
/*news.setId(id);*/
news.setTitle(title);
news.setContent(content);
news.setCreate_date(create_date);
news.setType(type);
try {
NewDao.addNew(news);
} catch (SQLException e) {
e.printStackTrace();
}
request.getRequestDispatcher("/pages/addSuccess.jsp").forward(request, response);//转发到指定的页面
out.flush();
out.close();
}
public void init()throws ServletException{
}
}
| [
"[email protected]"
] | |
680376957979ff0c961946a13327b68cd511aa55 | 829cb3e438f4b7a5c7e6649bab30a40df115d267 | /cmon-app-portlet/docroot/WEB-INF/service/org/oep/cmon/dao/report/NoSuchLephi_chitietException.java | 05bfed0a032323f446ef62ea6fc418b01f4dd69b | [
"Apache-2.0"
] | permissive | doep-manual/CMON-App | 643bc726ca55a268fb7e44e80b181642224b2b67 | 17007602673b0ecffbf844ad78a276d953e791a7 | refs/heads/master | 2020-12-29T00:29:01.395897 | 2015-06-29T08:00:58 | 2015-06-29T08:00:58 | 38,224,623 | 0 | 0 | null | 2015-06-29T02:56:41 | 2015-06-29T02:56:41 | null | UTF-8 | Java | false | false | 1,068 | java | /**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package org.oep.cmon.dao.report;
import com.liferay.portal.NoSuchModelException;
/**
* @author VIENPN
*/
public class NoSuchLephi_chitietException extends NoSuchModelException {
public NoSuchLephi_chitietException() {
super();
}
public NoSuchLephi_chitietException(String msg) {
super(msg);
}
public NoSuchLephi_chitietException(String msg, Throwable cause) {
super(msg, cause);
}
public NoSuchLephi_chitietException(Throwable cause) {
super(cause);
}
} | [
"[email protected]"
] | |
308c9dda77487d309b8cbb3de1e743af1b2f0e53 | 55b2fb6a2ce69a670216f0971246c9a13219be85 | /xc-service-api/src/main/java/com/xuecheng/api/search/EsCourseControllerApi.java | 744b0d5f09c9ffe4e573605aaeaf50b91d1454b7 | [] | no_license | w850640608/xcEduService01 | 50f494a708a779043b51503ab33755e0efb4be42 | cedb7e4290ce63aaf46ecd39537da83a38c3747f | refs/heads/master | 2022-12-30T00:30:52.942027 | 2020-10-20T07:06:00 | 2020-10-20T07:06:00 | 302,553,174 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 714 | java | package com.xuecheng.api.search;
import com.xuecheng.framework.domain.course.CoursePub;
import com.xuecheng.framework.domain.search.CourseSearchParam;
import com.xuecheng.framework.model.response.QueryResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
/**
* @Author wzg
* @Date 2020/9/21
* @Version 1.0
*/
@Api(value = "课程搜索",description = "课程搜索",tags = {"课程搜索"})
public interface EsCourseControllerApi {
//搜索课程信息
@ApiOperation("课程搜索")
public QueryResponseResult<CoursePub> list(int page, int size, CourseSearchParam courseSearchParam) throws IOException;
}
| [
"[email protected]"
] | |
cb0b2af9ea740e5575683a76fc922d1b771837f9 | 70eaf57f1dfccc852ee2ec08aab7709c63667aa7 | /UniversityRentingApplication/src/unitTestCases/TestViewRenter.java | d33c4fde14e27517cc7464fc83680dad69a9140a | [] | no_license | SunidhiKabra/SSDI_Project | 10ab238fff23f73190ebf313e11fe042e683fbfe | 3d08193445e2f1113667c2bee79b120ecd5d5f1f | refs/heads/master | 2021-04-15T06:59:47.219936 | 2018-03-28T04:04:46 | 2018-03-28T04:04:46 | 126,664,596 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,647 | java | package unitTestCases;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
import dao.ICustomerDao;
import model.*;
class TestViewRenter {
ICustomer customer = new Customer();
ICustomerDao customerDao = new ICustomerDao() {
public ICustomer getCustomerById(int id)
{
ICustomer testCustomer = new Customer();
testCustomer.setID(id);
testCustomer.setEmail("[email protected]");
testCustomer.setFirstName("abc");
testCustomer.setLastName("xyz");
testCustomer.setPassword("123");
testCustomer.setPhoneNumber("45678");
return testCustomer;
}
@Override
public void addCustomer(Customer customer) {
// TODO Auto-generated method stub
}
@Override
public ICustomer getCustomer(String email) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Customer> getCustomers() {
// TODO Auto-generated method stub
return null;
}
};
public boolean equals(Object object1, Object object2)
{
if (object1 instanceof ICustomer && object2 instanceof ICustomer) {
ICustomer cust1 = (ICustomer) object1;
ICustomer cust2 = (ICustomer) object2;
return cust1.getEmail().equals(cust2.getEmail()) &&
cust1.getPassword().equals(cust2.getPassword()) &&
cust1.getFirstName().equals(cust2.getFirstName()) &&
cust1.getLastName().equals(cust2.getLastName()) &&
cust1.getPhoneNumber().equals(cust2.getPhoneNumber());
}
return false;
}
@Test
void test() {
customer = customerDao.getCustomerById(1);
assertEquals(true, equals(customer, customerDao.getCustomerById(1)));
}
}
| [
"[email protected]"
] | |
186ab2bbc90814bc4fcd793ba9c473ba53f61b9e | 1a9d4c06c549683ca38899786116692fa001de81 | /app/src/main/java/android_myandfix/android_myandfix/Caclutor.java | 32aef7531d612f458182929225094382fe3a2701 | [] | no_license | huihui4045/Android_MyAndFix | 41491c05b0c51a88d103de5de9f160a23be2d9f7 | c15410d970fb788f4b65f08c863f07d0a0d96b8d | refs/heads/master | 2021-01-23T16:51:37.577120 | 2017-09-07T14:45:55 | 2017-09-07T14:45:55 | 102,749,113 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 189 | java | package android_myandfix.android_myandfix;
/**
* apk
*/
public class Caclutor {
public int caculator()
{
// 1
//10/0
int i=0;
int j=10;
//模拟异常产生
return j/i;
}
}
| [
"[email protected]"
] | |
4da584eaa8de25dee7aacfc09b9498eef109baea | 7bb5f6027d39cb689fd4675fc6a7850237145281 | /src/java/org/docma/plugin/implementation/WebContext.java | 7c24fc6098270602bffc74792149941c32916660 | [] | no_license | yarcovisth1/docmenta-app | 52b13e0ca07d35aeb9d3a6ff3458861143305305 | 1709e7d75ea90d06fab2779a6e012b8efbc667f0 | refs/heads/master | 2021-09-19T14:49:15.688073 | 2018-07-28T16:23:26 | 2018-07-28T16:23:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 775 | java | /*
* WebContext.java
*
* Copyright (C) 2013 Manfred Paula, http://www.docmenta.org
*
* This file is part of Docmenta. Docmenta is free software: you can
* redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Docmenta. If not, see <http://www.gnu.org/licenses/>.
*/
package org.docma.plugin.implementation;
import java.io.*;
/**
*
* @author MP
*/
public interface WebContext
{
File getWebAppDirectory();
// void detachPluginFromWebSessions(String pluginId);
}
| [
""
] | |
c74d974c6c04ecbc2f2b9574da87b29152fdf912 | 75289106fbc5bfef1d647dac0876507a92e5830c | /TestNG/src/Test/day1.java | f8b35f20ecb891b12e1e3ab9e37a1502e2ab2262 | [] | no_license | sushilPandey80/GitHub | 8b0c064b8661b1c8ade13cba6b0aa584d93c4293 | b513bbd07f6c7aa69357435fc29ac37a6d66ceee | refs/heads/master | 2020-05-24T04:03:32.095832 | 2020-05-09T09:24:16 | 2020-05-09T09:24:16 | 187,084,487 | 0 | 1 | null | 2020-05-09T09:53:09 | 2019-05-16T18:52:55 | HTML | UTF-8 | Java | false | false | 1,034 | java | package Test;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class day1 {
@org.testng.annotations.AfterTest
public void AfterTest()
{
System.out.println("execute after test");
}
@Parameters({"url","username","password"})
@Test
public void Demo(String urlstring,String user,String pass)
{
System.out.println(urlstring);
System.out.println(user);
System.out.println(pass);
}
@Test
public void lastexecution()
{
System.out.println("Last execution");
Assert.assertTrue(false);
}
@Test(dataProvider="getData")
public void Demo2Test(String username,String Password)
{
System.out.println(username);
System.out.println(Password);
}
@DataProvider
public Object getData()
{
Object[][] data=new Object[3][2];
data[0][0]="0firstusername";
data[0][1]="0firstpassword";
data[1][0]="1firstusername";
data[1][1]="1firstpassword";
data[2][0]="2firstusername";
data[2][1]="2firstpassword";
return data;
}
}
| [
"[email protected]"
] | |
0808b7d958f9ec75d92c2db330b4e91bd2b4b78c | 327d20fa26e224a9ae1dc85609ef2cbf90d2dc4a | /src/com/ydclient/model/AirUpdateModel.java | d506cb76c5779dffc71e831171fdd5ac88ab59e6 | [] | no_license | linojiang268/YunDuoClient | a4639967ba2e6dde02197ff462ff9c5d656dc34d | e470198feb11d9d0feaa74a6be81288d4c0b1ee4 | refs/heads/master | 2020-03-11T04:30:21.507950 | 2018-04-16T17:05:19 | 2018-04-16T17:05:19 | 129,778,020 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 223 | java | package com.ydclient.model;
import java.util.List;
/**
* 空调设备新增、修改
*
* @author ouArea
*
*/
public class AirUpdateModel {
public DeviceInfo deviceInfo;
public List<AirParamInfo> airParamInfos;
}
| [
"[email protected]"
] | |
bb3ca8121c8a0e668095c10e249d8f884092412a | 3146b42269d0b8f6f9f92cd267b863f4f7b6db56 | /src/main/java/ru/sbt/mipt/oop/receiver/EventReceiver.java | 72fbead4912b02923c6897a007a0321e96b0abac | [] | no_license | tanya124/smart-home-2021 | db8e0d5ec9d4ccb78214de1e8c5aa4009e01f5e2 | fddfd76dbb379ee70e30adaeb1ef2badaeba23c6 | refs/heads/master | 2023-04-08T19:02:00.430766 | 2021-03-24T20:41:50 | 2021-03-24T20:41:50 | 345,965,906 | 0 | 0 | null | 2021-08-16T08:11:02 | 2021-03-09T10:20:02 | Java | UTF-8 | Java | false | false | 159 | java | package ru.sbt.mipt.oop.receiver;
import ru.sbt.mipt.oop.events.SensorEvent;
public interface EventReceiver {
public SensorEvent getNextSensorEvent();
}
| [
"[email protected]"
] | |
db0802f4e3c0d2b4024f9ee9745cf006c3128cb8 | a8e155473a007a99fe4525eebf125211d96a1127 | /config/src/main/java/com/alibaba/nacos/config/server/service/repository/extrnal/ExternalConfigInfoAggrPersistServiceImpl.java | fe65994261622785f06929aac3c87c07d925d489 | [
"Apache-2.0"
] | permissive | caojiele/nacos | 168fbc575433b5ed8fee57c31670d2a5148d8936 | 81ae2a8bb6d95782b08dc0bebc89ed9f25b52d6d | refs/heads/master | 2023-06-21T03:48:51.204825 | 2023-06-12T07:50:26 | 2023-06-12T07:50:26 | 141,900,388 | 12 | 2 | Apache-2.0 | 2019-07-12T11:35:57 | 2018-07-22T13:58:03 | Java | UTF-8 | Java | false | false | 22,625 | java | /*
* Copyright 1999-2022 Alibaba Group Holding Ltd.
*
* 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.alibaba.nacos.config.server.service.repository.extrnal;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.configuration.ConditionOnExternalStorage;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.ConfigInfoAggr;
import com.alibaba.nacos.config.server.model.ConfigInfoChanged;
import com.alibaba.nacos.config.server.model.ConfigKey;
import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.service.datasource.DataSourceService;
import com.alibaba.nacos.config.server.service.datasource.DynamicDataSource;
import com.alibaba.nacos.config.server.service.repository.ConfigInfoAggrPersistService;
import com.alibaba.nacos.config.server.service.repository.PaginationHelper;
import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.plugin.datasource.MapperManager;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoAggrMapper;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.context.annotation.Conditional;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.support.TransactionTemplate;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.CONFIG_INFO_AGGR_ROW_MAPPER;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.CONFIG_INFO_CHANGED_ROW_MAPPER;
/**
* ExternalConfigInfoAggrPersistServiceImpl.
*
* @author lixiaoshuang
*/
@SuppressWarnings(value = {"PMD.MethodReturnWrapperTypeRule", "checkstyle:linelength"})
@Conditional(value = ConditionOnExternalStorage.class)
@Service("externalConfigInfoAggrPersistServiceImpl")
public class ExternalConfigInfoAggrPersistServiceImpl implements ConfigInfoAggrPersistService {
private DataSourceService dataSourceService;
protected JdbcTemplate jt;
protected TransactionTemplate tjt;
private MapperManager mapperManager;
public ExternalConfigInfoAggrPersistServiceImpl() {
this.dataSourceService = DynamicDataSource.getInstance().getDataSource();
this.jt = dataSourceService.getJdbcTemplate();
this.tjt = dataSourceService.getTransactionTemplate();
Boolean isDataSourceLogEnable = EnvUtil.getProperty(Constants.NACOS_PLUGIN_DATASOURCE_LOG, Boolean.class,
false);
this.mapperManager = MapperManager.instance(isDataSourceLogEnable);
}
@Override
public <E> PaginationHelper<E> createPaginationHelper() {
return new ExternalStoragePaginationHelperImpl<>(jt);
}
@Override
public String generateLikeArgument(String s) {
String fuzzySearchSign = "\\*";
String sqlLikePercentSign = "%";
if (s.contains(PATTERN_STR)) {
return s.replaceAll(fuzzySearchSign, sqlLikePercentSign);
} else {
return s;
}
}
@Override
public boolean addAggrConfigInfo(final String dataId, final String group, String tenant, final String datumId,
String appName, final String content) {
String appNameTmp = StringUtils.isBlank(appName) ? StringUtils.EMPTY : appName;
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
final Timestamp now = new Timestamp(System.currentTimeMillis());
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
String select = configInfoAggrMapper.select(Collections.singletonList("content"),
Arrays.asList("data_id", "group_id", "tenant_id", "datum_id"));
String insert = configInfoAggrMapper.insert(
Arrays.asList("data_id", "group_id", "tenant_id", "datum_id", "app_name", "content", "gmt_modified"));
String update = configInfoAggrMapper.update(Arrays.asList("content", "gmt_modified"),
Arrays.asList("data_id", "group_id", "tenant_id", "datum_id"));
try {
try {
String dbContent = jt.queryForObject(select, new Object[] {dataId, group, tenantTmp, datumId},
String.class);
if (dbContent != null && dbContent.equals(content)) {
return true;
} else {
return jt.update(update, content, now, dataId, group, tenantTmp, datumId) > 0;
}
} catch (EmptyResultDataAccessException ex) { // no data, insert
return jt.update(insert, dataId, group, tenantTmp, datumId, appNameTmp, content, now) > 0;
}
} catch (DataAccessException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e, e);
throw e;
}
}
@Override
public boolean batchPublishAggr(final String dataId, final String group, final String tenant,
final Map<String, String> datumMap, final String appName) {
try {
Boolean isPublishOk = tjt.execute(status -> {
for (Map.Entry<String, String> entry : datumMap.entrySet()) {
try {
if (!addAggrConfigInfo(dataId, group, tenant, entry.getKey(), appName, entry.getValue())) {
throw new TransactionSystemException("error in batchPublishAggr");
}
} catch (Throwable e) {
throw new TransactionSystemException("error in batchPublishAggr");
}
}
return Boolean.TRUE;
});
if (isPublishOk == null) {
return false;
}
return isPublishOk;
} catch (TransactionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e, e);
return false;
}
}
@Override
public boolean replaceAggr(final String dataId, final String group, final String tenant,
final Map<String, String> datumMap, final String appName) {
try {
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
Boolean isReplaceOk = tjt.execute(status -> {
try {
String appNameTmp = appName == null ? "" : appName;
removeAggrConfigInfo(dataId, group, tenant);
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
String sql = configInfoAggrMapper.insert(
Arrays.asList("data_id", "group_id", "tenant_id", "datum_id", "app_name", "content",
"gmt_modified"));
for (Map.Entry<String, String> datumEntry : datumMap.entrySet()) {
jt.update(sql, dataId, group, tenantTmp, datumEntry.getKey(), appNameTmp, datumEntry.getValue(),
new Timestamp(System.currentTimeMillis()));
}
} catch (Throwable e) {
throw new TransactionSystemException("error in addAggrConfigInfo");
}
return Boolean.TRUE;
});
if (isReplaceOk == null) {
return false;
}
return isReplaceOk;
} catch (TransactionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e, e);
return false;
}
}
@Override
public void removeSingleAggrConfigInfo(final String dataId, final String group, final String tenant,
final String datumId) {
final String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
String sql = configInfoAggrMapper.delete(Arrays.asList("data_id", "group_id", "tenant_id", "datum_id"));
try {
this.jt.update(sql, ps -> {
int index = 1;
ps.setString(index++, dataId);
ps.setString(index++, group);
ps.setString(index++, tenantTmp);
ps.setString(index, datumId);
});
} catch (CannotGetJdbcConnectionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e, e);
throw e;
}
}
@Override
public void removeAggrConfigInfo(final String dataId, final String group, final String tenant) {
final String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
String sql = configInfoAggrMapper.delete(Arrays.asList("data_id", "group_id", "tenant_id"));
try {
this.jt.update(sql, ps -> {
int index = 1;
ps.setString(index++, dataId);
ps.setString(index++, group);
ps.setString(index, tenantTmp);
});
} catch (CannotGetJdbcConnectionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e, e);
throw e;
}
}
@Override
public boolean batchRemoveAggr(final String dataId, final String group, final String tenant,
final List<String> datumList) {
final String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
final String sql = configInfoAggrMapper.batchRemoveAggr(datumList.size());
final Object[] args = new Object[3 + datumList.size()];
args[0] = dataId;
args[1] = group;
args[2] = tenantTmp;
System.arraycopy(datumList.toArray(), 0, args, 3, datumList.size());
try {
jt.update(sql, args);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e, e);
return false;
}
return true;
}
@Override
public int aggrConfigInfoCount(String dataId, String group, String tenant) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
String sql = configInfoAggrMapper.count(Arrays.asList("data_id", "group_id", "tenant_id"));
Integer result = jt.queryForObject(sql, Integer.class, new Object[] {dataId, group, tenantTmp});
if (result == null) {
throw new IllegalArgumentException("aggrConfigInfoCount error");
}
return result.intValue();
}
@Override
public int aggrConfigInfoCount(String dataId, String group, String tenant, List<String> datumIds, boolean isIn) {
if (datumIds == null || datumIds.isEmpty()) {
return 0;
}
final String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
String sql = configInfoAggrMapper.aggrConfigInfoCount(datumIds.size(), isIn);
List<Object> objectList = com.alibaba.nacos.common.utils.CollectionUtils.list(dataId, group, tenantTmp);
objectList.addAll(datumIds);
Integer result = jt.queryForObject(sql, Integer.class, objectList.toArray());
if (result == null) {
throw new IllegalArgumentException("aggrConfigInfoCount error");
}
return result.intValue();
}
@Override
public ConfigInfoAggr findSingleConfigInfoAggr(String dataId, String group, String tenant, String datumId) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
String sql = configInfoAggrMapper.select(
Arrays.asList("id", "data_id", "group_id", "tenant_id", "datum_id", "app_name", "content"),
Arrays.asList("data_id", "group_id", "tenant_id", "datum_id"));
try {
return this.jt.queryForObject(sql, new Object[] {dataId, group, tenantTmp, datumId},
CONFIG_INFO_AGGR_ROW_MAPPER);
} catch (EmptyResultDataAccessException e) {
// EmptyResultDataAccessException, indicating that the data does not exist, returns null
return null;
} catch (CannotGetJdbcConnectionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e, e);
throw e;
} catch (Exception e) {
LogUtil.FATAL_LOG.error("[db-other-error]" + e.getMessage(), e);
throw new RuntimeException(e);
}
}
@Override
public List<ConfigInfoAggr> findConfigInfoAggr(String dataId, String group, String tenant) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
String sql = configInfoAggrMapper.findConfigInfoAggrIsOrdered();
try {
return this.jt.query(sql, new Object[] {dataId, group, tenantTmp}, CONFIG_INFO_AGGR_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e, e);
throw e;
} catch (EmptyResultDataAccessException e) {
return Collections.emptyList();
} catch (Exception e) {
LogUtil.FATAL_LOG.error("[db-other-error]" + e.getMessage(), e);
throw new RuntimeException(e);
}
}
@Override
public Page<ConfigInfoAggr> findConfigInfoAggrByPage(String dataId, String group, String tenant, final int pageNo,
final int pageSize) {
String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
final int startRow = (pageNo - 1) * pageSize;
String sqlCountRows = configInfoAggrMapper.select(Arrays.asList("count(*)"),
Arrays.asList("data_id", "group_id", "tenant_id"));
String sqlFetchRows = configInfoAggrMapper.findConfigInfoAggrByPageFetchRows(startRow, pageSize);
PaginationHelper<ConfigInfoAggr> helper = this.createPaginationHelper();
try {
return helper.fetchPageLimit(sqlCountRows, new Object[] {dataId, group, tenantTmp}, sqlFetchRows,
new Object[] {dataId, group, tenantTmp}, pageNo, pageSize, CONFIG_INFO_AGGR_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e, e);
throw e;
}
}
@Override
public Page<ConfigInfoAggr> findConfigInfoAggrLike(final int pageNo, final int pageSize, ConfigKey[] configKeys,
boolean blacklist) {
String sqlCountRows = "SELECT count(*) FROM config_info_aggr WHERE ";
String sqlFetchRows = "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr WHERE ";
StringBuilder where = new StringBuilder(" 1=1 ");
// Whitelist, please leave the synchronization condition empty, there is no configuration that meets the conditions
if (configKeys.length == 0 && blacklist == false) {
Page<ConfigInfoAggr> page = new Page<>();
page.setTotalCount(0);
return page;
}
PaginationHelper<ConfigInfoAggr> helper = createPaginationHelper();
List<String> params = new ArrayList<>();
boolean isFirst = true;
for (ConfigKey configInfoAggr : configKeys) {
String dataId = configInfoAggr.getDataId();
String group = configInfoAggr.getGroup();
String appName = configInfoAggr.getAppName();
if (StringUtils.isBlank(dataId) && StringUtils.isBlank(group) && StringUtils.isBlank(appName)) {
break;
}
if (blacklist) {
if (isFirst) {
isFirst = false;
where.append(" AND ");
} else {
where.append(" AND ");
}
where.append('(');
boolean isFirstSub = true;
if (!StringUtils.isBlank(dataId)) {
where.append(" data_id NOT LIKE ? ");
params.add(generateLikeArgument(dataId));
isFirstSub = false;
}
if (!StringUtils.isBlank(group)) {
if (!isFirstSub) {
where.append(" OR ");
}
where.append(" group_id NOT LIKE ? ");
params.add(generateLikeArgument(group));
isFirstSub = false;
}
if (!StringUtils.isBlank(appName)) {
if (!isFirstSub) {
where.append(" OR ");
}
where.append(" app_name != ? ");
params.add(appName);
isFirstSub = false;
}
where.append(") ");
} else {
if (isFirst) {
isFirst = false;
where.append(" AND ");
} else {
where.append(" OR ");
}
where.append('(');
boolean isFirstSub = true;
if (!StringUtils.isBlank(dataId)) {
where.append(" data_id LIKE ? ");
params.add(generateLikeArgument(dataId));
isFirstSub = false;
}
if (!StringUtils.isBlank(group)) {
if (!isFirstSub) {
where.append(" AND ");
}
where.append(" group_id LIKE ? ");
params.add(generateLikeArgument(group));
isFirstSub = false;
}
if (!StringUtils.isBlank(appName)) {
if (!isFirstSub) {
where.append(" AND ");
}
where.append(" app_name = ? ");
params.add(appName);
isFirstSub = false;
}
where.append(") ");
}
}
try {
Page<ConfigInfoAggr> result = helper.fetchPage(sqlCountRows + where, sqlFetchRows + where, params.toArray(),
pageNo, pageSize, CONFIG_INFO_AGGR_ROW_MAPPER);
return result;
} catch (CannotGetJdbcConnectionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e, e);
throw e;
}
}
@Override
public List<ConfigInfoChanged> findAllAggrGroup() {
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
String sql = configInfoAggrMapper.findAllAggrGroupByDistinct();
try {
return jt.query(sql, new Object[] {}, CONFIG_INFO_CHANGED_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e);
throw e;
} catch (EmptyResultDataAccessException e) {
return null;
} catch (Exception e) {
LogUtil.FATAL_LOG.error("[db-other-error]" + e.getMessage(), e);
throw new RuntimeException(e);
}
}
@Override
public List<String> findDatumIdByContent(String dataId, String groupId, String content) {
ConfigInfoAggrMapper configInfoAggrMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.CONFIG_INFO_AGGR);
String sql = configInfoAggrMapper.select(Collections.singletonList("datum_id"),
Arrays.asList("data_id", "group_id", "content"));
try {
return this.jt.queryForList(sql, new Object[] {dataId, groupId, content}, String.class);
} catch (EmptyResultDataAccessException e) {
return null;
} catch (IncorrectResultSizeDataAccessException e) {
return null;
} catch (CannotGetJdbcConnectionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e, e);
throw e;
}
}
}
| [
"[email protected]"
] | |
89254c4d36c23ed0a1f7d1e496505bc6e277b1de | d2c92e50f69d11dcea7a80d3afdb60b2b781e507 | /app/src/main/java/sg/edu/ro/c346/id16046530/demolistview/MainActivity.java | 2068e3ba9e89601b100035cb264d9becbdd34533 | [] | no_license | NixWM/C347Lesson1SectionBDemoListView | 9ce42e718e4dfe294c49ae9a23ded9cedeb910ef | af51b5b9b9b8613bf5347b1c082b76f759fee93b | refs/heads/master | 2023-04-08T17:03:02.348182 | 2021-04-20T04:33:23 | 2021-04-20T04:33:23 | 359,681,825 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,573 | java | package sg.edu.ro.c346.id16046530.demolistview;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView lv;
ArrayAdapter aa;
ArrayList<Food> food;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) this.findViewById(R.id.lvFood);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Food selectedFood = food.get(position);
Toast.makeText(MainActivity.this, selectedFood.getName()
+ " Star: " + selectedFood.isStar(),
Toast.LENGTH_LONG).show();
}
});
// Create a few food objects in Food array
food = new ArrayList<Food>();
food.add(new Food("Ah Lat Coffee", false));
food.add(new Food("Rocky Choc", true));
food.add(new Food("Kid Cat Choc", true));
// Link this Activity object, the row.xml layout for
// each row and the food String array together
aa = new FoodAdapter(this, R.layout.row, food);
lv.setAdapter(aa);
}
} | [
"[email protected]"
] | |
bf7e2045480ce6b8af7aeacf3f317a5029dd3393 | 6a89bc412c16d703cb70d4e32751b7788d802188 | /src/com/wangml/MyPro05/testInterface/SuperMan.java | 912b048ae7c25d41684f0e7cee64dbb364ae86ba | [] | no_license | Merlin660/WelcomeClass | 6f664ad395ff49d571c56a40d00415652385cd02 | 4e17e15f9cc9131c953bf4b3a56fe42579eae945 | refs/heads/master | 2022-12-06T06:32:32.979057 | 2020-08-14T13:19:23 | 2020-08-14T13:19:23 | 287,535,596 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 433 | java | package com.wangml.MyPro05.testInterface;
//implements实现接口
public class SuperMan implements Volant, Honest {
@Override
public void fly() {
System.out.println("我是超人,我可以横着飞!");
}
@Override
public void stop() {
System.out.println("竖着停!");
}
@Override
public void helpOther() {
System.out.println("哪里call我,飞哪里!");
}
}
| [
"[email protected]"
] | |
5bb173bee5a82fa1c9fec354c64705f10a03a822 | 072975770c0099971bd1e864c2e085513f6835ac | /openhds-server/dao/src/main/java/org/openhds/dao/service/impl/BaseDaoImpl.java | 881baff4c08d30f79188cbf8e55e9bb13f9c5317 | [] | no_license | sm0017/COS-576 | 6b01de780b45991968773b089c90eb6e421c5fa0 | cec9301116f1b47950734834ffd4ac977a5e468b | refs/heads/master | 2021-01-23T13:37:12.162766 | 2017-03-15T19:12:11 | 2017-03-15T19:12:11 | 38,788,040 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,495 | java | package org.openhds.dao.service.impl;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.Type;
import org.openhds.dao.finder.ArgumentTypeFactory;
import org.openhds.dao.finder.FinderExecutor;
import org.openhds.dao.finder.NamingStrategy;
import org.openhds.dao.service.Dao;
import org.openhds.domain.model.AuditableEntity;
import org.openhds.domain.model.FieldWorker;
import org.openhds.domain.model.LocationHierarchy;
import org.openhds.domain.model.User;
@SuppressWarnings("unchecked")
public class BaseDaoImpl<T, PK extends Serializable> implements Dao<T, PK>, FinderExecutor<T> {
/** Model object type */
Class<T> entityType;
/** Hibernate session factory configured in applicationContext */
SessionFactory sessFact;
NamingStrategy namingStrategy;
ArgumentTypeFactory argumentTypeFactory;
public BaseDaoImpl(Class<T> entityType) {
if (entityType == null) {
throw new IllegalArgumentException(
"entity type not specified for dao");
}
this.entityType = entityType;
}
/** Persist the <code>newInstance</code> object into the database */
public PK save(T newInstance) {
getSession().flush();
return (PK) getSession().save(newInstance);
}
public PK create(T newInstance) {
getSession().flush();
return (PK) getSession().save(newInstance);
}
public <S> S merge(S newInstance){
return (S)getSession().merge(newInstance);
}
public void saveOrUpdate(T newInstance){
getSession().saveOrUpdate(newInstance);
}
/** Retrieve an object that was previously persisted to the
* database using the indicated <code>id</code> as primary key */
public T read(PK id) {
return (T) getSession().get(entityType, id);
}
/** Save changes made to a persistent object */
public void update(T transientObject) {
getSession().update(transientObject);
}
/** Remove an object from persistent storage in the database */
public void delete(T persistentObject) {
getSession().delete(persistentObject);
}
public void evict(T persistentObject) {
getSession().evict(persistentObject);
}
/** Retrieve an entity with the specified <code>propertyName</code>
* with the associated <code>value</code> */
public T findByProperty(String propertyName, Object value) {
Criteria criteria = getSession().createCriteria(entityType).add(Restrictions.eq(propertyName, value));
if (AuditableEntity.class.isAssignableFrom(entityType)) {
criteria = addImplicitRestrictions(criteria);
}
return (T) criteria.uniqueResult();
}
/** Retrieve a list of all objects of the DAO's <code>entityType</code> */
public List<T> findAll(boolean filterDeleted) {
Criteria criteria = getSession().createCriteria(entityType);
if (AuditableEntity.class.isAssignableFrom(entityType) ||
LocationHierarchy.class.isAssignableFrom(entityType) ||
FieldWorker.class.isAssignableFrom(entityType)) {
criteria = addImplicitRestrictions(criteria);
}
if (filterDeleted) {
criteria = criteria.add(Restrictions.eq("deleted", false));
}
return criteria.list();
}
/** Retrieve a list of all objects of the DAO's <code>entityType</code>
* and also limit the number or results returned specified by the index of
* <code>firstResult</code> and the amount of <code>maxResults</code> */
public List<T> findPaged(int maxResults, int firstResult) {
Criteria criteria = getSession().createCriteria(entityType);
if (AuditableEntity.class.isAssignableFrom(entityType) ||
LocationHierarchy.class.isAssignableFrom(entityType) ||
FieldWorker.class.isAssignableFrom(entityType) ||
User.class.isAssignableFrom(entityType)) {
criteria = addImplicitRestrictions(criteria);
}
return criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).
setFirstResult(firstResult).setMaxResults(maxResults).
list();
}
/** Retrieve the total number of unique entities in the database */
public long getTotalCount() {
Criteria criteria = getSession().createCriteria(entityType);
if (AuditableEntity.class.isAssignableFrom(entityType) ||
LocationHierarchy.class.isAssignableFrom(entityType) ||
FieldWorker.class.isAssignableFrom(entityType) ||
User.class.isAssignableFrom(entityType)) {
criteria = addImplicitRestrictions(criteria);
}
return (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
}
/** Looks at the name of the invoked class and method and matches these to the name
* of the Hibernate query */
public List<T> executeFinder(Method method, final Object[] queryArgs) {
final Query namedQuery = prepareQuery(method, queryArgs);
return (List<T>) namedQuery.list();
}
public Iterator<T> iterateFinder(Method method, final Object[] queryArgs) {
final Query namedQuery = prepareQuery(method, queryArgs);
return (Iterator<T>) namedQuery.iterate();
}
private Query prepareQuery(Method method, Object[] queryArgs) {
final String queryName = getNamingStrategy().queryNameFromMethod(
entityType, method);
final Query namedQuery = getSession().getNamedQuery(queryName);
String[] namedParameters = namedQuery.getNamedParameters();
if (namedParameters.length == 0) {
setPositionalParams(queryArgs, namedQuery);
} else {
setNamedParams(namedParameters, queryArgs, namedQuery);
}
return namedQuery;
}
private void setPositionalParams(Object[] queryArgs, Query namedQuery) {
if (queryArgs != null) {
for (int i = 0; i < queryArgs.length; i++) {
Object arg = queryArgs[i];
Type argType = getArgumentTypeFactory().getArgumentType(arg);
if (argType != null) {
namedQuery.setParameter(i, arg, argType);
} else {
namedQuery.setParameter(i, arg);
}
}
}
}
private void setNamedParams(String[] namedParameters, Object[] queryArgs,
Query namedQuery) {
if (queryArgs != null) {
for (int i = 0; i < queryArgs.length; i++) {
Object arg = queryArgs[i];
Type argType = getArgumentTypeFactory().getArgumentType(arg);
if (argType != null) {
namedQuery.setParameter(namedParameters[i], arg, argType);
} else {
if (arg instanceof Collection) {
namedQuery.setParameterList(namedParameters[i],
(Collection) arg);
} else {
namedQuery.setParameter(namedParameters[i], arg);
}
}
}
}
}
public List<T> findListByProperty(String propertyName, Object value, boolean filterDeleted) {
Criteria criteria = getSession().createCriteria(entityType).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).
add(Restrictions.eq(propertyName, value));
if (filterDeleted) {
criteria = criteria.add(Restrictions.eq("deleted", false));
}
return criteria.list();
}
public List<T> findListByPropertyPaged(String propertyName, Object value, int firstResult, int maxResults) {
Criteria criteria = getSession().createCriteria(entityType).add(Restrictions.eq(propertyName, value));
if (AuditableEntity.class.isAssignableFrom(entityType)) {
criteria = addImplicitRestrictions(criteria);
}
return (List<T>) criteria.setFirstResult(firstResult).setMaxResults(maxResults).
setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
}
public List<T> findListByPropertyPagedInsensitive(String propertyName, Object value, int firstResult, int maxResults) {
Criteria criteria = getSession().createCriteria(entityType).add(Restrictions.ilike(propertyName, (String)value, MatchMode.ANYWHERE));
if (AuditableEntity.class.isAssignableFrom(entityType)) {
criteria = addImplicitRestrictions(criteria);
}
return (List<T>) criteria.setFirstResult(firstResult).setMaxResults(maxResults).
setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
}
public List<T> findByExample(T exampleInstance,String... excludeProperty) {
Criteria crit = getSession().createCriteria(entityType);
Example example = Example.create(exampleInstance);
for (String exclude : excludeProperty) {
example.excludeProperty(exclude);
}
crit.add(example);
return crit.list();
}
public long getCountByProperty(String propertyName, Object value) {
Criteria criteria = getSession().createCriteria(entityType).add(Restrictions.eq(propertyName, value));
if (AuditableEntity.class.isAssignableFrom(entityType)) {
criteria = addImplicitRestrictions(criteria);
}
return (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
}
protected Criteria addImplicitRestrictions(Criteria criteria) {
return criteria.add(Restrictions.eq("deleted", false));
}
public void setSessionFactory(SessionFactory sessFact) {
this.sessFact = sessFact;
}
protected Session getSession() {
return sessFact.getCurrentSession();
}
public NamingStrategy getNamingStrategy() {
return namingStrategy;
}
public void setNamingStrategy(NamingStrategy namingStrategy) {
this.namingStrategy = namingStrategy;
}
public ArgumentTypeFactory getArgumentTypeFactory() {
return argumentTypeFactory;
}
public void setArgumentTypeFactory(ArgumentTypeFactory argumentTypeFactory) {
this.argumentTypeFactory = argumentTypeFactory;
}
}
| [
"[email protected]"
] | |
5cfcf61c1b23202708fe9f63ffed4da5be8fb3d5 | b644a85071e7a03b16f055eb5373f2aa30411fac | /app/src/main/java/com/example/movieapp/adapter/MoviesAdapter.java | 0f144b0a77870d7e3cb8ec43fdef76128c087554 | [] | no_license | charlesmwangi/Movie_App | 2acdfd89184c4d1f258ad644f1113c11d5d45f9b | 01504cd8f134c5b0dfb5871a4495a816ee28fa3b | refs/heads/master | 2020-12-08T12:28:26.024956 | 2020-01-10T06:29:59 | 2020-01-10T06:29:59 | 232,981,630 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,854 | java | package com.example.movieapp.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.movieapp.R;
import com.example.movieapp.model.Movie;
import com.squareup.picasso.Picasso;
import java.util.List;
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieViewHolder> {
private List<Movie> movies;
private int rowLayout;
private Context context;
public static final String IMAGE_URL_BASE_PATH="http://image.tmdb.org/t/p/w342//";
public MoviesAdapter(List<Movie> movies, int rowLayout, Context context) {
this.movies = movies;
this.rowLayout = rowLayout;
this.context = context;
}
//A view holder inner class where we get reference to the views in the layout using their ID
public static class MovieViewHolder extends RecyclerView.ViewHolder {
LinearLayout moviesLayout;
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
ImageView movieImage;
public MovieViewHolder(View v) {
super(v);
moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
movieImage = (ImageView) v.findViewById(R.id.movie_image);
movieTitle = (TextView) v.findViewById(R.id.title);
data = (TextView) v.findViewById(R.id.date);
movieDescription = (TextView) v.findViewById(R.id.description);
rating = (TextView) v.findViewById(R.id.rating);
}
}
@NonNull
@Override
public MoviesAdapter.MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(rowLayout, parent, false);
return new MovieViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MovieViewHolder holder, int position) {
String image_url = IMAGE_URL_BASE_PATH + movies.get(position).getPosterPath();
Picasso.get()
.load(image_url)
.placeholder(android.R.drawable.sym_def_app_icon)
.error(android.R.drawable.sym_def_app_icon)
.into(holder.movieImage);
holder.movieTitle.setText(movies.get(position).getTitle());
holder.data.setText(movies.get(position).getReleaseDate());
holder.movieDescription.setText(movies.get(position).getOverview());
holder.rating.setText(movies.get(position).getVoteAverage().toString());
}
@Override
public int getItemCount() {
return movies.size();
}
}
| [
"[email protected]"
] | |
5ddee82b1304389a2597d5d277a30c342487b5cc | b2a356e03af96c305edabc85453154892fd40e8f | /part3-data_abstraction/mod4/TPD-practice-projects/Traceable/src/model/Traceable.java | 1fdeb50b847996f374cb839a2b368c4576111d41 | [] | no_license | khoivan88/UBCx-How_to_program | 1265ca69408a3476dce74d7493587b1dd0319a70 | b026d74cde149eb36deb4035ea6266f8a0881791 | refs/heads/master | 2020-03-19T02:38:43.219125 | 2018-06-23T17:41:58 | 2018-06-23T17:41:58 | 135,647,431 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 117 | java | package model;
public interface Traceable {
String getLocation();
Object getTrace();
void track();
}
| [
"[email protected]"
] | |
5f694ec0f0c8c676fe619b3bb5b48e6a84006781 | f0568343ecd32379a6a2d598bda93fa419847584 | /modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201306/CustomFieldServiceInterfaceupdateCustomFields.java | 75b295c7c11b22dc37f0431d9188b5cb03e78e74 | [
"Apache-2.0"
] | permissive | frankzwang/googleads-java-lib | bd098b7b61622bd50352ccca815c4de15c45a545 | 0cf942d2558754589a12b4d9daa5902d7499e43f | refs/heads/master | 2021-01-20T23:20:53.380875 | 2014-07-02T19:14:30 | 2014-07-02T19:14:30 | 21,526,492 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,260 | java |
package com.google.api.ads.dfp.jaxws.v201306;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Updates the specified {@link CustomField} objects.
*
* @param customFields the custom fields to update
* @return the updated custom fields
*
*
* <p>Java class for updateCustomFields element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="updateCustomFields">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="customFields" type="{https://www.google.com/apis/ads/publisher/v201306}CustomField" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"customFields"
})
@XmlRootElement(name = "updateCustomFields")
public class CustomFieldServiceInterfaceupdateCustomFields {
protected List<CustomField> customFields;
/**
* Gets the value of the customFields property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the customFields property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCustomFields().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CustomField }
*
*
*/
public List<CustomField> getCustomFields() {
if (customFields == null) {
customFields = new ArrayList<CustomField>();
}
return this.customFields;
}
}
| [
"[email protected]"
] | |
fd76bde166c414b862ea0a184b837b823d6dfa1a | 022ac85c9a972e25a781be06bb9211a9753417cb | /showroom/showroom-ejb/src/main/java/artRoom/persistence/service/GalleryServiceRemote.java | fc11c50368f71f492693723b544952e0bdfc3f44 | [] | no_license | HendAjej/showroom-repo | f9c4ed6c9b451046b6b3a4219aa16326b651b11d | 0450ce9e157a34a2847b18fcf96fb6466efa9fe8 | refs/heads/master | 2020-05-21T21:43:07.077524 | 2017-05-03T05:53:43 | 2017-05-03T05:53:43 | 84,651,389 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 561 | java | package artRoom.persistence.service;
import java.util.List;
import javax.ejb.Remote;
import artRoom.entities.Gallery;
@Remote
public interface GalleryServiceRemote {
void addGallery(Gallery gallery);
Gallery findGalleryById(Integer id);
List<Gallery> findGalleryByName(String name);
void deleteGalleryById(Integer id);
void deleteGallery(Gallery gallery);
void updateGallery(Gallery gallery);
void updateGallery1(Gallery gallery,String address,String nom,Integer nbre,Integer star);
List<Gallery> findAllGallery();
}
| [
"[email protected]"
] | |
5b68946b784bc9ffede7ff0d696810d83011a9d8 | 70a43a6e4dd803e15139e5327dacf7a73baf70b3 | /src/Main.java | 33ae913eca3d50ee36d669f4059407f3082147c8 | [] | no_license | aakarshsingh/theMP3Grabber | 45764926fffd5b478e7f6da18aab904202ff330b | 00b14decbea6bef940c2e0b8dc8f23128decc62b | refs/heads/master | 2021-01-01T08:21:22.932618 | 2015-06-19T06:20:30 | 2015-06-19T06:20:30 | 37,705,245 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 162 | java | public class Main
{
public static void main(String[] args)
{
FirstFrame firstFrame=new FirstFrame();
firstFrame.setVisible(true);
}
}
| [
"[email protected]"
] | |
80d7efee2bf2fae3c9f21484e9e76c6a46e86fd4 | eed34a375e57419a134c72d2c5060d02a28c0a6a | /examplegereratordao/src/main/java/com/example/DaoGeneratorExample.java | 2633acf27d19f62b250e4bcfe5006a6c7331eb21 | [] | no_license | zhangtaoqf/MVPGreenDaoDemo | 1d5f8fd63fd50e22abba0844d7577819bb3e09de | 6b14cd5883ae24ecbfdbe129ef4eb4f728906490 | refs/heads/master | 2021-01-17T10:50:40.953545 | 2016-08-05T12:50:18 | 2016-08-05T12:50:18 | 65,004,458 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,523 | java | package com.example;
import org.greenrobot.greendao.generator.DaoGenerator;
import org.greenrobot.greendao.generator.Entity;
import org.greenrobot.greendao.generator.Property;
import org.greenrobot.greendao.generator.Schema;
/**
*
* 1.给这个工程module添加生成dao,entity,sesstion,master类的依赖greendao-generator.jar包
* compile 'org.greenrobot:greendao-generator:3.1.0'(直接添加在当前module的gradle文件中的dependencies节点中)
* 2.创建一个模式
* 一个模式对应一个数据库
* 一个数据库下对应多个表
*/
public class DaoGeneratorExample {
public static void main(String[] args) throws Exception {
/**
* 参数一:数据库版本
* 参数二:要存放的包
*/
Schema stus = new Schema(1, "com.example.db");
//添加一个表
Entity student = stus.addEntity("Student");
//给这个表添加响应的属性
//id属性
Property.PropertyBuilder propertyBuilder = student.addIdProperty();
Property.PropertyBuilder autoincrement = propertyBuilder.autoincrement();
//name属性
student.addStringProperty("name");
//身高,身高不为null
Property.PropertyBuilder height = student.addFloatProperty("height");
height.notNull();
//自动生成
//注意:目录一定是 '/' 不是 '\'
new DaoGenerator().generateAll(stus,"E:/demo_shangke/GreenDaoDemo3/app/src/main/java");
}
}
| [
"[email protected]"
] | |
1c2caf52cb75d41dad5f69ae7e788df7cfef5605 | 79fcf92274d45275735901e78deca508db42b385 | /AGDC/src/main/java/com/tomsung/agdc/controller/OperLogController.java | 327754dd66d71239a501b414f3cf20bf9003af72 | [] | no_license | lanshitou/test_dates_service | 2eb5e819674beb2bcc16e2e4104e9d91a28bc171 | 40292e3749fc16fdf790531141256da4c198b82e | refs/heads/master | 2020-04-13T10:55:07.856428 | 2018-12-26T09:22:19 | 2018-12-26T09:22:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,187 | java | package com.tomsung.agdc.controller;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageInfo;
import com.tomsung.agdc.common.ResultModel;
import com.tomsung.agdc.common.ResultStatus;
import com.tomsung.agdc.service.IOperLogService;
import com.tomsung.agdc.vo.OperateDevLogVo;
import com.tomsung.agdc.vo.OperateLogVo;
import io.swagger.annotations.ApiOperation;
/**
* 用户信息相关查询接口
* @author Administrator
*
*/
@RestController
@RequestMapping("/sys/operlog")
public class OperLogController {
@Autowired
private IOperLogService operLogService;
@GetMapping("/get_all_user_logs")
@ApiOperation(value = "获取所有用户的操作日志列表")
public Object getAllOperLogs(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
PageInfo<OperateLogVo> operLogs = operLogService.getOperLogs(pageNum, pageSize);
if (CollectionUtils.isNotEmpty(operLogs.getList())) {
return ResultModel.ok(operLogs);
}
return ResultModel.error(ResultStatus.ERR_OPER_LOG_NO_DATAS);
}
@GetMapping("/get_all_farmland_logs")
@ApiOperation(value = "获取该大棚的操作日志列表")
public Object getAllFarmlandLogs(
@RequestParam(value = "farmlandId") Integer farmlandId,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
PageInfo<OperateDevLogVo> operLogs = operLogService.getOperDevLogs(farmlandId, pageNum, pageSize);
if (CollectionUtils.isNotEmpty(operLogs.getList())) {
return ResultModel.ok(operLogs);
}
return ResultModel.error(ResultStatus.ERR_OPER_DEV_LOG_NO_DATAS);
}
}
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.