text stringlengths 10 2.72M |
|---|
package com.eazy.firda.eazy;
import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.eazy.firda.eazy.Tasks.JSONParser;
import com.eazy.firda.eazy.utils.GPSTracker;
import com.eazy.firda.eazy.utils.ImageFilePath;
import com.eazy.firda.eazy.utils.Misc;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import it.sauronsoftware.ftp4j.FTPClient;
import worker8.com.github.radiogroupplus.RadioGroupPlus;
public class BookActivity extends AppCompatActivity {
String submit_booking= "http://new.entongproject.com/api/customer/book_car";
TextView bookName, bookPhone, bookMail, bookDateStart,
bookDateEnd, bookDuration, bookPickUp, bookReturn, bookChgDate, bookChgLocation, totalWallet1, totalWallet2, totalCash;
Button submit;
RadioGroup groupPrice;
RadioGroupPlus groupTotal;
RadioButton daily, weekly, monthly, cash, wallet;
LinearLayout layTotal;
SharedPreferences sp;
SharedPreferences.Editor edit;
SimpleDateFormat day_name, day_number, month_name, date, time;
String search_dateStart, search_dateEnd, price_type, dateStart, dateEnd, locationPickup, locationReturn, member_id, book, car_id, login_as, booking_number;
String total_type = "";
String memberUrl = "http://new.entongproject.com/api/customer/call/profile";
String[] dataLicense, dataIc;
String licenseType, licenseResPath, icType, icResPath;
String uploadPath1, uploadPath2, url1, url2, name1, name2;
FTPClient client;
String[] ds, de;
int total = 0;
int interval, priceDay, priceWeek, priceMonth, tWallet, tCash, point;
ImageView imgLicense, imgPassport, delLicense, delPassport;
RelativeLayout layLicense, layPassport;
LinearLayout layUpload;
int GALLERY = 1, CAMERA = 2;
Bitmap bitmap;
String type = "";
Calendar c;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
this.getSupportActionBar().setTitle("");
bookName = (TextView)findViewById(R.id.book_name);
bookMail = (TextView)findViewById(R.id.book_email);
bookPhone = (TextView)findViewById(R.id.book_phone);
layUpload = findViewById(R.id.layUpload);
imgLicense = findViewById(R.id.imgLicense);
imgPassport = findViewById(R.id.imgPassport);
layLicense = findViewById(R.id.layLicense);
layPassport = findViewById(R.id.layPassport);
delLicense = findViewById(R.id.delLicense);
delPassport = findViewById(R.id.delPassport);
groupPrice = (RadioGroup)findViewById(R.id.group_payment);
daily = (RadioButton)findViewById(R.id.book_payday);
weekly = (RadioButton)findViewById(R.id.book_payweek);
monthly = (RadioButton)findViewById(R.id.book_paymonth);
bookDuration = (TextView)findViewById(R.id.book_duration);
bookDateStart = (TextView)findViewById(R.id.book_dateStart);
bookDateEnd = (TextView)findViewById(R.id.book_dateEnd);
bookChgDate = (TextView)findViewById(R.id.book_chgDate);
bookPickUp = (TextView)findViewById(R.id.book_pickupLocation);
bookReturn = (TextView)findViewById(R.id.book_returnLocation);
bookChgLocation = (TextView)findViewById(R.id.book_chgLocation);
layTotal = (LinearLayout)findViewById(R.id.lay_total);
groupTotal = (RadioGroupPlus) findViewById(R.id.group_total);
cash = (RadioButton)findViewById(R.id.total_cash);
wallet = (RadioButton)findViewById(R.id.total_wallet);
totalWallet1 = (TextView)findViewById(R.id.tag_total_wallet1);
totalWallet2 = (TextView)findViewById(R.id.tag_total_wallet2);
totalCash = (TextView)findViewById(R.id.tag_total_cash);
submit = (Button)findViewById(R.id.btn_book);
layTotal.setVisibility(View.GONE);
month_name = new SimpleDateFormat("MMMM", Locale.ENGLISH);
day_name = new SimpleDateFormat("EEE", Locale.ENGLISH);
day_number = new SimpleDateFormat("dd", Locale.ENGLISH);
date = new SimpleDateFormat("M/d/yyyy", Locale.ENGLISH);
time = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
client = new FTPClient();
sp = PreferenceManager.getDefaultSharedPreferences(this);
member_id = sp.getString("user_id", null);
login_as = sp.getString("login_as", null);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
car_id = extras.getString("car_id");
priceDay = extras.getInt("price_daily");
priceWeek = extras.getInt("price_weekly");
priceMonth = extras.getInt("price_monthly");
search_dateStart = sp.getString("search_dateStart", null);
search_dateEnd = sp.getString("search_dateEnd", null);
Date date1 = new Date();
Date date2 = new Date();
if(login_as.equals("member")){
layUpload.setVisibility(View.GONE);
}
else if(login_as.equals("guest")){
layUpload.setVisibility(View.VISIBLE);
}
layLicense.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
type = "license";
showPictureDialog();
}
});
layPassport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
type = "passport";
showPictureDialog();
}
});
delLicense.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imgLicense.setImageBitmap(null);
delLicense.setVisibility(View.GONE);
}
});
delPassport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imgPassport.setImageBitmap(null);
delPassport.setVisibility(View.GONE);
}
});
if(search_dateStart != null || search_dateEnd != null){
ds = search_dateStart.split("/");
de = search_dateEnd.split("/");
try{
date1 = date.parse(sp.getString("search_dateStart", null));
date2 = date.parse(sp.getString("search_dateStart", null));
}catch(ParseException e){
e.printStackTrace();
}
dateStart = day_name.format(date1) + ", " + ds[1] + " " + month_name.format(date1) + ", " + sp.getString("search_timeStart", null);
dateEnd = day_name.format(date2) + ", " + de[1] + " " + month_name.format(date2) + ", " + sp.getString("search_timeEnd", null);
interval = (int)sp.getLong("search_timeInterval", 0);
locationPickup = sp.getString("location_pickup", null);
locationReturn = sp.getString("location_return", null);
}else{
GPSTracker gps;
Double lat = 0.0, lng = 0.0;
String saveDateStart, saveDateEnd, saveTimeStart, saveTimeEnd, newMonths, newDays, newMonthe, newDaye;
int year, month, dayofmonth, hour, min;
int year2, month2, dayofmonth2, hour2, min2;
Date dt, dt2;
gps = new GPSTracker(getBaseContext(), BookActivity.this);
if(gps.canGetLocation()){
lng = gps.getLongitude();
lat = gps.getLatitude();
}
else{
gps.showSettingsAlert();
}
c = Calendar.getInstance(TimeZone.getDefault());
dt = c.getTime();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
dayofmonth = c.get(Calendar.DAY_OF_MONTH);
hour = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
dateStart = day_name.format(dt) + ", " + day_number.format(dt) + " " + month_name.format(dt)
+ ", " + time.format(dt);
if((month+1) < 10){
newMonths = "0" + (month+1);
}else{
newMonths = ""+ (month+1);
}
if(dayofmonth < 10){
newDays = "0" + dayofmonth;
}
else{
newDays = "" + dayofmonth;
}
saveDateStart = newMonths + "/" + newDays + "/" + String.valueOf(year);
saveTimeStart = time.format(dt);
c.add(dayofmonth, 3);
dt2 = c.getTime();
year2 = c.get(Calendar.YEAR);
month2 = c.get(Calendar.MONTH);
dayofmonth2 = c.get(Calendar.DAY_OF_MONTH);
hour2 = c.get(Calendar.HOUR_OF_DAY);
min2 = c.get(Calendar.MINUTE);
dateEnd = day_name.format(dt2) + ", " + day_number.format(dt2) + " " + month_name.format(dt2)
+ ", " + time.format(dt2);
interval = 3;
if((month2+1) < 10){
newMonthe = "0" + (month2+1);
}else{
newMonthe = ""+ (month2+1);
}
if(dayofmonth2 < 10){
newDaye = "0" + dayofmonth2;
}
else{
newDaye = "" + dayofmonth2;
}
saveDateEnd = newMonthe + "/" + newDaye + "/" + String.valueOf(year2);
saveTimeEnd = time.format(dt2);
edit.putString("location_pickup", "nearby");
edit.putString("location_return", "nearby");
edit.putLong("user_lat", Double.doubleToRawLongBits(lat));
edit.putLong("user_lang", Double.doubleToRawLongBits(lng));
edit.putString("search_dateStart", saveDateStart);
edit.putString("search_timeStart", saveTimeStart);
edit.putString("search_dateEnd", saveDateEnd);
edit.putString("search_timeEnd", saveTimeEnd);
edit.putLong("search_timeInterval", interval);
edit.putString("search_producer", "All");
edit.putInt("search_type1", 0);
edit.putInt("search_type2", 0);
edit.putInt("search_type3", 0);
edit.putInt("search_type4", 0);
edit.putString("search_transmission", "Both");
edit.putInt("search_minVal", 0);
edit.putInt("search_maxVal", 1000000);
}
if(member_id != null){
detailMember dm = new detailMember();
dm.execute();
}
bookDateStart.setText(dateStart);
bookDateEnd.setText(dateEnd);
bookDuration.setText(String.valueOf(interval));
bookPickUp.setText(locationPickup);
bookReturn.setText(locationReturn);
bookDuration.setEnabled(false);
if(interval % 7 == 0){
weekly.setVisibility(View.VISIBLE);
}else{
weekly.setVisibility(View.GONE);
}
if(interval % 30 == 0){
monthly.setVisibility(View.VISIBLE);
}else{
monthly.setVisibility(View.GONE);
}
point = sp.getInt("epoint", 0);
groupPrice.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.book_payday:
price_type = "Daily";
tCash = interval * priceDay;
tWallet = tCash - (int)((tCash * 0.1));
break;
case R.id.book_payweek:
price_type = "Weekly";
tCash = interval * priceWeek;
tWallet = tCash - (int)((tCash * 0.1));
break;
case R.id.book_paymonth:
price_type = "Monthly";
tCash = interval * priceMonth;
tWallet = tCash - (int)((tCash * 0.1));
break;
}
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
symbols.setGroupingSeparator(',');
DecimalFormat formatter = new DecimalFormat("###,###", symbols);
layTotal.setVisibility(View.VISIBLE);
totalCash.setText("RM " + formatter.format(tCash));
totalWallet1.setText("RM " + formatter.format(tCash));
totalWallet1.setPaintFlags(totalWallet1.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
totalWallet2.setText("RM " + formatter.format(tWallet));
if(login_as.equals("member")){
if(point < tWallet){
wallet.setEnabled(false);
}
else{
wallet.setEnabled(true);
}
}
else if(login_as.equals("guest")){
wallet.setEnabled(false);
}
Log.v("price_type", price_type);
}
});
bookChgDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent chgDate = new Intent(BookActivity.this, DateActivity.class);
startActivity(chgDate);
}
});
bookChgLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
groupTotal.setOnCheckedChangeListener(new RadioGroupPlus.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroupPlus radioGroupPlus, int i) {
switch(i){
case R.id.total_wallet:
total_type = "Wallet";
total = tWallet;
break;
case R.id.total_cash:
total_type = "Cash";
total = tCash;
break;
}
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(bookName.getText().length() == 0 || bookMail.getText().length() == 0 || bookPhone.getText().length() == 0){
Toast.makeText(getApplicationContext(), "Data is not completed", Toast.LENGTH_SHORT).show();
}else{
if(total_type == ""){
Toast.makeText(getApplicationContext(), "Data is not completed", Toast.LENGTH_SHORT).show();
}
else{
if(total == 0){
Toast.makeText(getApplicationContext(), "Data is not completed", Toast.LENGTH_SHORT).show();
}
else{
if(login_as.equals("guest")){
if(imgLicense.getDrawable() == null || imgPassport.getDrawable() == null){
Toast.makeText(getApplicationContext(), "Please choose license's photo", Toast.LENGTH_SHORT).show();
}
else{
dataLicense = copyfile(licenseResPath, "license");
uploadPath1 = dataLicense[0];
url1 = dataLicense[1];
name1 = dataLicense[2];
if(licenseType.equals("camera")){
File tmp = new File(licenseResPath);
boolean delLicense = tmp.delete();
if(delLicense)Log.v("source file:", "deleted");
}
dataIc = copyfile(icResPath, "passport");
uploadPath2 = dataIc[0];
url2 = dataIc[1];
name2 = dataIc[2];
if(icType.equals("camera")){
File tmp = new File(icResPath);
boolean delLicense = tmp.delete();
if(delLicense)Log.v("source file:", "deleted");
}
uploadPict up = new uploadPict();
up.execute(uploadPath1, uploadPath2);
booking b = new booking();
b.execute();
}
}
else{
url1 = "";
name1 = "";
url2 = "";
name2 = "";
booking b = new booking();
b.execute();
}
}
}
}
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera"
};
pictureDialog.setItems(pictureDialogItems, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0 :
choosePhotoFromGallery();
break;
case 1 :
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_CANCELED){
return;
}
if(requestCode == GALLERY){
if(data != null){
Uri contentURI = data.getData();
try{
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), contentURI);
if(type.equals("license")){
imgLicense.setImageBitmap(bitmap);
delLicense.setVisibility(View.VISIBLE);
licenseType = "gallery";
licenseResPath = ImageFilePath.getPath(this ,data.getData());
}
else if(type.equals("passport")){
imgPassport.setImageBitmap(bitmap);
delPassport.setVisibility(View.VISIBLE);
icType = "gallery";
icResPath = ImageFilePath.getPath(this ,data.getData());
}
// uploadImage(contentURI);
}catch (IOException e){
e.printStackTrace();
}
}
}
else if(requestCode == CAMERA){
bitmap = (Bitmap)data.getExtras().get("data");
if(type.equals("license")){
imgLicense.setImageBitmap(bitmap);
delLicense.setVisibility(View.VISIBLE);
licenseType = "camera";
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String tmp = "/" + timestamp.getTime() + ".jpeg";
File outFile = new File(Environment.getExternalStorageDirectory(), tmp);
try{
FileOutputStream fos = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
licenseResPath = Environment.getExternalStorageDirectory() + tmp;
Log.v("photo path", licenseResPath);
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e2){
e2.printStackTrace();
}
}
else if(type.equals("passport")){
imgPassport.setImageBitmap(bitmap);
delPassport.setVisibility(View.VISIBLE);
icType = "camera";
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String tmp = "/" + timestamp.getTime() + ".jpeg";
File outFile = new File(Environment.getExternalStorageDirectory(), tmp);
try{
FileOutputStream fos = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
icResPath = Environment.getExternalStorageDirectory() + tmp;
Log.v("photo path", icResPath);
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e2){
e2.printStackTrace();
}
}
}
}
private String[] copyfile(String path, String type){
String[] result;
String url, imgPath, newImgPath, currName, newName, extension, photoId;
newName = "";
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// imgString = Base64.encodeToString(bb, Base64.DEFAULT);
// imgPath = ImageFilePath.getPath(this ,data.getData());
Log.v("old image path", path);
currName = path.substring(path.lastIndexOf("/")+1);
extension = currName.substring(currName.lastIndexOf(".")+1);
photoId = Misc.randomString(20);
if(type.equals("license")){
newName = "license_" + photoId + "_" + timestamp.getTime() + "." + extension;
}
else if(type.equals("passport")){
newName = "passsport_" + photoId + "_" + timestamp.getTime() + "." + extension;
}
newImgPath = path.replace(currName, newName);
Log.v("new image path", newImgPath);
Misc.copyFile(path, newImgPath);
url = "http://new.entongproject.com/images/profile/" + newName;
result = new String[]{newImgPath, url, newName};
return result;
}
private class detailMember extends AsyncTask<Void, Void, JSONObject>{
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(BookActivity.this);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
}
@Override
protected JSONObject doInBackground(Void... voids) {
JSONParser jsonParser = new JSONParser();
JSONObject response = jsonParser.getJsonFromUrl(memberUrl, member_id);
return response;
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
try{
String result = jsonObject.getString("result");
if(result.equals("success")){
JSONObject u = jsonObject.getJSONObject("member");
bookName.setText(u.getString("name"));
bookPhone.setText(u.getString("phone"));
bookMail.setText(u.getString("email"));
bookName.setEnabled(false);
bookPhone.setEnabled(false);
bookMail.setEnabled(false);
}
else{
bookName.setText("");
bookPhone.setText("");
bookMail.setText("");
bookName.setEnabled(true);
bookPhone.setEnabled(true);
bookMail.setEnabled(true);
Log.v("result", jsonObject.getString("message"));
}
}catch(JSONException e){
e.printStackTrace();
}
progressDialog.dismiss();
}
}
private class uploadPict extends AsyncTask<String, Void, Void>{
ProgressDialog dialog = new ProgressDialog(BookActivity.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Uploading...");
this.dialog.dismiss();
}
@Override
protected Void doInBackground(String... strings) {
File imgLicense = new File(strings[0]);
File imgIc = new File(strings[1]);
try{
int permission = ActivityCompat.checkSelfPermission(BookActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
BookActivity.this, PERMISSIONS_STORAGE, 1
);
}
client.connect(getResources().getString(R.string.ftp_server),21);
client.login(getResources().getString(R.string.sftp_user), getResources().getString(R.string.sftp_password));
client.setType(FTPClient.TYPE_BINARY);
client.changeDirectory("/public_html/angkot/public/images/profile");
Misc.MyTransferListener tfl = new Misc().new MyTransferListener();
client.upload(imgLicense, tfl);
client.upload(imgIc, tfl);
boolean delLicense = imgLicense.delete();
boolean delIc = imgIc.delete();
if(delLicense){Log.v("status", "image deleted");}
else{Log.v("status", "image can't delete");}
if(delIc){Log.v("status", "image deleted");}
else{Log.v("status", "image can't delete");}
}catch (Exception e){
e.printStackTrace();
try {
client.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
this.dialog.dismiss();
}
}
private class booking extends AsyncTask<String, String, JSONObject> {
private ProgressDialog progressDialog;
@Override
protected void onPreExecute(){
progressDialog = new ProgressDialog(BookActivity.this);
progressDialog.setMessage("Save Boooking ...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
book = login_as + "|" + car_id + "|" + member_id
+ "|" + bookName.getText().toString()
+ "|" + bookPhone.getText().toString()
+ "|" + bookMail.getText().toString()
+ "|" + price_type + "|" + interval
+ "|" + sp.getString("search_dateStart", null) + " "
+ sp.getString("search_timeStart", null)
+ "|" + sp.getString("search_dateEnd", null) + " "
+ sp.getString("search_timeEnd", null)
+ "|" + total_type
+ "|" + total
+ "|" + url1 + "|" + name1
+ "|" + url2 + "|" + name2;
}
@Override
protected JSONObject doInBackground(String... data){
JSONParser jParser = new JSONParser();
Log.v("booking_url", submit_booking);
Log.v("booking_data", book);
//Log.v("screen_status", Integer.toString(screen_status2));
JSONObject mybook = jParser.getJsonFromUrl(submit_booking, book);
return mybook;
}
@Override
protected void onPostExecute(JSONObject mybook){
progressDialog.dismiss();
String result;
try{
result = mybook.getString("result");
Log.v("JSON", mybook.toString());
Log.v("result", result);
if(result.equals("success")){
booking_number = mybook.getString("booking_number");
AlertDialog.Builder builder = new AlertDialog.Builder(BookActivity.this);
builder.setTitle("Booking Success");
builder.setMessage("This is your booking number \n" + booking_number);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(member_id == null){
Intent redirect = new Intent(BookActivity.this, GuestMain.class);
startActivity(redirect);
}
else{
Intent redirect = new Intent(BookActivity.this, HomeActivity.class);
startActivity(redirect);
}
finish();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
else{
Toast.makeText(getBaseContext(), "Cannot submit data", Toast.LENGTH_SHORT).show();
}
}catch(JSONException e){
e.printStackTrace();
}
}
}
private void showBookNumber(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getBaseContext());
alertDialogBuilder.setTitle("Your booking is proceed");
alertDialogBuilder
.setMessage(booking_number)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
if(member_id == null){
Intent redirect = new Intent(BookActivity.this, GuestMain.class);
startActivity(redirect);
}
else{
Intent redirect = new Intent(BookActivity.this, HomeActivity.class);
startActivity(redirect);
}
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
|
package it.geek.annunci.service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ServiceFactory {
private static ApplicationContext cxt = null;
static{
cxt = new ClassPathXmlApplicationContext("applicationContext.xml");
}
public static AnnuncioServiceInterface getAnnuncioService(){
return (AnnuncioServiceInterface)cxt.getBean("aservice");
}
public static UtenteServiceInterface getUtenteService(){
return (UtenteServiceInterface)cxt.getBean("uservice");
}
}
|
package com.company.tests;
import com.company.Couple;
import org.junit.jupiter.api.Test;
import com.company.NOD;
import java.util.Random;
import static org.junit.jupiter.api.Assertions.*;
public class NODTest {
@Test
public void stressTest(int n){
long start = System.currentTimeMillis();
NOD nod = new NOD(0,0);
final Random random = new Random();
int a,b;
for (int i=0;i<n;i++){
a=random.nextInt(1000);
b=random.nextInt(1000);
long v = nod.calculate(a,b);
}
long finish = System.currentTimeMillis();
long timeOfMethod = finish-start;
System.out.println("Method execurion time: "+timeOfMethod);
System.out.println("Average time to execute a method NOD: "+timeOfMethod/n);
}
@Test
public void stressTestGeneration(){
stressTest(1000);
stressTest(1000000);
stressTest(1000000000);
}
@Test
public void simpleTestOne(){
NOD nod = new NOD(0,0);
Couple[] array= new Couple[4];
array[0]=new Couple(3,9);
array[1]=new Couple(27,81);
array[2]=new Couple(20,82);
long[] expected = {3,27,2};
long[] testarray = new long[3];
for (int i=0;i<3;i++){
testarray[i]=nod.calculate(array[i].getx(),array[i].gety());
}
assertArrayEquals(expected,testarray);
}
@Test
public void simpleTestTwo(){
NOD nod = new NOD(0,0);
Couple[] array= new Couple[10];
array[0]=new Couple(3,9);
array[1]=new Couple(27,81);
array[2]=new Couple(20,82);
array[3]=new Couple(5,19);
array[4]=new Couple(220,182);
array[5]=new Couple(221,182);
array[6]=new Couple(2000,1200);
array[7]=new Couple(50,51);
array[8]=new Couple(69,92);
array[9]=new Couple(200,8);
long[] expected = {3,27,2,1,2,13,400,1,13,8};
long[] testarray = new long[3];
for (int i=0;i<10;i++){
testarray[i]=nod.calculate(array[i].getx(),array[i].gety());
}
assertArrayEquals(expected,testarray);
}
}
|
package com.tencent.mm.plugin.appbrand.page;
import com.tencent.mm.plugin.appbrand.b.a;
/* synthetic */ class h$1 {
public static final /* synthetic */ int[] fjn = new int[a.values().length];
static {
try {
fjn[a.fjf.ordinal()] = 1;
} catch (NoSuchFieldError e) {
}
try {
fjn[a.fje.ordinal()] = 2;
} catch (NoSuchFieldError e2) {
}
try {
fjn[a.fjg.ordinal()] = 3;
} catch (NoSuchFieldError e3) {
}
try {
fjn[a.fjh.ordinal()] = 4;
} catch (NoSuchFieldError e4) {
}
}
}
|
package com.example.maximeglod.fbta;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class ActiviteSportive extends AppCompatActivity {
//Propriétés
private static AccesLocal accesLocal;
RadioButton r_nulle, r_modere, r_forte;
RadioGroup r_grp;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// On retire la barre de notifications pour afficher l'application en plein écran
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activite_sportive);
accesLocal = new AccesLocal(getApplicationContext());
r_nulle = (RadioButton) findViewById(R.id.btnNulle);
r_modere = (RadioButton) findViewById(R.id.btnModere);
r_forte = (RadioButton) findViewById(R.id.btnForte);
r_grp = (RadioGroup) findViewById(R.id.radioGroup);
btn = (Button) findViewById(R.id.save);
Double lObjectif = 0.0;
//On récupère l'activité sportive de l'utilisateur pour cocher le btn radio correspondant
if (accesLocal.recupactsport().equals("Intense")) {
r_forte.setChecked(true);
r_forte.toggle();
Double objectif = (accesLocal.totalcal()) / 1.82;
lObjectif = objectif;
} else if (accesLocal.recupactsport().equals("Modéré")) {
r_modere.setChecked(true);
r_modere.toggle();
Double objectif = (accesLocal.totalcal()) / 1.64;
lObjectif = objectif;
} else {
//L'activité est "détente"
r_nulle.setChecked(true);
r_nulle.toggle();
Double objectif = (accesLocal.totalcal()) / 1.375;
lObjectif = objectif;
}
final Double lObjectif2 = lObjectif;
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(getBaseContext(), MainActivity.class);
//ATTENTION UTILISATION DE VALEUR ARRONDI DONC DECALLAGE POSSIBLE DE QUELQUES CALORIES (Negligeable cependant)
//Mise à jour de l'activité sportive dans la base de données
if (r_forte.isChecked()) {
//Si l'activité forte est cochée
Double objmod = lObjectif2;
int objmod2 = (int) (objmod * 1.82);
accesLocal.majactsport("Intense", objmod2);
} else if (r_modere.isChecked()) {
//Si l'activité modéré est cochée
Double objmod = lObjectif2;
int objmod2 = (int) (objmod * 1.64);
accesLocal.majactsport("Modéré", objmod2);
} else {
//Si l'activité détente est cochée
Double objmod = lObjectif2;
int objmod2 = (int) (objmod * 1.375);
accesLocal.majactsport("Détente", objmod2);
}
Toast.makeText(getApplicationContext(), "L'activité choisie a bien été sauvegardée dans la base de données", Toast.LENGTH_LONG).show();
startActivityForResult(myIntent, 0);
}
});
}
}
|
package freeWork;
public class BasicMemberManager extends MemberManager{
public void add(BasicMember basicMember) {
System.out.println(basicMember.getBasicId()+" " + basicMember.getFirstName()+" " + basicMember.getLastName()+" " + "Adlı Basic Kullanıcı Sisteme Kayıt Edildi");
}
public void delete(BasicMember basicMember) {
System.out.println(basicMember.getBasicId()+" " + basicMember.getFirstName()+" " + basicMember.getLastName()+" " + "Adlı Basic Kullanıcı Sistemden Silindi");
}
}
|
package Collectionsss;
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListNaveen {
public static void main(String[] args) {
// VirtualCapacity.how do you change the virtual capacity
ArrayList<Object> ar = new ArrayList<Object>(20);
// ArrayList<Object> ar = new ArrayList<Object>(20); 20 is virtual capacity no
ar.add(10);
System.out.println(ar.size());
ar.add(20);
ar.add(35);
ar.add(56);
System.out.println(ar.size());
// List with other collection
ArrayList<Integer> numbers = new ArrayList<Integer>(Arrays.asList(10, 20, 30));
System.out.println(numbers);
for (Integer nolist : numbers) {
System.out.println(nolist);
}
ArrayList<String> names = new ArrayList<String>(Arrays.asList("Hi", "Bye", "Sai"));
System.out.println(names);
}
}
|
package org.rebioma.server.services;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.filter.InternalFilter;
import org.elasticsearch.search.aggregations.bucket.range.InternalRange;
import org.elasticsearch.search.aggregations.bucket.terms.InternalTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.hibernate.Session;
import org.rebioma.client.bean.ListStatisticAPIModel;
import org.rebioma.client.bean.StatisticModel;
import org.rebioma.client.services.StatisticType;
import org.rebioma.client.services.StatisticsService;
import org.rebioma.server.elasticsearch.search.OccurrenceSearch;
import org.rebioma.server.util.HibernateUtil;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.sencha.gxt.data.shared.loader.PagingLoadConfig;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;
import com.sencha.gxt.data.shared.loader.PagingLoadResultBean;
public class StatisticsServiceImpl extends RemoteServiceServlet implements StatisticsService {
private StatisticsDbProxy statisticsDbProxyEs = new StatisticsDbProxyESImpl();
private StatisticsDbProxy statisticsDbProxyPg = new StatisticsDbProxyPgImpl();
/**
*
*/
private static final long serialVersionUID = -1110165293224724280L;
public StatisticsServiceImpl() {
}
@Override
public ListStatisticAPIModel getStatisticsByTypeEnum(StatisticType statisticType) {
ListStatisticAPIModel result = new ListStatisticAPIModel();
try{
result = statisticsDbProxyEs.getStatisticsByTypeEnum(statisticType);
}catch(Exception e){
String packageName = e.getClass().getPackage().getName();
if(packageName.startsWith("org.elasticsearch")){
//si c'est une erreur ES, on bascule à Postgres
result = statisticsDbProxyPg.getStatisticsByTypeEnum(statisticType);
}else{
throw e;
}
}
return result;
}
@Override
public List<StatisticModel> getStatisticsByType(int statisticsType) {
List<StatisticModel> result = new ArrayList<StatisticModel>();
try{
result = statisticsDbProxyEs.getStatisticsByType(statisticsType);
}catch(Exception e){
String packageName = e.getClass().getPackage().getName();
if(packageName.startsWith("org.elasticsearch")){
//si c'est une erreur ES, on bascule à Postgres
result = statisticsDbProxyPg.getStatisticsByType(statisticsType);
}else{
throw e;
}
}
return result;
}
@Override
public List<StatisticModel> getStatisticDetails(
StatisticModel statisticModel) {
return getStatisticDetails(statisticModel.getStatisticType(), statisticModel.getTitle());
}
@Override
public PagingLoadResult<StatisticModel> getStatisticsByType(
int statisticsType, PagingLoadConfig config) {
List<StatisticModel> statisticModels = getStatisticsByType(statisticsType);
int start = config.getOffset();
int limit = statisticModels.size();
ArrayList<StatisticModel> subListToShow = new ArrayList<StatisticModel>();
if (config.getLimit() > 0) {
limit = Math.min(start + config.getLimit(), limit);
}
for (int i = config.getOffset(); i < limit; i++) {
subListToShow.add(statisticModels.get(i));
}
return new PagingLoadResultBean<StatisticModel>
(subListToShow, statisticModels.size(),config.getOffset());
}
/*@Override
public List<StatisticModel> getStatisticsByType(int statisticsType) {
List<StatisticModel> list = new ArrayList<StatisticModel>();
list.add(new StatisticModel(1,1, "Rakoto frah", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(2,1, "Rakoto frahq", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(3,1, "Rakoto frahw", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(4,1, "Rakoto frahr", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(5,1, "Rakoto fraht", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(6,1, "Rakoto frahf", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(7,1, "Rakoto frahh", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(8,1, "Rakoto frahj", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(9,1, "Bema kelyd", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(10,1, "Bema kelys", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(11,1, "Bema kelya", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(12,1, "Bema kelyz", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(13,1, "Bema kelyp", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(14,1, "Bema kelym", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(15,1, "Bema kelyg", 2, 3, 4, 5, 6, 7));
list.add(new StatisticModel(16,1, "Bema kelyh", 2, 3, 4, 5, 6, 7));
return list;
}*/
@Override
public PagingLoadResult<StatisticModel> getStatisticDetails(
StatisticModel statisticModel, PagingLoadConfig config) {
List<StatisticModel> statisticModels = getStatisticDetails(statisticModel);
int start = config.getOffset();
int limit = statisticModels.size();
ArrayList<StatisticModel> subListToShow = new ArrayList<StatisticModel>();
if (config.getLimit() > 0) {
limit = Math.min(start + config.getLimit(), limit);
}
for (int i = config.getOffset(); i < limit; i++) {
subListToShow.add(statisticModels.get(i));
}
return new PagingLoadResultBean<StatisticModel>
(subListToShow, statisticModels.size(),config.getOffset());
}
@Override
public List<StatisticModel> getStatisticDetails(int statisticsType,
String libelle) {
List<StatisticModel> ret = new ArrayList<StatisticModel>();
String colonne="";
switch (statisticsType) {
case 1:
colonne=" u.first_name || ' ' || upper(u.last_name) || ' - ' || u.institution || ' ' || u.email ";
break;
case 2:
colonne=" institutioncode ";
break;
case 3:
colonne=" collectioncode ";
break;
case 4:
colonne=" year ";
break;
default:
break;
}
String sql = "SELECT UPPER(acceptedorder) as acceptedorder,sum(\"private\") as nbprivate,sum(\"public\") as nbpublic,sum(reliable) as reliable, sum(awaiting) as awaiting,sum(questionnable) as questionnable,sum(invalidated) as invalidated,\n" +
"0 as \"all\"\n" +
"FROM \n" +
"( \n" +
"SELECT acceptedorder, "+colonne+" as libelle , \n" +
" count(*) as \"private\",0 as \"public\",0 as reliable,0 as awaiting,0 as questionnable,0 as invalidated,0 as \"all\"\n" +
"FROM occurrence LEFT JOIN \"user\" u ON u.email=occurrence.email\n" +
" WHERE 1=1 AND \n" +
"occurrence.\"public\" = FALSE \n" +
"GROUP BY " + colonne + " ,acceptedorder " +
"UNION\n" +
"SELECT acceptedorder , "+colonne+" as libelle, \n" +
" 0 as \"private\",count(*) as \"public\",0 as reliable,0 as awaiting,0 as questionnable,0 as invalidated,0 as \"all\"\n" +
"FROM occurrence LEFT JOIN \"user\" u ON u.email=occurrence.email\n" +
" WHERE 1=1 AND \n" +
"occurrence.\"public\" = TRUE \n" +
"GROUP BY " + colonne +" ,acceptedorder " +
"UNION\n" +
"SELECT acceptedorder , "+colonne+" as libelle, \n" +
" 0 as \"private\",0 as \"public\",count(*) as reliable,0 as awaiting,0 as questionnable,0 as invalidated,0 as \"all\"\n" +
"FROM occurrence LEFT JOIN \"user\" u ON u.email=occurrence.email\n" +
" WHERE 1=1 AND \n" +
"occurrence.reviewed = true\n" +
"GROUP BY " + colonne +" ,acceptedorder " +
"UNION\n" +
"SELECT acceptedorder , "+colonne+" as libelle, \n" +
" 0 as \"private\",0 as \"public\", 0 as reliable,count(*) as awaiting,0 as questionnable,0 as invalidated,0 as \"all\"\n" +
"FROM occurrence LEFT JOIN \"user\" u ON u.email=occurrence.email\n" +
" WHERE 1=1 AND \n" +
"occurrence.reviewed IS NULL AND occurrence.validated=TRUE\n" +
"GROUP BY " + colonne +" ,acceptedorder " +
"UNION\n" +
"SELECT acceptedorder , "+colonne+" as libelle, \n" +
" 0 as \"private\",0 as \"public\", 0 as reliable,0 as awaiting,count(*) as questionnable,0 as invalidated,0 as \"all\"\n" +
"FROM occurrence LEFT JOIN \"user\" u ON u.email=occurrence.email\n" +
" WHERE 1=1 AND \n" +
"occurrence.reviewed = FALSE\n" +
"GROUP BY " + colonne +" ,acceptedorder " +
"UNION\n" +
"SELECT acceptedorder , "+colonne+" as libelle, \n" +
" 0 as \"private\",0 as \"public\", 0 as reliable,0 as awaiting,0 as questionnable,count(*) as invalidated, 0 as \"all\"\n" +
"FROM occurrence LEFT JOIN \"user\" u ON u.email=occurrence.email\n" +
" WHERE 1=1 AND \n" +
"occurrence.validated = FALSE\n" +
"GROUP BY " + colonne +" ,acceptedorder " +
")as tbl\n" +
" WHERE libelle= ? " +
"GROUP BY upper(acceptedorder) ORDER BY upper(acceptedorder)";
System.out.println(sql);
Session sess = null;
Connection conn =null;
PreparedStatement st=null;
ResultSet rst=null;
try {
sess=HibernateUtil.getSessionFactory().openSession();
conn=sess.connection();
st = conn.prepareStatement(sql);
st.setString(1, libelle);
rst = st.executeQuery();
while(rst.next()) {
//if(rst.getString("libelle")!=null && !rst.getString("libelle").trim().isEmpty()){
StatisticModel obj = new StatisticModel();
obj.setNbInvalidated(rst.getInt("invalidated"));
obj.setNbAwaiting(rst.getInt("awaiting"));
obj.setNbPrivateData(rst.getInt("nbprivate"));
obj.setNbPublicData(rst.getInt("nbpublic"));
obj.setNbQuestionable(rst.getInt("questionnable"));
obj.setNbReliable(rst.getInt("reliable"));
obj.setStatisticType(statisticsType);
obj.setTitle(rst.getString("acceptedorder"));
ret.add(obj);
//}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(rst!=null) {
try {
rst.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if(st!=null) {
try {
st.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(sess!=null)
sess.close();
}
return ret;
}
}
|
package net.senmori.vanillatweaks.config.sections;
import net.senmori.senlib.configuration.option.BooleanOption;
import net.senmori.senlib.configuration.option.SectionOption;
import net.senmori.senlib.configuration.option.StringOption;
public class VillagerOption extends SectionOption {
public static VillagerOption newOption(String key) {
return new VillagerOption(key);
}
public final BooleanOption ENABLED = addOption("Villager Enabled Option", new BooleanOption("enabled", true));
public final StringOption FOLLOW_BLOCK = addOption("Villager Follow Block", new StringOption("follow-block", "emerald_block"));
public VillagerOption(String key) {
super(key, key);
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.module;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.openkm.bean.Document;
import com.openkm.bean.Folder;
import com.openkm.bean.Mail;
import com.openkm.bean.QueryResult;
import com.openkm.bean.ResultSet;
import com.openkm.core.AccessDeniedException;
import com.openkm.core.DatabaseException;
import com.openkm.core.ParseException;
import com.openkm.core.PathNotFoundException;
import com.openkm.core.RepositoryException;
import com.openkm.dao.bean.QueryParams;
public interface SearchModule {
/**
* Search for documents using it indexed content.
*
* @param expression Expression to be searched.
* @return A collection of document which content matched the searched expression.
* @throws RepositoryException If there is any general repository problem.
*/
public List<QueryResult> findByContent(String token, String expression) throws IOException, ParseException,
AccessDeniedException, RepositoryException, DatabaseException;
/**
* Search for documents by document name.
*
* @param expression Expression to be searched.
* @return A collection of document which name matched the searched expression.
* @throws RepositoryException If there is any general repository problem.
*/
public List<QueryResult> findByName(String token, String expression) throws IOException, ParseException,
AccessDeniedException, RepositoryException, DatabaseException;
/**
* Search for documents using it associated keywords.
*
* @param expression Expression to be searched.
* @return A collection of document which keywords matched the searched expression.
* @throws RepositoryException If there is any general repository problem.
*/
public List<QueryResult> findByKeywords(String token, Set<String> expression) throws IOException, ParseException,
AccessDeniedException, RepositoryException, DatabaseException;
/**
* Performs a complex search by content, name and keywords (between others).
*
* @param params The complex search elements.
* @return A collection of documents.
* @throws RepositoryException If there is any general repository problem.
* @throws IOException If something fails when parsing metadata.
*/
public List<QueryResult> find(String token, QueryParams params) throws IOException, ParseException,
AccessDeniedException, RepositoryException, DatabaseException;
/**
* Performs a complex search by content, name and keywords. Paginated version.
*
* @param params The complex search elements.
* @param offset Query result list offset.
* @param limit Query result list limit.
* @return A result set with the total of the results and a collection of document from the resulting query
* statement.
* @throws RepositoryException If there is any general repository problem.
*/
public ResultSet findPaginated(String token, QueryParams params, int offset, int limit) throws IOException,
ParseException, AccessDeniedException, RepositoryException, DatabaseException;
/**
* Save a search for future use.
*
* @param params The query params.
* @param name The name of the query to be saved.
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public long saveSearch(String token, QueryParams params) throws AccessDeniedException, RepositoryException,
DatabaseException;
/**
* Updated a saved search.
*
* @param params The query params.
* @param name The name of the query to be saved.
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public void updateSearch(String token, QueryParams params) throws AccessDeniedException, RepositoryException,
DatabaseException;
/**
* Get a saved search.
*
* @param name The name of the saved search to retrieve.
* @return The saved search query params.
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public QueryParams getSearch(String token, int qpId) throws AccessDeniedException, PathNotFoundException, RepositoryException,
DatabaseException;
/**
* Get all saved search.
*
* @return A collection with the names of the saved search.
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public List<QueryParams> getAllSearchs(String token) throws AccessDeniedException, RepositoryException, DatabaseException;
/**
* Delete a saved search.
*
* @param name The name of the saved search
* @throws PathNotFoundException If there is no saved search with this name.
* @throws RepositoryException If there is any general repository problem or the query fails
*/
public void deleteSearch(String token, long qpId) throws AccessDeniedException, RepositoryException,
DatabaseException;
/**
* Return a Keyword map. This is a hash with the keywords and the occurrence.
*
* @param filter A collection of keywords used to obtain the related document keywords.
* @return The keyword map.
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public Map<String, Integer> getKeywordMap(String token, List<String> filter) throws AccessDeniedException, RepositoryException,
DatabaseException;
/**
* Get the documents within a category
*
* @param categoryId The category id (UUID)
* @return A Collection of documents in the category
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public List<Document> getCategorizedDocuments(String token, String categoryId) throws AccessDeniedException, RepositoryException,
DatabaseException;
/**
* Get the folders within a category
*
* @param categoryId The category id (UUID)
* @return A Collection of folders in the category
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public List<Folder> getCategorizedFolders(String token, String categoryId) throws AccessDeniedException,RepositoryException,
DatabaseException;
/**
* Get the mails within a category
*
* @param categoryId The category id (UUID)
* @return A Collection of mails in the category
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public List<Mail> getCategorizedMails(String token, String categoryId) throws AccessDeniedException, RepositoryException,
DatabaseException;
/**
* Get the documents with a keyword
*
* @param keyword The keyword
* @return A Collection of documents with the keyword
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public List<Document> getDocumentsByKeyword(String token, String keyword) throws AccessDeniedException, RepositoryException,
DatabaseException;
/**
* Get the folders with a keyword
*
* @param keyword The keyword
* @return A Collection of folders with the keyword
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public List<Folder> getFoldersByKeyword(String token, String keyword) throws AccessDeniedException, RepositoryException,
DatabaseException;
/**
* Get the mails with a keyword
*
* @param keyword The keyword
* @return A Collection of mails with the keyword
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public List<Mail> getMailsByKeyword(String token, String keyword) throws AccessDeniedException, RepositoryException, DatabaseException;
/**
* Get the documents with a property value
*
* @param keyword The property value
* @return A Collection of documents with the property value
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public List<Document> getDocumentsByPropertyValue(String token, String group, String property, String value)
throws AccessDeniedException, RepositoryException, DatabaseException;
/**
* Get the folders with a property value
*
* @param property The property value
* @return A Collection of folders with the property value
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public List<Folder> getFoldersByPropertyValue(String token, String group, String property, String value)
throws AccessDeniedException, RepositoryException, DatabaseException;
/**
* Get the mails with a property value
*
* @param property The property value
* @return A Collection of mails with the property value
* @throws RepositoryException If there is any general repository problem or the query fails.
*/
public List<Mail> getMailsByPropertyValue(String token, String group, String property, String value)
throws AccessDeniedException, RepositoryException, DatabaseException;
/**
* Performs a simple search using on GQL language.
*
* @see http://jackrabbit.apache.org/api/1.6/org/apache/jackrabbit/commons/query/GQL.html
* @param statement The simple search in GQL language.
* @return A collection of documents.
* @throws RepositoryException If there is any general repository problem.
*/
public List<QueryResult> findSimpleQuery(String token, String statement) throws AccessDeniedException, RepositoryException,
DatabaseException;
/**
* Performs a simple search using GQL languahe. Paginated version.
*
* @see http://jackrabbit.apache.org/api/1.6/org/apache/jackrabbit/commons/query/GQL.html
* @param statement The simple search in GQL language.
* @param offset Query result list offset.
* @param limit Query result list limit.
* @return A result set with the total of the results and a collection of document from the resulting query
* statement.
* @throws RepositoryException If there is any general repository problem.
*/
public ResultSet findSimpleQueryPaginated(String token, String statement, int offset, int limit)
throws AccessDeniedException, RepositoryException, DatabaseException;
/**
* Find documents like a given one.
* @param uuid Uuid of the document to find other similar.
* @param maxResults Maximum number of returned documents.
* @return A result set with the total of the results and a collection of document from the resulting query
* statement.
* @throws RepositoryException If there is any general repository problem.
*/
public ResultSet findMoreLikeThis(String token, String uuid, int maxResults) throws AccessDeniedException, RepositoryException,
DatabaseException;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Main;
/**
*La clase instrucción, usada para administrar instrucciones
* @author Alberto Ortiz
*/
public class Instruccion {
/**
* El tipo de Enemigo
*/
private int tipoEnemigo;
/**
* El tiempo en milisegundos en el que aparece el Enemigo
*/
private int tiempoAparicion;
/**
* EL tiempo que el enemigo puede permanecer en pantalla, antes de desaparecer
*/
private int idleTime;
private int x, y;
/**
*
* @param enemigo - El tipo de enemigo
* @param aparicion - El tiempo que tarda en aparecer un nuevo enemigo, en milisegundos
* @param idle - EL tiempo en el que se queda un enemigo, antes de desaparecer.
*/
public Instruccion(int x, int y, int enemigo, int aparicion, int idle){
this.tipoEnemigo = enemigo;
this.tiempoAparicion = aparicion;
this.idleTime = idle;
this.x = x;
this.y = y;
}
int getTiempoAparicion() {
return this.tiempoAparicion;
}
int getTipoEnemigo() {
return this.tipoEnemigo;
}
int getIdleTime() {
return this.idleTime;
}
int getX() {
return x;
}
int getY() {
return y;
}
}
|
package com.identicum.config;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
@EnableOAuth2Client
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/webjars/**", "/css/**", "/favicon.*", "/imgs/**").permitAll()
.anyRequest().authenticated()
.and().logout().
logoutUrl("/logout")
.invalidateHttpSession(true).logoutSuccessUrl("/");
}
}
|
package BLL.Scheduling;
import java.io.Serializable;
import DAL.DAL_Factory;
import DAL.Service.DAL_Scheduling;
import basicas.service.Appointment;
public class BLL_Scheduling {
public void insert(Appointment sc){
DAL_Scheduling dao = DAL_Factory.getDAL_Scheduling();
dao.insert(sc);
}
public Appointment findById(Serializable key){
DAL_Scheduling dao = DAL_Factory.getDAL_Scheduling();
return dao.findByID(key);
}
public Appointment update(Appointment sc){
DAL_Scheduling dao = DAL_Factory.getDAL_Scheduling();
return dao.update(sc);
}
}
|
package hash;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public final class ClosedHash extends BaseHash {
private final List<List<String>> hashTable = new ArrayList<>();
public ClosedHash() {
for (int i = 0; i < DEFAULT_ITEMS_COUNT; i++) {
hashTable.add(new LinkedList<>());
}
}
private int hashFunction(String word) {
return word.length() % DEFAULT_ITEMS_COUNT;
}
public void add(String word) {
final int index = hashFunction(word);
hashTable.get(index).add(word);
}
public void delete(String word) {
if (contains(word)) {
final int index = this.hashFunction(word);
hashTable.get(index).remove(word);
}
}
public boolean contains(final String word) {
final int index = hashFunction(word);
return hashTable.get(index).contains(word);
}
public int getPosition(final String word) {
if (contains(word)) {
return hashFunction(word);
}
return INVALID_POSITION;
}
} |
package Controllers;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Models.EnterSubject;
import Models.Grade;
import dao.AddSubjectDao;
import dao.LearningResourcesDao;
/**
* Servlet implementation class LearningResourcesProcess
*/
@WebServlet("/LearningResourcesProcess")
public class LearningResourcesProcess extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
LearningResourcesDao ldao = new LearningResourcesDao();
public LearningResourcesProcess() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
RequestDispatcher dispatcher = null;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
AddSubjectDao addSujectDAO = new AddSubjectDao();
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
EnterSubject e = new EnterSubject();
e.setSubjectName(request.getParameter("subject"));
e.setClassID(Integer.parseInt(request.getParameter("grade")));
if (addSujectDAO.addSubject(e) == 1) {
request.setAttribute("submitDone", "saved successfull.!");
dispatcher = request.getRequestDispatcher("/LearningResources.jsp");
dispatcher.forward(request, response);
} else if (addSujectDAO.addSubject(e) == 2) {
request.setAttribute("submitDone","Subject already exist.");
request.getRequestDispatcher("LearningResources.jsp").forward(request, response);
} else {
request.getSession().setAttribute("submitDone", "Oops: something went wrong.");
request.getRequestDispatcher("LearningResources.jsp").forward(request, response);
}
}
}
|
package com.cpz.Demo14;
import java.util.LinkedList;
import java.util.List;
public class DemoLinkedList {
public static void main(String[] args) {
LinkedList<String> list=new LinkedList<>();
list.add("a");
list.add("b");
list.add("c");
System.out.println(list);
list.addFirst("d");//将元素添加到集合的开头
System.out.println(list);
}
}
|
package com.tencent.mm.plugin.account.friend.ui;
import android.os.Bundle;
import android.os.Message;
import com.tencent.mm.sdk.platformtools.ag;
class i$1 extends ag {
final /* synthetic */ i eNG;
i$1(i iVar) {
this.eNG = iVar;
}
public final void handleMessage(Message message) {
if ((i.a(this.eNG) == null || i.a(this.eNG).isShowing()) && !i.b(this.eNG)) {
i.a(this.eNG, i.c(this.eNG) + 1);
i.d(this.eNG).setProgress(i.c(this.eNG));
if (i.c(this.eNG) < i.d(this.eNG).getMax() - 2) {
sendEmptyMessageDelayed(0, 1000);
return;
}
i.e(this.eNG);
i.d(this.eNG).setIndeterminate(true);
if (!i.f(this.eNG)) {
if (i.a(this.eNG) != null) {
i.a(this.eNG).dismiss();
}
i.a(this.eNG, new Bundle());
}
}
}
}
|
package com.malsolo.mercury.spring.events.domain;
public class Type {
private String id;
//@Indexed(unique = true) it fails when creating Alarms without Type due to a 11000 code, duplicate: null :|
private Integer code;
private String description;
private Boolean active;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
@Override
public String toString() {
return com.google.common.base.Objects.toStringHelper(this)
.addValue(this.id)
.addValue(this.code)
.addValue(this.description)
.addValue(this.active)
.toString();
}
}
|
package BD;
import java.sql.*;
import UML.Equipo;
import java.util.ArrayList;
public class tablaEquipos {
private static Connection con;
public static void crearEquipo (Equipo equipo) throws Exception{
BaseDatos.conectar();
con = BaseDatos.getCon();
String plantilla = "INSERT INTO EQUIPOS VALUES (?,?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(plantilla);
ps.setInt(1, equipo.getIdEquipo());
ps.setString(2, equipo.getNombre());
ps.setString(3, equipo.getPais());
ps.setInt(4, equipo.getJefe().getIdPersona());
ps.setInt(5, equipo.getPreparador().getIdPersona());
ps.setInt(6, equipo.getEntrenador().getIdPersona());
int n = ps.executeUpdate();
ps.close();
if (n!=1)
throw new Exception("Se ha introducido más de un equipo");
System.out.println("Equipo insertado con éxito");
BaseDatos.desconectar();
}
public static Equipo equipoByIdEquipo (String idEquipo) throws Exception{
BaseDatos.conectar();
con = BaseDatos.getCon();
String plantilla = "SELECT * FROM EQUIPOS WHERE IDEQUIPO=?";
PreparedStatement ps = con.prepareStatement(plantilla);
ps.setString(1, idEquipo);
ResultSet resultado = ps.executeQuery();
if(resultado.next()){
Equipo equipoActual = new Equipo();
equipoActual.setIdEquipo(resultado.getInt("IDEQUIPO"));
equipoActual.setNombre(resultado.getString("NOMBRE"));
equipoActual.setPais(resultado.getString("PAIS"));
equipoActual.setJefe(tablaJefes.JefeByIdJefe(resultado.getInt("IDJEFE")));
equipoActual.setPreparador(tablaPreparadores.preparadorByIdPreparador(resultado.getString("IDPREPARADOR")));
equipoActual.setEntrenador(tablaEntrenadores.entrenadorByIdEntrenador(resultado.getString("IDENTRENADOR")));
BaseDatos.desconectar();
return equipoActual;
}
return null;
}
public static Equipo equipoByIdEquipo (Equipo equipo) throws Exception{
BaseDatos.conectar();
con = BaseDatos.getCon();
String plantilla = "SELECT * FROM EQUIPOS WHERE IDEQUIPO=?";
PreparedStatement ps = con.prepareStatement(plantilla);
ps.setInt(1, equipo.getIdEquipo());
ResultSet resultado = ps.executeQuery();
Equipo equipoActual = new Equipo();
equipoActual.setIdEquipo(resultado.getInt("IDEQUIPO"));
equipoActual.setNombre(resultado.getString("NOMBRE"));
equipoActual.setPais(resultado.getString("PAIS"));
equipoActual.setJefe(tablaJefes.JefeByIdJefe(resultado.getInt("IDJEFE")));
equipoActual.setPreparador(tablaPreparadores.preparadorByIdPreparador(resultado.getString("IDPREPARADOR")));
equipoActual.setEntrenador(tablaEntrenadores.entrenadorByIdEntrenador(resultado.getString("IDENTRENADOR")));
BaseDatos.desconectar();
return equipoActual;
}
public static ArrayList<Equipo> allEquipos() throws Exception{
BaseDatos.conectar();
con = BaseDatos.getCon();
String plantilla = "SELECT * FROM EQUIPOS";
PreparedStatement ps = con.prepareStatement(plantilla);
ResultSet resultado = ps.executeQuery();
ArrayList<Equipo> listaEquipos = new ArrayList();
while(resultado.next()){
Equipo equipoActual = new Equipo();
equipoActual.setIdEquipo(resultado.getInt("IDEQUIPO"));
equipoActual.setNombre(resultado.getString("NOMBRE"));
equipoActual.setPais(resultado.getString("PAIS"));
equipoActual.setJefe(tablaJefes.JefeByIdJefe(resultado.getInt("IDJEFE")));
//equipoActual.setPreparador(tablaPreparadores.preparadorByIdPreparador(resultado.getString("IDPREPARADOR")));
equipoActual.setEntrenador(tablaEntrenadores.entrenadorByIdEntrenador(resultado.getString("IDENTRENADOR")));
listaEquipos.add(equipoActual);
}
if(!listaEquipos.isEmpty()){
BaseDatos.desconectar();
return listaEquipos;
}
else{
return null;
}
}
public static void eliminarEquipo (String id) throws Exception{
BaseDatos.conectar();
con = BaseDatos.getCon();
String plantilla = "DELETE FROM EQUIPOS WHERE IDEQUIPO=?";
PreparedStatement ps = con.prepareStatement(plantilla);
ps.setString(1, id);
int n = ps.executeUpdate();
ps.close();
if (n!=1)
throw new Exception ("Se ha eliminado más de un equipo");
System.out.println("Equipo eliminado con éxito");
BaseDatos.desconectar();
}
public static void eliminarEquipo (Equipo equipo) throws Exception{
BaseDatos.conectar();
con = BaseDatos.getCon();
String plantilla = "DELETE FROM EQUIPOS WHERE IDEQUIPO=?";
PreparedStatement ps = con.prepareStatement(plantilla);
ps.setInt(1, equipo.getIdEquipo());
int n = ps.executeUpdate();
ps.close();
if (n!=1)
throw new Exception ("Se ha eliminado más de un equipo");
System.out.println("Equipo eliminado con éxito");
BaseDatos.desconectar();
}
public static void modNombreEquipo (Equipo equipo) throws Exception{
BaseDatos.conectar();
con = BaseDatos.getCon();
String plantilla = "UPDATE EQUIPOS SET NOMBRE=? WHERE IDEQUIPO=?";
PreparedStatement ps = con.prepareStatement(plantilla);
ps.setString(1, equipo.getNombre());
ps.setInt(2, equipo.getIdEquipo());
int n = ps.executeUpdate();
if (n!=1)
throw new Exception ("Se ha modificado más de un equipo");
System.out.println("Equipo modificado con éxito");
BaseDatos.desconectar();
}
public static void modPaisEquipo (Equipo equipo) throws Exception{
BaseDatos.conectar();
con = BaseDatos.getCon();
String plantilla = "UPDATE EQUIPOS SET PAIS=? WHERE IDEQUIPO=?";
PreparedStatement ps = con.prepareStatement(plantilla);
ps.setString(1, equipo.getPais());
ps.setInt(2, equipo.getIdEquipo());
int n = ps.executeUpdate();
if (n!=1)
throw new Exception ("Se ha modificado más de un equipo");
System.out.println("Equipo modificado con éxito");
BaseDatos.desconectar();
}
}
|
package quiz16;
public class MainClass {
public static void main(String[] args) {
Shape r = new Rect(3,5,"사각형");
System.out.println(r.getArea());
Shape c = new Circle(4,"원");
System.out.println(c.getArea());
}
}
|
package st.bookstore;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;
@Component
@Scope(SCOPE_PROTOTYPE) // because we share instances which store state
public class PerformanceTracker {
private final ApplicationProperties applicationProperties;
private LocalDateTime startTime;
private LocalDateTime endTime;
public PerformanceTracker(ApplicationProperties applicationProperties) {
this.applicationProperties = applicationProperties;
}
public void startTracking() {
if (applicationProperties.isDebug()) {
}
}
public void endTracikng() {
}
}
|
package kimmyeonghoe.cloth.domain.question;
import java.time.LocalDate;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Question {
private int questionNum;
private String title;
private String content;
@JsonFormat(pattern="yyyy-MM-dd", timezone="Asia/Seoul")
private LocalDate regDate;
private String answerContent;
private String userId;
}
|
package com.dio.live.repositoy;
import com.dio.live.model.WorkDay;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
*
* @author Evandro
*/
@Repository
public interface WorkDayRepository extends JpaRepository<WorkDay, Long>{
}
|
package org.sagebionetworks.repo.manager.oauth;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.sagebionetworks.repo.model.oauth.OAuthProvider;
import org.sagebionetworks.repo.model.oauth.ProvidedUserInfo;
import org.sagebionetworks.repo.model.principal.AliasType;
public class OAuthManagerImplUnitTest {
private OAuthManagerImpl oauthManager;
private OAuthProviderBinding providerBinding;
private OAuthProvider PROVIDER_ENUM = OAuthProvider.ORCID;
@Before
public void before() throws Exception {
oauthManager = new OAuthManagerImpl();
Map<OAuthProvider, OAuthProviderBinding> providerMap = new HashMap<OAuthProvider, OAuthProviderBinding>();
providerBinding = Mockito.mock(OAuthProviderBinding.class);
providerMap.put(PROVIDER_ENUM, providerBinding);
oauthManager.setProviderMap(providerMap);
}
@Test
public void testGetAuthorizationUrl() {
String redirUrl = "redirectUrl";
String expected = "http://foo.bar.com?response_type=code&redirect_uri="+redirUrl;
when(providerBinding.getAuthorizationUrl(redirUrl)).thenReturn(expected);
assertEquals(expected, oauthManager.getAuthorizationUrl(PROVIDER_ENUM, redirUrl, null));
}
@Test
public void testGetAuthorizationUrlWithState() {
String redirUrl = "redirectUrl";
String state = "some state#@%";
String authUrl = "http://foo.bar.com?response_type=code&redirect_uri="+redirUrl;
String expected = authUrl+"&state="+URLEncoder.encode(state);
when(providerBinding.getAuthorizationUrl(redirUrl)).thenReturn(authUrl);
assertEquals(expected, oauthManager.getAuthorizationUrl(PROVIDER_ENUM, redirUrl, state));
}
@Test
public void testValidateUserWithProvider() {
String authCode = "xxx";
String redirUrl = "redirectUrl";
ProvidedUserInfo expected = new ProvidedUserInfo();
expected.setUsersVerifiedEmail("foo@bar.com");
when(providerBinding.validateUserWithProvider(authCode, redirUrl)).thenReturn(expected);
assertEquals(expected, oauthManager.validateUserWithProvider(PROVIDER_ENUM, authCode, redirUrl));
}
@Test
public void testRetrieveProvidersId() {
String authCode = "xxx";
String redirUrl = "redirectUrl";
AliasAndType expected = new AliasAndType("ID", AliasType.USER_ORCID);
when(providerBinding.retrieveProvidersId(authCode, redirUrl)).thenReturn(expected);
assertEquals(expected, oauthManager.retrieveProvidersId(PROVIDER_ENUM, authCode, redirUrl));
}
}
|
/*
* 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 developerWorks.Servlets;
import developerWorks.beans.User;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Eric
*/
public class submitServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
User formData = new User();
formData.setFirstName(request.getParameter("FName"));
formData.setLastName(request.getParameter("LName"));
formData.setEmail(request.getParameter("UserID"));
formData.setPassword(request.getParameter("Password"));
formData.setRePassword(request.getParameter("RePassword"));
formData.setDisplayName(request.getParameter("alias"));
formData.setCountry(request.getParameter("CountryOfRes"));
formData.setCity(request.getParameter("City"));
formData.setLanguage(request.getParameter("Language"));
formData.setSecurityQuestion(request.getParameter("SecurityQues"));
formData.setSecurityAnswer(request.getParameter("SecurityAns"));
if(request.getParameter("NC_CHECK_EMAIL") != null)
formData.setByEmail(true);
else
formData.setByEmail(false);
if(request.getParameter("NC_CHECK_OTHER") != null)
formData.setByTelephoneOrPostalMail(true);
else
formData.setByTelephoneOrPostalMail(false);
String urlSuccess = "submitPage.jsp";
String urlFail = "index.jsp";
RequestDispatcher rd = request.getRequestDispatcher(urlFail);
request.setAttribute("formData", formData);
if(formData.isValid()){
RequestDispatcher r = request.getRequestDispatcher(urlSuccess);
r.forward(request, response);
//response.sendRedirect(urlSuccess);
} else {
request.setAttribute("errorMessage", "Invalid Email Address");
rd.include(request, response);
}
//}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
/*
* 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 edu.byui.cs313.model;
import java.sql.Date;
/**
*
* @author jesus
*/
public class Comment {
int commentId;
String time;
String name;
String commentText;
public int getCommentId() {
return commentId;
}
public void setCommentId(int commentId) {
this.commentId = commentId;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCommentText() {
return commentText;
}
public void setCommentText(String nameText) {
this.commentText = nameText;
}
}
|
package javabasico.aula33labs;
public class ContaCorrente {
private int numero;
private double saldo;
private boolean chequeEspecial;
private double limite;
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
public double getSaldo() {
return saldo;
}
public void setSaldo(double saldo) {
this.saldo = saldo;
}
public void isChequeEspecial(boolean chequeEspecial) {
this.chequeEspecial = chequeEspecial;
}
public double getlimite() {
return limite;
}
public void setLimite(double limite) {
this.limite = limite;
}
void realizarSaque (double valor) {
if (saldo >= valor) {
saldo -= valor;
System.out.println("Saque realizado com Sucesso" );
} else if (chequeEspecial == true && (saldo + limite) >= valor) {
saldo -= valor;
System.out.println("Saque realizado com Sucesso");
usandoLimite();
} else {
System.out.println("Conta nao tem saldo suficiente!!!");
}
}
void depositar (double valor) {
saldo = saldo + valor;
System.out.println("Deposito Realizado");
}
void consultarSaldo () {
System.out.println("Saldo é " + saldo );
}
void usandoLimite () {
System.out.println("Seu limite é " + limite + " e voce ja usou " + (limite + saldo));
}
}
|
/*
* 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 latihancruddesktop.ui.master;
/**
*
* @author KENDAY
*/
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import latihancruddesktop.Main;
import latihancruddesktop.domain.Peserta;
import latihancruddesktop.ui.tableModel.MasterPesertaTableModel;
import latihancruddesktop.utils.DatabaseConnection;
import latihancruddesktop.utils.ErrorDialog;
import latihancruddesktop.utils.TableUtil;
public class MasterPeserta extends javax.swing.JPanel {
public static final String PANEL_NAME = "Master Peserta";
private static MasterPeserta panel;
private List<Peserta> listPeserta;
private Peserta peserta;
/**
* Creates new form MasterPeserta
*/
public MasterPeserta() {
initComponents();
loadDataToTable();
tblPeserta.getSelectionModel().addListSelectionListener(new TableSelection());
}
public static MasterPeserta getPanel() {
if (panel == null) {
panel = new MasterPeserta();
}
return panel;
}
private class TableSelection implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
if (tblPeserta.getSelectedRow() >= 0) {
peserta = listPeserta.get(tblPeserta.getSelectedRow());
}
}
}
/**
* 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() {
jToolBar1 = new javax.swing.JToolBar();
btnTambah = new javax.swing.JButton();
btnEdit = new javax.swing.JButton();
btnHapus = new javax.swing.JButton();
btnTutup = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tblPeserta = new javax.swing.JTable();
jToolBar1.setRollover(true);
btnTambah.setText("Tambah");
btnTambah.setFocusable(false);
btnTambah.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnTambah.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnTambah.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTambahActionPerformed(evt);
}
});
jToolBar1.add(btnTambah);
btnEdit.setText("Edit");
btnEdit.setFocusable(false);
btnEdit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnEdit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditActionPerformed(evt);
}
});
jToolBar1.add(btnEdit);
btnHapus.setText("Hapus");
btnHapus.setFocusable(false);
btnHapus.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnHapus.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnHapus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHapusActionPerformed(evt);
}
});
jToolBar1.add(btnHapus);
btnTutup.setText("Tutup");
btnTutup.setFocusable(false);
btnTutup.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnTutup.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnTutup.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTutupActionPerformed(evt);
}
});
jToolBar1.add(btnTutup);
tblPeserta.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Nama", "Alamat", "No Induk", "Jenis Kelamin"
}
));
jScrollPane1.setViewportView(tblPeserta);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 697, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(77, 77, 77)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 538, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(45, 45, 45)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(78, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
try {
if (tblPeserta.getSelectedRow() >= 0 && peserta != null) {
peserta = new FormDialogPeserta().editAnggota(peserta);
if (peserta != null) {
Main.getPesertaDao().editPeserta(peserta,DatabaseConnection.getConnection());
loadDataToTable();
}
} else {
JOptionPane.showMessageDialog(Main.getMainForm(),
"Tidak ada data yang ingin di edit !!",
"Terjadi Kesalahan !!",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
ErrorDialog.showErrorDialog(e);
}
}//GEN-LAST:event_btnEditActionPerformed
private void btnTambahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTambahActionPerformed
try {
peserta = new FormDialogPeserta().showDialog();
if (peserta != null) {
Main.getPesertaDao().insertPeserta(peserta,DatabaseConnection.getConnection());
loadDataToTable();
}
} catch (Exception e) {
ErrorDialog.showErrorDialog(e);
}
}//GEN-LAST:event_btnTambahActionPerformed
private void btnTutupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTutupActionPerformed
Main.getMainForm().getMainTabbedPane().remove(this);
panel = null;
}//GEN-LAST:event_btnTutupActionPerformed
private void btnHapusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHapusActionPerformed
try {
if (tblPeserta.getSelectedRow() >= 0 && peserta != null) {
Main.getPesertaDao().hapusPeserta(peserta,DatabaseConnection.getConnection());
loadDataToTable();
} else {
JOptionPane.showMessageDialog(Main.getMainForm(),
"Tidak ada data yang ingin di hapus !!",
"Terjadi Kesalahan !!",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
ErrorDialog.showErrorDialog(e);
}
}//GEN-LAST:event_btnHapusActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnEdit;
private javax.swing.JButton btnHapus;
private javax.swing.JButton btnTambah;
private javax.swing.JButton btnTutup;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JTable tblPeserta;
// End of variables declaration//GEN-END:variables
private void loadDataToTable() {
try {
listPeserta = Main.getPesertaDao().getAllPeserta(DatabaseConnection.getConnection());
if (!listPeserta.isEmpty()) {
tblPeserta.setModel(new MasterPesertaTableModel(listPeserta));
} else {
tblPeserta.setModel(new MasterPesertaTableModel(new ArrayList<Peserta>()));
TableUtil.initColumn(tblPeserta);
}
} catch (SQLException ex) {
ErrorDialog.showErrorDialog(ex);
}
}
}
|
package com.muryang.sureforprice.queue;
import com.muryang.sureforprice.core.object.Document;
public class DocumentQueue {
public DocumentQueue() {
}
public int enqueue(Document doc) {
return -1 ;
}
}
|
package com.hiwes.cores.thread.thread4.Thread0219;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* void lockInterruptibly()。
* 如果当前线程未被中断,则获取锁定,如果已经被中断则出现异常。
*/
public class MyThread17 {
}
class Service17 {
private ReentrantLock lock = new ReentrantLock(); // 默认使用false,非公平锁。
private Condition condition = lock.newCondition();
public void waitMethod() {
try {
lock.lock();
// lock.lockInterruptibly();
System.out.println("lock begin: " + Thread.currentThread().getName());
for (int i = 0; i < Integer.MAX_VALUE / 10; i++) {
String newString = new String();
Math.random();
}
System.out.println("lock end: " + Thread.currentThread().getName());
// } catch (InterruptedException e) {
// e.printStackTrace();
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
}
class Run17 {
public static void main(String[] args) throws InterruptedException {
final Service17 service = new Service17();
Runnable runnable = new Runnable() {
@Override
public void run() {
service.waitMethod();
}
};
Thread a = new Thread(runnable);
a.setName("A");
a.start();
Thread.sleep(500);
Thread b = new Thread(runnable);
b.setName("B");
b.start();
b.interrupt(); // 打断标记
System.out.println("main end.");
}
} |
package com.zsy.swagger.controller;
import com.zsy.swagger.domain.Student;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudenntController {
@ApiOperation(value="获取学生分数等信息", notes="根据url的id来获取学生分数等信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
@RequestMapping(value = "student/{id}",method = RequestMethod.GET)
public Student getStudent(@PathVariable(value = "id") Integer id){
Student student = new Student("zhousy",18,100);
return student;
}
@ApiOperation(value="获取学生信息", notes="根据url的id来获取学生信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
@RequestMapping(value = "studentInfo/{id}",method = RequestMethod.GET)
public Student getStudentInfo(@PathVariable(value = "id") Integer id){
Student student = new Student("zhousy",18,100);
return student;
}
}
|
package com.aprendoz_test.data.output;
/**
* Generated for query "dash_aprendizajes" on 01/19/2015 07:59:26
*
*/
public class Dash_aprendizajesRtnType {
private Integer idasignaturas;
private String asignatura;
private Long aprProgreso;
private Long aprCompetente;
private Long aprAvanzado;
private Long aprMagistral;
public Integer getIdasignaturas() {
return idasignaturas;
}
public void setIdasignaturas(Integer idasignaturas) {
this.idasignaturas = idasignaturas;
}
public String getAsignatura() {
return asignatura;
}
public void setAsignatura(String asignatura) {
this.asignatura = asignatura;
}
public Long getAprProgreso() {
return aprProgreso;
}
public void setAprProgreso(Long aprProgreso) {
this.aprProgreso = aprProgreso;
}
public Long getAprCompetente() {
return aprCompetente;
}
public void setAprCompetente(Long aprCompetente) {
this.aprCompetente = aprCompetente;
}
public Long getAprAvanzado() {
return aprAvanzado;
}
public void setAprAvanzado(Long aprAvanzado) {
this.aprAvanzado = aprAvanzado;
}
public Long getAprMagistral() {
return aprMagistral;
}
public void setAprMagistral(Long aprMagistral) {
this.aprMagistral = aprMagistral;
}
}
|
package ru.javabegin.training.webservices.testws;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean
@RequestScoped
public class CallWS {
private String name;
private String correctedName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCorrectedName() {
return correctedName;
}
public void setCorrectedName(String correctedName) {
this.correctedName = correctedName;
}
public void correctName() {
TestWS_Service service = new TestWS_Service();
TestWS port = service.getTestWSPort();
correctedName = port.correctName(name);
}
}
|
package com.takshine.wxcrm.message.sugar;
import java.util.ArrayList;
import java.util.List;
/**
* 查询从市场活动接口传递回来的参数
* @author dengbo
*
*/
public class CampaignsResp extends BaseCrm{
private String count = null;//数字
private String currpage = "1";//当前页
private String pagecount = "5";//每页的条数
private List<CampaignsAdd> cams = new ArrayList<CampaignsAdd>();//市场活动列表
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getCurrpage() {
return currpage;
}
public void setCurrpage(String currpage) {
this.currpage = currpage;
}
public String getPagecount() {
return pagecount;
}
public void setPagecount(String pagecount) {
this.pagecount = pagecount;
}
public List<CampaignsAdd> getCams() {
return cams;
}
public void setCams(List<CampaignsAdd> cams) {
this.cams = cams;
}
}
|
/*
* User: djoiner
* Date: Oct 5, 2002
* Time: 1:19:50 PM
*/
package com.github.jwebfit;
import fit.Fixture;
import fit.Counts;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class DirectoryResultWriter extends FitResultWriter {
private List results;
public DirectoryResultWriter(File directory) {
super(directory);
results = new ArrayList();
}
public String getLinkString() {
return getOutput().getName() + "/index.html";
}
public String getDisplayName() {
return getOutput().getName();
}
public void addResult(FitResultWriter result) {
results.add(result);
}
public Counts getCounts() {
Counts c = new Fixture().counts;
for (Iterator iterator = results.iterator(); iterator.hasNext();) {
FitResultWriter fitResult = (FitResultWriter) iterator.next();
c.tally(fitResult.getCounts());
}
return c;
}
public void write() {
writeChildren();
writeIndexFile();
}
private void writeChildren() {
for (Iterator iterator = results.iterator(); iterator.hasNext();) {
FitResultWriter fitResult = (FitResultWriter) iterator.next();
fitResult.write();
}
}
private void writeIndexFile() {
File indexFile = new File(getOutput(), "index.html");
FileWriter writer = null;
try {
writer = new FileWriter(indexFile);
writer.write("<html><head><title>Fit Results Summary</title></head><body>");
writer.write("<h1>Results</h1>");
writer.write("<table border=\"1\" cellspacing=\"1\" cellpadding=\"2\">");
writeResults(writer);
writer.write("</table>");
writer.write("<br>");
writer.write("Cumulative Results: " + getCounts());
writer.write("<br><br>");
writer.write(new Date().toString());
writer.write("</body></html>");
writer.flush();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use Options | File Templates.
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void writeResults(FileWriter writer) throws IOException {
for (Iterator iterator = results.iterator(); iterator.hasNext();) {
FitResultWriter result = (FitResultWriter) iterator.next();
String color = (result.didFail()) ? "#ffcfcf" : "#cfffcf";
writer.write("<tr bgcolor=\"" + color + "\"><td>");
writer.write("<a href=\"" + result.getLinkString() + "\">" + result.getDisplayName() + "</a>");
writer.write("<td>" + result.getCounts() + "</td>");
writer.write("</td></tr>");
}
}
}
|
package com.jim.multipos.ui.reports.summary_report.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.jim.multipos.R;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class PairAdapter extends RecyclerView.Adapter<PairAdapter.PairViewHolder>{
List<PairString> pairStrings;
public PairAdapter(List<PairString> pairStrings){
this.pairStrings = pairStrings;
}
public void update(List<PairString> pairStrings){
this.pairStrings = pairStrings;
notifyDataSetChanged();
}
@Override
public PairViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pair, parent, false);
return new PairViewHolder(view);
}
@Override
public void onBindViewHolder(PairViewHolder holder, int position) {
holder.tvFirst.setText(pairStrings.get(position).getFirstString());
holder.tvSecond.setText(pairStrings.get(position).getSecondString());
}
@Override
public int getItemCount() {
return pairStrings.size();
}
public class PairViewHolder extends RecyclerView.ViewHolder{
@BindView(R.id.tvFirst)
TextView tvFirst;
@BindView(R.id.tvSecond)
TextView tvSecond;
public PairViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.portable;
import java.util.Set;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.inject.spi.InjectionPoint;
import org.apache.webbeans.config.WebBeansContext;
public abstract class AbstractEjbInjectionTarget<T> extends InjectionTargetImpl<T>
{
public AbstractEjbInjectionTarget(AnnotatedType<T> annotatedType,
Set<InjectionPoint> points,
WebBeansContext webBeansContext)
{
super(annotatedType, points, webBeansContext, null, null);
}
@Override
public abstract T produce(CreationalContext<T> creationalContext);
}
|
package com.tencent.mm.plugin.appbrand.ui.widget;
class AppBrandLoadIconPreference$1 implements Runnable {
final /* synthetic */ AppBrandLoadIconPreference gBj;
AppBrandLoadIconPreference$1(AppBrandLoadIconPreference appBrandLoadIconPreference) {
this.gBj = appBrandLoadIconPreference;
}
public final void run() {
AppBrandLoadIconPreference.a(this.gBj);
}
}
|
/*
* Copyright (C) 2022-2023 Hedera Hashgraph, LLC
*
* 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.hedera.mirror.importer.reconciliation;
import static com.hedera.mirror.common.domain.job.ReconciliationStatus.FAILURE_CRYPTO_TRANSFERS;
import static com.hedera.mirror.common.domain.job.ReconciliationStatus.FAILURE_FIFTY_BILLION;
import static com.hedera.mirror.common.domain.job.ReconciliationStatus.FAILURE_TOKEN_TRANSFERS;
import static com.hedera.mirror.common.domain.job.ReconciliationStatus.SUCCESS;
import static com.hedera.mirror.common.domain.job.ReconciliationStatus.UNKNOWN;
import static com.hedera.mirror.importer.reconciliation.BalanceReconciliationService.FIFTY_BILLION_HBARS;
import static com.hedera.mirror.importer.reconciliation.BalanceReconciliationService.METRIC;
import static com.hedera.mirror.importer.reconciliation.BalanceReconciliationService.TokenAccountId;
import static com.hedera.mirror.importer.reconciliation.ReconciliationProperties.RemediationStrategy.ACCUMULATE;
import static com.hedera.mirror.importer.reconciliation.ReconciliationProperties.RemediationStrategy.FAIL;
import static com.hedera.mirror.importer.reconciliation.ReconciliationProperties.RemediationStrategy.RESET;
import static org.assertj.core.api.Assertions.assertThat;
import com.hedera.mirror.common.domain.DomainBuilder;
import com.hedera.mirror.common.domain.balance.AccountBalance;
import com.hedera.mirror.common.domain.balance.AccountBalanceFile;
import com.hedera.mirror.common.domain.balance.TokenBalance;
import com.hedera.mirror.common.domain.entity.EntityId;
import com.hedera.mirror.common.domain.entity.EntityType;
import com.hedera.mirror.common.domain.job.ReconciliationJob;
import com.hedera.mirror.common.domain.job.ReconciliationStatus;
import com.hedera.mirror.common.domain.token.TokenTransfer;
import com.hedera.mirror.common.domain.transaction.ErrataType;
import com.hedera.mirror.importer.IntegrationTest;
import com.hedera.mirror.importer.repository.ReconciliationJobRepository;
import com.hedera.mirror.importer.repository.RecordFileRepository;
import com.hedera.mirror.importer.util.Utility;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.assertj.core.api.ObjectAssert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.support.TransactionTemplate;
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
class BalanceReconciliationServiceTest extends IntegrationTest {
private final DomainBuilder domainBuilder;
private final MeterRegistry meterRegistry;
private final RecordFileRepository recordFileRepository;
private final ReconciliationJobRepository reconciliationJobRepository;
private final ReconciliationProperties reconciliationProperties;
private final BalanceReconciliationService reconciliationService;
private final TransactionTemplate transactionTemplate;
@BeforeEach
void setup() {
reconciliationProperties.setDelay(Duration.ZERO);
reconciliationProperties.setEnabled(true);
reconciliationProperties.setEndDate(Utility.MAX_INSTANT_LONG);
reconciliationProperties.setRemediationStrategy(FAIL);
reconciliationProperties.setStartDate(Instant.EPOCH);
reconciliationProperties.setToken(true);
reconciliationService.status.set(UNKNOWN);
}
@Test
void cryptoTransfersSuccess() {
// given
balance(Map.of(2L, FIFTY_BILLION_HBARS));
transfer(2, 3, 1000);
transfer(3, 4, 100);
balance(Map.of(2L, FIFTY_BILLION_HBARS - 1000L, 3L, 900L, 4L, 100L, 5L, 0L));
transfer(2, 4, 500);
transfer(2, 5, 100);
var last = balance(Map.of(2L, FIFTY_BILLION_HBARS - 1600L, 3L, 900L, 4L, 600L, 5L, 100L));
// when
reconcile();
// then
assertReconciliationJob(SUCCESS, last).returns(2L, ReconciliationJob::getCount);
}
@Test
void cryptoTransfersFailure() {
// given
balance(Map.of(2L, FIFTY_BILLION_HBARS));
transfer(2, 3, 1000);
balance(Map.of(2L, FIFTY_BILLION_HBARS - 1010L, 3L, 1010L)); // Missing 10 tinybar transfer
// when
reconcile();
// then
assertReconciliationJob(FAILURE_CRYPTO_TRANSFERS, null).returns(0L, ReconciliationJob::getCount);
}
@Test
void cryptoTransfersAccumulateStrategy() {
// given
reconciliationProperties.setRemediationStrategy(ACCUMULATE);
balance(Map.of(2L, FIFTY_BILLION_HBARS));
var balance2 = balance(Map.of(2L, FIFTY_BILLION_HBARS));
balance(Map.of(2L, FIFTY_BILLION_HBARS - 1000L, 3L, 1000L)); // Missing 1000 tinybar transfer
transfer(3, 4, 1);
balance(Map.of(2L, FIFTY_BILLION_HBARS - 1000L, 3L, 999L, 4L, 1L));
// when
reconcile();
// then
assertReconciliationJob(FAILURE_CRYPTO_TRANSFERS, balance2)
.returns(3L, ReconciliationJob::getCount)
.satisfies(r -> assertThat(r.getError()).contains(""));
}
@Test
void cryptoTransfersResetStrategy() {
// given
reconciliationProperties.setRemediationStrategy(RESET);
balance(Map.of(2L, FIFTY_BILLION_HBARS));
var balance2 = balance(Map.of(2L, FIFTY_BILLION_HBARS));
balance(Map.of(2L, FIFTY_BILLION_HBARS - 1000L, 3L, 1000L)); // Missing 1000 tinybar transfer
transfer(3, 4, 1);
balance(Map.of(2L, FIFTY_BILLION_HBARS - 1000L, 3L, 999L, 4L, 1L));
// when
reconcile();
// then
assertReconciliationJob(FAILURE_CRYPTO_TRANSFERS, balance2).returns(3L, ReconciliationJob::getCount);
}
@Test
void cryptoTransfersZeroBalances() {
// given
balance(Map.of(2L, FIFTY_BILLION_HBARS, 3L, 0L));
var balance2 = balance(Map.of(2L, FIFTY_BILLION_HBARS, 4L, 0L));
// when
reconcile();
// then
assertReconciliationJob(SUCCESS, balance2).returns(1L, ReconciliationJob::getCount);
}
@Test
void delay() {
// given
long delay = 1000L;
reconciliationProperties.setDelay(Duration.ofMillis(delay));
balance(Map.of(2L, FIFTY_BILLION_HBARS, 3L, 0L));
var balance2 = balance(Map.of(2L, FIFTY_BILLION_HBARS, 4L, 0L));
// when
long start = System.currentTimeMillis();
reconcile();
long end = System.currentTimeMillis();
// then
assertReconciliationJob(SUCCESS, balance2).returns(1L, ReconciliationJob::getCount);
assertThat(end - start).isGreaterThanOrEqualTo(delay);
}
@Test
void tokenTransfersSuccess() {
// given
tokenBalance(Map.of());
tokenTransfer(2, 100, 1000);
tokenTransfer(2, 100, -100);
tokenTransfer(3, 100, 100);
var balance2 = tokenBalance(Map.of(new TokenAccountId(2, 100), 900L, new TokenAccountId(3, 100), 100L));
// when
reconcile();
// then
assertReconciliationJob(SUCCESS, balance2).returns(1L, ReconciliationJob::getCount);
}
@Test
void tokenTransfersFailure() {
// given
tokenBalance(Map.of(new TokenAccountId(2, 100), 1L));
tokenBalance(Map.of(new TokenAccountId(2, 100), 2L)); // Missing transfer
// when
reconcile();
// then
assertReconciliationJob(FAILURE_TOKEN_TRANSFERS, null).returns(0L, ReconciliationJob::getCount);
}
@Test
void tokenTransfersResetStrategy() {
// given
reconciliationProperties.setRemediationStrategy(RESET);
tokenBalance(Map.of(new TokenAccountId(2, 100), 100L));
var balance2 = tokenBalance(Map.of(new TokenAccountId(2, 100), 100L));
tokenBalance(Map.of(new TokenAccountId(2, 100), 101L)); // Missing transfer
tokenTransfer(2, 100, -10);
tokenTransfer(3, 100, 10);
tokenBalance(Map.of(new TokenAccountId(2, 100), 91L, new TokenAccountId(3, 100), 10L));
// when
reconcile();
// then
assertReconciliationJob(FAILURE_TOKEN_TRANSFERS, balance2).returns(3L, ReconciliationJob::getCount);
}
@Test
void tokensNotEnabled() {
// given
reconciliationProperties.setToken(false);
tokenBalance(Map.of(new TokenAccountId(2, 100), 1L));
var balance2 = tokenBalance(Map.of(new TokenAccountId(2, 100), 2L)); // Missing transfer
// when
reconcile();
// then
assertReconciliationJob(SUCCESS, balance2).returns(1L, ReconciliationJob::getCount);
}
@Test
void tokenTransfersZeroBalances() {
// given
tokenBalance(Map.of(new TokenAccountId(2, 100), 0L, new TokenAccountId(3, 100), 0L));
var balance2 = tokenBalance(Map.of(new TokenAccountId(2, 100), 0L, new TokenAccountId(3, 100), 0L));
// when
reconcile();
// then
assertReconciliationJob(SUCCESS, balance2).returns(1L, ReconciliationJob::getCount);
}
@Test
void errata() {
// given
balance(Map.of(2L, FIFTY_BILLION_HBARS));
transfer(2, 3, 1);
domainBuilder
.cryptoTransfer()
.customize(c -> c.amount(100).entityId(4).errata(ErrataType.DELETE))
.persist();
domainBuilder
.cryptoTransfer()
.customize(c -> c.amount(-100).entityId(2).errata(ErrataType.DELETE))
.persist();
var balance2 = balance(Map.of(2L, FIFTY_BILLION_HBARS - 1L, 3L, 1L)); // Errata rows not present
// when
reconcile();
// then
assertMetric(SUCCESS);
assertReconciliationJob(SUCCESS, balance2).returns(1L, ReconciliationJob::getCount);
}
@Test
void notEnabled() {
// given
reconciliationProperties.setEnabled(false);
balance(Map.of(2L, 1L)); // Would fail if checked
// when
reconcile();
// then
assertMetric(UNKNOWN);
assertThat(reconciliationJobRepository.count()).isZero();
}
@Test
void noBalanceFiles() {
// when
reconcile();
// then
assertMetric(UNKNOWN);
assertReconciliationJob(UNKNOWN, null).returns(0L, ReconciliationJob::getCount);
}
@Test
void singleBalanceFile() {
// given
balance(Map.of(2L, FIFTY_BILLION_HBARS));
// when
reconcile();
// then
assertReconciliationJob(SUCCESS, null).returns(0L, ReconciliationJob::getCount);
}
@Test
void balanceNotFiftyBillion() {
// given
balance(Map.of(2L, FIFTY_BILLION_HBARS));
transfer(2, 3, 100);
balance(Map.of(2L, FIFTY_BILLION_HBARS, 3L, 100L));
// when
reconcile();
// then
assertReconciliationJob(FAILURE_FIFTY_BILLION, null).returns(0L, ReconciliationJob::getCount);
}
@Test
void startDate() {
// given
balance(Map.of(2L, 1L)); // Would fail if checked
var balanceFile2 = balance(Map.of(2L, FIFTY_BILLION_HBARS));
var balanceFile3 = balance(Map.of(2L, FIFTY_BILLION_HBARS));
reconciliationProperties.setStartDate(Instant.ofEpochSecond(0L, balanceFile2.getConsensusTimestamp()));
// when
reconcile();
// then
assertReconciliationJob(SUCCESS, balanceFile3).returns(1L, ReconciliationJob::getCount);
}
@Test
void startDateAfterLastRun() {
// given
var balanceFile1 = balance(Map.of(2L, 1L)); // Would fail if checked
var balanceFile2 = balance(Map.of(2L, FIFTY_BILLION_HBARS));
var balanceFile3 = balance(Map.of(2L, FIFTY_BILLION_HBARS));
domainBuilder
.reconciliationJob()
.customize(r -> r.consensusTimestamp(balanceFile1.getConsensusTimestamp())
.timestampStart(Instant.EPOCH)
.timestampEnd(Instant.EPOCH.plusSeconds(1)))
.persist();
reconciliationProperties.setStartDate(Instant.ofEpochSecond(0L, balanceFile2.getConsensusTimestamp()));
// when
reconcile();
// then
assertReconciliationJob(SUCCESS, balanceFile3).returns(1L, ReconciliationJob::getCount);
}
@Test
void endDate() {
// given
balance(Map.of(2L, FIFTY_BILLION_HBARS));
balance(Map.of(2L, FIFTY_BILLION_HBARS));
var balanceFile3 = balance(Map.of(2L, FIFTY_BILLION_HBARS));
balance(Map.of(2L, 1L)); // Would fail if checked
reconciliationProperties.setEndDate(Instant.ofEpochSecond(0L, balanceFile3.getConsensusTimestamp()));
// when
reconcile();
// then
assertReconciliationJob(SUCCESS, balanceFile3).returns(2L, ReconciliationJob::getCount);
}
@Test
void recovers() {
// given
balance(Map.of(2L, FIFTY_BILLION_HBARS));
domainBuilder.cryptoTransfer().customize(c -> c.amount(100).entityId(3)).persist();
var missingTransfer =
domainBuilder.cryptoTransfer().customize(c -> c.amount(-100).entityId(2));
var last = balance(Map.of(2L, FIFTY_BILLION_HBARS - 100, 3L, 100L));
// when
reconcile();
// then
assertReconciliationJob(FAILURE_CRYPTO_TRANSFERS, null)
.returns(0L, ReconciliationJob::getCount)
.extracting(ReconciliationJob::getError)
.asInstanceOf(InstanceOfAssertFactories.STRING)
.contains("not equal: value differences={2=(5000000000000000000, 4999999999999999900)}");
// given
missingTransfer.persist();
// when
reconciliationService.reconcile();
// then
assertReconciliationJob(SUCCESS, last).returns(1L, ReconciliationJob::getCount);
assertThat(reconciliationJobRepository.count()).isEqualTo(2);
}
private void assertMetric(ReconciliationStatus status) {
assertThat(meterRegistry.find(METRIC).gauges())
.hasSize(1)
.first()
.extracting(Gauge::value)
.isEqualTo((double) status.ordinal());
}
private ObjectAssert<ReconciliationJob> assertReconciliationJob(
ReconciliationStatus status, AccountBalanceFile accountBalanceFile) {
assertMetric(status);
var consensusTimestamp = accountBalanceFile != null ? accountBalanceFile.getConsensusTimestamp() : 0L;
var jobAssert = assertThat(reconciliationJobRepository.findLatest())
.get()
.returns(consensusTimestamp, ReconciliationJob::getConsensusTimestamp)
.satisfies(rj -> assertThat(rj.getCount()).isNotNegative())
.satisfies(rj -> assertThat(rj.getTimestampEnd()).isNotNull())
.satisfies(rj -> assertThat(rj.getTimestampStart()).isNotNull().isBeforeOrEqualTo(rj.getTimestampEnd()))
.asInstanceOf(InstanceOfAssertFactories.type(ReconciliationJob.class));
if (status == SUCCESS) {
jobAssert.returns("", ReconciliationJob::getError);
}
return jobAssert;
}
private void reconcile() {
transactionTemplate.executeWithoutResult(t -> reconciliationService.reconcile());
}
private AccountBalanceFile balance(Map<Long, Long> balances) {
var accountBalanceFile = domainBuilder.accountBalanceFile().persist();
long timestamp = accountBalanceFile.getConsensusTimestamp();
balances.forEach((accountId, balance) -> {
var entityId = EntityId.of(accountId, EntityType.ACCOUNT);
domainBuilder
.accountBalance()
.customize(a -> a.balance(balance).id(new AccountBalance.Id(timestamp, entityId)))
.persist();
});
domainBuilder.recordFile().customize(r -> r.hapiVersionMinor(20)).persist();
return accountBalanceFile;
}
private AccountBalanceFile tokenBalance(Map<TokenAccountId, Long> balances) {
var accountBalanceFile = balance(Map.of(2L, FIFTY_BILLION_HBARS));
long timestamp = accountBalanceFile.getConsensusTimestamp();
balances.forEach((id, balance) -> {
var accountId = EntityId.of(id.getAccountId(), EntityType.ACCOUNT);
var tokenId = EntityId.of(id.getTokenId(), EntityType.TOKEN);
domainBuilder
.tokenBalance()
.customize(a -> a.balance(balance).id(new TokenBalance.Id(timestamp, accountId, tokenId)))
.persist();
});
return accountBalanceFile;
}
private void transfer(long from, long to, long amount) {
domainBuilder
.cryptoTransfer()
.customize(c -> c.amount(amount).entityId(to))
.persist();
domainBuilder
.cryptoTransfer()
.customize(c -> c.amount(-amount).entityId(from))
.persist();
}
private void tokenTransfer(long accountNum, long tokenNum, long amount) {
long timestamp = domainBuilder.timestamp();
EntityId accountId = EntityId.of(accountNum, EntityType.ACCOUNT);
EntityId tokenId = EntityId.of(tokenNum, EntityType.TOKEN);
domainBuilder
.tokenTransfer()
.customize(c -> c.amount(amount).id(new TokenTransfer.Id(timestamp, tokenId, accountId)))
.persist();
}
}
|
package co.nos.noswallet.kyc.identity;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Date;
import javax.inject.Inject;
import co.nos.noswallet.R;
import co.nos.noswallet.base.SimpleWatcher;
import co.nos.noswallet.databinding.FragmentKyc4IdentityBinding;
import co.nos.noswallet.kyc.KnowYourCustomerActivity;
import co.nos.noswallet.kyc.KycUserDataRepository;
public class IdentityFragment extends co.nos.noswallet.base.BaseFragment<KnowYourCustomerActivity> {
public static final int POSITION = 4;
TextWatcher watcher;
DatePickerDialog datePickerDialog;
@Inject
KycUserDataRepository userDataRepository;
@Inject
IdentityMapper identityMapper;
FragmentKyc4IdentityBinding binding;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// init dependency injection
if (canInject()) {
getActivityComponent().inject(this);
} else {
exitFromHere();
}
// inflate the view
binding = DataBindingUtil.inflate(
inflater, R.layout.fragment_kyc_4_identity, container, false);
View view = binding.getRoot();
// bind data to view
binding.setHandlers(new IdentityFragment.ClickHandlers());
binding.identityFirstName.setText(userDataRepository.firstName);
binding.identityLastName.setText(userDataRepository.lastName);
binding.identityBirthdate.setText(userDataRepository.birthDate);
setupBirthDateListener();
watcher = new IdentityWatcher();
binding.identityFirstName.addTextChangedListener(watcher);
binding.identityLastName.addTextChangedListener(watcher);
binding.identityBirthdate.addTextChangedListener(watcher);
return view;
}
@SuppressLint("ClickableViewAccessibility")
private void setupBirthDateListener() {
binding.identityBirthdate.setOnEditTextTouchListener((v, event) -> {
if (datePickerDialog == null || !datePickerDialog.isShowing()) {
onCalendarPicked();
}
return true;
});
}
void enableIdentity() {
boolean valid = identityMapper.areIdentityValid(
binding.identityFirstName.getTrimmedText(),
binding.identityLastName.getTrimmedText(),
binding.identityBirthdate.getTrimmedText()
);
enableButton(valid);
}
void onCalendarPicked() {
DatePickerDialog.OnDateSetListener listener = (view, year, month, dayOfMonth) -> {
Date date = new Date(year - 1900, month, dayOfMonth);
String dateAsString = identityMapper.formatDate(date);
binding.identityBirthdate.setText(dateAsString);
};
datePickerDialog = new DatePickerDialog(getParentActivity(), listener, 1993, 6, 20);
datePickerDialog.show();
}
private void enableButton(boolean enable) {
if (enable)
binding.kyc1Continue.setBackgroundResource(R.drawable.bg_large_button);
else
binding.kyc1Continue.setBackgroundResource(R.drawable.bg_large_button_gray);
}
public class ClickHandlers {
public void onClickContinue(View view) {
binding.identityFirstName.clearError();
binding.identityLastName.clearError();
binding.identityBirthdate.clearError();
boolean canGoNext = true;
if (binding.identityFirstName.isEmpty()) {
binding.identityFirstName.setError(getString(R.string.field_cannot_be_blank));
canGoNext = false;
}
if (binding.identityLastName.isEmpty()) {
binding.identityLastName.setError(getString(R.string.field_cannot_be_blank));
canGoNext = false;
}
if (!identityMapper.isBirthDateValid(binding.identityBirthdate.getTrimmedText())) {
binding.identityBirthdate.setError(getString(R.string.birthdate_invalid));
canGoNext = false;
}
if (canGoNext) {
enableButton(true);
} else {
return;
}
userDataRepository.firstName = binding.identityFirstName.getTrimmedText();
userDataRepository.lastName = binding.identityLastName.getTrimmedText();
userDataRepository.birthDate = binding.identityBirthdate.getTrimmedText();
getParentActivity().navigateNext(POSITION);
}
}
class IdentityWatcher extends SimpleWatcher {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
enableIdentity();
}
}
}
|
package parcial.model;
public class Cuota {
private int Ncuota;
private double valorCuota;
private double valorPagar;
private double saldo;
private boolean pagada;
private Prestamo pres1;
public Cuota(int Ncuota, double valorCuota, double valorPagar, double saldo, boolean pagada, Prestamo pres1) {
this.Ncuota = Ncuota;
this.valorCuota = valorCuota;
this.valorPagar = valorPagar;
this.saldo = saldo;
this.pagada = pagada;
this.pres1 = pres1;
}
public int getNcuota() {
return Ncuota;
}
public void setNcuota(int Ncuota) {
this.Ncuota = Ncuota;
}
public double getValorCuota() {
return valorCuota;
}
public void setValorCuota(double valorCuota) {
this.valorCuota = valorCuota;
}
public double getValorPagar() {
return valorPagar;
}
public void setValorPagar(double valorPagar) {
this.valorPagar = valorPagar;
}
public double getSaldo() {
return saldo;
}
public void setSaldo(double saldo) {
this.saldo = saldo;
}
public boolean isPagada() {
return pagada;
}
public void setPagada(boolean pagada) {
this.pagada = pagada;
}
public Prestamo getPres1() {
return pres1;
}
public void setPres1(Prestamo pres1) {
this.pres1 = pres1;
}
}
|
/**
* <pre>
*
* Author:
* Brandon Mota
*
*
* Description:
* This class is the child class to Geom.
* It provides the necessary methods for
* a triangle object.
*
*
* </pre>
*/
public class Triangle extends Geom
{
private double base, height;
/**
* <pre>
* Description:
* This is the constructor for the class.
* Pre:
* none.
* Post:
* Triangle is created.
* </pre>
*
*/
public Triangle()
{
super("Triangle");
base = 0;
height = 0;
}
/**
* <pre>
* Description:
* This provides a new instance of Triangle.
* Pre:
* none.
* Post:
* A new Triangle is created.
* </pre>
*
*/
public Triangle(double base, double height)
{
super("Triangle");
this.base = base;
this.height = height;
}
/**
* <pre>
* Description:
* This returns the base caller.
* Pre:
* none.
* Post:
* Base is returned.
* </pre>
*
*/
public double getbase()
{
return base;
}
/**
* <pre>
* Description:
* This returns the height back to the caller.
* Pre:
* none.
* Post:
* Height is returned.
* </pre>
*
*/
public double getheight()
{
return height;
}
/**
* <pre>
* Description:
* This calculated the area of the shape and returns it.
* Pre:
* none.
* Post:
* Area is returned.
* </pre>
*
*/
public double computeArea()
{
return (base/2) * height;
}
/**
* <pre>
* Description:
* This prints the shape data.
* Pre:
* none.
* Post:
* Shape data is printed.
* </pre>
*
*/
public void print()
{
System.out.println("tri " + base + " " + height + " " + computeArea());
}
}
|
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServletUpdateWeight
*/
@WebServlet("/UpdateWeight")
public class ServletUpdateWeight extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletUpdateWeight() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String idStr = request.getParameter("id");
String weightStr = request.getParameter("weight");
DB db = new DB();
int id = Integer.parseInt(idStr);
if(!Validator.validateDouble(weightStr))
{
response.sendError(400,"Invalid Weight!");
}
else
{
double weightNum = Double.parseDouble(weightStr);
AssignmentWeight weight = db.getWeightFromId(id);
System.out.println("ole weight num = " +weight.getWeight());
weight.setWeight(weightNum);
System.out.println("new weight num = " +weight.getWeight());
db.updateWeight(weight);
RequestDispatcher rd = request.getRequestDispatcher("AllWeights");
rd.forward(request, response);
}
}
}
|
package com.supconit.kqfx.web.util;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class XmlAnalysisUtil {
private transient static final Logger logger = LoggerFactory
.getLogger(XmlAnalysisUtil.class);
public static String getCode(String xml){
try {
Document doc;
doc = DocumentHelper.parseText(xml);
//Document doc = reader.read(ffile); //读取一个xml的文件
Element root = doc.getRootElement();
//Attribute testCmd= root.attribute("test");
//System.out.println(testCmd.getName()+"-***--"+testCmd.getValue());
Element code = root.element("CODE");
Element message = root.element("MESSAGE");
String falg = code.getTextTrim();
logger.info("CODE节点内容*--"+code.getTextTrim());
logger.info("MESSAGE节点内容*--"+message.getTextTrim());
return falg;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String getMesssage(String xml){
try {
Document doc;
doc = DocumentHelper.parseText(xml);
//Document doc = reader.read(ffile); //读取一个xml的文件
Element root = doc.getRootElement();
//Attribute testCmd= root.attribute("test");
//System.out.println(testCmd.getName()+"-***--"+testCmd.getValue());
Element message = root.element("MESSAGE");
String falg = message.getTextTrim();
return falg;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String getTime(String xml){
try {
Document doc;
doc = DocumentHelper.parseText(xml);
Element root = doc.getRootElement();
Element currentTime = root.element("CURRENTTIME");
String time = currentTime.getTextTrim();
return time;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.h5_interact;
import com.tencent.mm.ipcinvoker.a;
import com.tencent.mm.ipcinvoker.c;
import com.tencent.mm.ipcinvoker.type.IPCVoid;
final class b$a implements a<SendDataToH5FromMiniProgramEvent, IPCVoid> {
private b$a() {
}
public final /* synthetic */ void a(Object obj, c cVar) {
SendDataToH5FromMiniProgramEvent sendDataToH5FromMiniProgramEvent = (SendDataToH5FromMiniProgramEvent) obj;
if (sendDataToH5FromMiniProgramEvent != null) {
com.tencent.mm.sdk.b.a.sFg.m(sendDataToH5FromMiniProgramEvent);
}
}
}
|
package com.mashibing;
import java.io.IOException;
import java.util.Properties;
/**
* @create: 2020-04-03 13:21
**/
public class ConfigMgr {
private ConfigMgr(){}
static Properties properties = new Properties();
static {
try {
properties.load(ConfigMgr.class.getClassLoader().getResourceAsStream("config"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Integer getInt(String key){
if(properties == null) return null;
return Integer.parseInt(properties.getProperty(key));
}
public static String getString(String key){
if(properties == null) return null;
return properties.getProperty(key);
}
}
|
package com.example.sidra.quizapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button nextbtn;
TextView tv,number_of_question;
RadioButton rdbtn1;
RadioButton rdbtn2;
RadioButton rdbtn3;
RadioButton rdbtn4;
int correct=0;
int wrong=0;
int count=0;
int q_no=1;
int checkedradiobutton[];
final ArrayList<Question> questionArrayList=new ArrayList<Question>();
/*int quiz_array[]={R.string.q1,R.string.q2,R.string.q3,R.string.q4,R.string.q5,R.string.q6};
int answer_array[][]={{R.string._1a,R.string._1b,R.string._1c,R.string._1d},{R.string._2a,R.string._2b,R.string._2c,R.string._2d},
{R.string._3a,R.string._3b,R.string._3c,R.string._3d}};
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextbtn=(Button)findViewById(R.id.button );
rdbtn1=(RadioButton)findViewById(R.id.radioButton1);
rdbtn2=(RadioButton)findViewById(R.id.radioButton2);
rdbtn3=(RadioButton)findViewById(R.id.radioButton3);
rdbtn4=(RadioButton)findViewById(R.id.radioButton4);
tv=(TextView)findViewById(R.id.textView1);
number_of_question=(TextView)findViewById(R.id.questionnumber);
questionArrayList.add(new Question(1," What is the meaning of Pakistan?",new Answer(4," Muslim Land ","Land of five rivers "," Desert","Holy Land")));
questionArrayList.add(new Question(2,"Who is the first Governor General of Pakistan?",new Answer(1," Mohammed Ali Jinnah","Liaquat Ali Khan "," Ayub Khan","Iskander Mirza")));
questionArrayList.add(new Question(3,"What was the major event of 1971?",new Answer(1," Bangladesh broke away from Pakistan","Explosion of nuclear bomb ","Tashkent Agreement ","Nawaz Sharif became Prime Minister")));
questionArrayList.add(new Question(4,"When Musharraf overthrew the government of Nawaz Sharif what designation did he take?",new Answer(2,"Consul ","Chief Executive "," Prime Minister","Dictator")));
questionArrayList.add(new Question(5,"In which year did Pakistan win the Cricket World Cup?" ,new Answer(3,"1990 "," 1991","1992 ","1993")));
questionArrayList.add(new Question(6,"Which party was in power in North West Frontier Province at the time of independence?",new Answer(3,"Muslim League "," Justice Party "," Congress"," Communist Party")));
questionArrayList.add(new Question(7," Who succeeded Zia Ul Haque as President of Pakistan?",new Answer(3," Rafiq Tarar"," Farooq Ahmed Khan Leghari"," Ghulam Ishaq Khan "," Benazir Bhutto")));
questionArrayList.add(new Question(8,"When did Pakistan become a Republic?",new Answer(2," 14/08/1947 "," 23/03/1956 "," 16/12/1971 "," 12/10/1999")));
//initializing array to the size of arraylist
checkedradiobutton=new int[questionArrayList.size()];
//setting initial values to textarea and radio button
tv.setText(questionArrayList.get(0).getQ_text());
rdbtn1.setText( questionArrayList.get(count).getAnswer().a1_text);
rdbtn2.setText( questionArrayList.get(count).getAnswer().a2_text);
rdbtn3.setText( questionArrayList.get(count).getAnswer().a3_text);
rdbtn4.setText( questionArrayList.get(count).getAnswer().a4_text);
number_of_question.setText(" "+ q_no);
nextbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(count==questionArrayList.size()-1)
{
releasingResult();
}
else {
//uncheckingRadioButton();
++q_no;
++count;
String temp = questionArrayList.get(count).getQ_text();
tv.setText(temp);
number_of_question.setText(" "+q_no);
rdbtn1.setText( questionArrayList.get(count).getAnswer().a1_text);
rdbtn2.setText( questionArrayList.get(count).getAnswer().a2_text);
rdbtn3.setText( questionArrayList.get(count).getAnswer().a3_text);
rdbtn4.setText( questionArrayList.get(count).getAnswer().a4_text);
checkingWhichRadioButtonIsSelected(count);
}
}
});
}
public void checkingWhichRadioButtonIsSelected(int temp1)
{
if(rdbtn1.isSelected())
{
checkedradiobutton[temp1]=1;
}
else if(rdbtn2.isSelected())
{
checkedradiobutton[temp1]=2;
}
else if(rdbtn3.isSelected())
{
checkedradiobutton[temp1]=3;
}
else if(rdbtn4.isSelected())
{
checkedradiobutton[temp1]=4;
}
}
public void releasingResult()
{
for(int i=0;i<=questionArrayList.size()-1;i++)
{
if(questionArrayList.get(i).getAnswer().correct_ans_id==checkedradiobutton[i])
{
correct++;
}
else
{
wrong++;
}
}
System.out.println("This is correct "+correct);
Toast.makeText(MainActivity.this,"Your score is: "+correct,Toast.LENGTH_LONG).show();
}
public void uncheckingRadioButton()
{
rdbtn1.setChecked(false);
rdbtn2.setChecked(false);
rdbtn3.setChecked(false);
rdbtn4.setChecked(false);
}
}
|
package com.libedi.jpa.inheritance.singletable;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import lombok.Getter;
import lombok.Setter;
/**
* Book
*
* @author Sang-jun, Park
* @since 2019. 05. 17
*/
@Entity(name = "inheritance_singletable_Book")
@DiscriminatorValue("B") // 엔티티를 저장할 떄 구분 컬럼 입력값을 지정
@Getter @Setter
public class Book extends Item {
private String author;
private String isbn;
}
|
package com.grability.test.dlmontano.grabilitytest.custom.adapter;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.grability.test.dlmontano.grabilitytest.R;
import com.grability.test.dlmontano.grabilitytest.model.Category;
import java.util.List;
/**
* Created by Diego Montano on 16/06/2016.
*/
public class CategoryArrayAdapter extends ArrayAdapter<Category> {
private static String idKey = "appId";
private final Activity context;
private final Category[] categories;
static class ViewHolder {
public TextView categoryIdLine;
public TextView categoryNameLine;
}
public CategoryArrayAdapter(Activity context, Category[] categories) {
super(context, R.layout.category_line_list_row, categories);
this.context = context;
this.categories = categories;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.category_line_list_row, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.categoryIdLine = (TextView) rowView
.findViewById(R.id.categoryIdLine);
viewHolder.categoryNameLine = (TextView) rowView
.findViewById(R.id.categoryNameLine);
rowView.setTag(viewHolder);
}
Category category = categories[position];
ViewHolder holder = (ViewHolder) rowView.getTag();
holder.categoryIdLine.setText("" + category.getId());
holder.categoryNameLine.setText(category.getTerm());
return rowView;
}
}
|
package SortingAlgorithms;
import Controller.Simulation;
public class SelectionSort {
Simulation sim = Simulation.get_instance();
public void selectionSort(int[] arr) {
int min = arr[0];
int minIndex = 0;
int temp = 0;
for (int i = 0; i < arr.length; i++) {
min = arr[i];
minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < min) {
min = arr[j];
minIndex = j;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
sim.setCurr_point1(minIndex);
sim.setCurr_point4(i);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sim.setBounds(arr);
}
}
}
|
/**
* Provides classes for evaluating HSV image channels linear fuzzinesses.
*/
package pwr.chrzescijanek.filip.gifa.core.function.hsv.fuzziness.linear; |
package com.ybh.front.model;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class FapiaoExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public FapiaoExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andUsernameIsNull() {
addCriterion("username is null");
return (Criteria) this;
}
public Criteria andUsernameIsNotNull() {
addCriterion("username is not null");
return (Criteria) this;
}
public Criteria andUsernameEqualTo(String value) {
addCriterion("username =", value, "username");
return (Criteria) this;
}
public Criteria andUsernameNotEqualTo(String value) {
addCriterion("username <>", value, "username");
return (Criteria) this;
}
public Criteria andUsernameGreaterThan(String value) {
addCriterion("username >", value, "username");
return (Criteria) this;
}
public Criteria andUsernameGreaterThanOrEqualTo(String value) {
addCriterion("username >=", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLessThan(String value) {
addCriterion("username <", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLessThanOrEqualTo(String value) {
addCriterion("username <=", value, "username");
return (Criteria) this;
}
public Criteria andUsernameLike(String value) {
addCriterion("username like", value, "username");
return (Criteria) this;
}
public Criteria andUsernameNotLike(String value) {
addCriterion("username not like", value, "username");
return (Criteria) this;
}
public Criteria andUsernameIn(List<String> values) {
addCriterion("username in", values, "username");
return (Criteria) this;
}
public Criteria andUsernameNotIn(List<String> values) {
addCriterion("username not in", values, "username");
return (Criteria) this;
}
public Criteria andUsernameBetween(String value1, String value2) {
addCriterion("username between", value1, value2, "username");
return (Criteria) this;
}
public Criteria andUsernameNotBetween(String value1, String value2) {
addCriterion("username not between", value1, value2, "username");
return (Criteria) this;
}
public Criteria andUsermoneyIsNull() {
addCriterion("usermoney is null");
return (Criteria) this;
}
public Criteria andUsermoneyIsNotNull() {
addCriterion("usermoney is not null");
return (Criteria) this;
}
public Criteria andUsermoneyEqualTo(BigDecimal value) {
addCriterion("usermoney =", value, "usermoney");
return (Criteria) this;
}
public Criteria andUsermoneyNotEqualTo(BigDecimal value) {
addCriterion("usermoney <>", value, "usermoney");
return (Criteria) this;
}
public Criteria andUsermoneyGreaterThan(BigDecimal value) {
addCriterion("usermoney >", value, "usermoney");
return (Criteria) this;
}
public Criteria andUsermoneyGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("usermoney >=", value, "usermoney");
return (Criteria) this;
}
public Criteria andUsermoneyLessThan(BigDecimal value) {
addCriterion("usermoney <", value, "usermoney");
return (Criteria) this;
}
public Criteria andUsermoneyLessThanOrEqualTo(BigDecimal value) {
addCriterion("usermoney <=", value, "usermoney");
return (Criteria) this;
}
public Criteria andUsermoneyIn(List<BigDecimal> values) {
addCriterion("usermoney in", values, "usermoney");
return (Criteria) this;
}
public Criteria andUsermoneyNotIn(List<BigDecimal> values) {
addCriterion("usermoney not in", values, "usermoney");
return (Criteria) this;
}
public Criteria andUsermoneyBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("usermoney between", value1, value2, "usermoney");
return (Criteria) this;
}
public Criteria andUsermoneyNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("usermoney not between", value1, value2, "usermoney");
return (Criteria) this;
}
public Criteria andRealmoneyIsNull() {
addCriterion("realmoney is null");
return (Criteria) this;
}
public Criteria andRealmoneyIsNotNull() {
addCriterion("realmoney is not null");
return (Criteria) this;
}
public Criteria andRealmoneyEqualTo(BigDecimal value) {
addCriterion("realmoney =", value, "realmoney");
return (Criteria) this;
}
public Criteria andRealmoneyNotEqualTo(BigDecimal value) {
addCriterion("realmoney <>", value, "realmoney");
return (Criteria) this;
}
public Criteria andRealmoneyGreaterThan(BigDecimal value) {
addCriterion("realmoney >", value, "realmoney");
return (Criteria) this;
}
public Criteria andRealmoneyGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("realmoney >=", value, "realmoney");
return (Criteria) this;
}
public Criteria andRealmoneyLessThan(BigDecimal value) {
addCriterion("realmoney <", value, "realmoney");
return (Criteria) this;
}
public Criteria andRealmoneyLessThanOrEqualTo(BigDecimal value) {
addCriterion("realmoney <=", value, "realmoney");
return (Criteria) this;
}
public Criteria andRealmoneyIn(List<BigDecimal> values) {
addCriterion("realmoney in", values, "realmoney");
return (Criteria) this;
}
public Criteria andRealmoneyNotIn(List<BigDecimal> values) {
addCriterion("realmoney not in", values, "realmoney");
return (Criteria) this;
}
public Criteria andRealmoneyBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("realmoney between", value1, value2, "realmoney");
return (Criteria) this;
}
public Criteria andRealmoneyNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("realmoney not between", value1, value2, "realmoney");
return (Criteria) this;
}
public Criteria andTitleIsNull() {
addCriterion("title is null");
return (Criteria) this;
}
public Criteria andTitleIsNotNull() {
addCriterion("title is not null");
return (Criteria) this;
}
public Criteria andTitleEqualTo(String value) {
addCriterion("title =", value, "title");
return (Criteria) this;
}
public Criteria andTitleNotEqualTo(String value) {
addCriterion("title <>", value, "title");
return (Criteria) this;
}
public Criteria andTitleGreaterThan(String value) {
addCriterion("title >", value, "title");
return (Criteria) this;
}
public Criteria andTitleGreaterThanOrEqualTo(String value) {
addCriterion("title >=", value, "title");
return (Criteria) this;
}
public Criteria andTitleLessThan(String value) {
addCriterion("title <", value, "title");
return (Criteria) this;
}
public Criteria andTitleLessThanOrEqualTo(String value) {
addCriterion("title <=", value, "title");
return (Criteria) this;
}
public Criteria andTitleLike(String value) {
addCriterion("title like", value, "title");
return (Criteria) this;
}
public Criteria andTitleNotLike(String value) {
addCriterion("title not like", value, "title");
return (Criteria) this;
}
public Criteria andTitleIn(List<String> values) {
addCriterion("title in", values, "title");
return (Criteria) this;
}
public Criteria andTitleNotIn(List<String> values) {
addCriterion("title not in", values, "title");
return (Criteria) this;
}
public Criteria andTitleBetween(String value1, String value2) {
addCriterion("title between", value1, value2, "title");
return (Criteria) this;
}
public Criteria andTitleNotBetween(String value1, String value2) {
addCriterion("title not between", value1, value2, "title");
return (Criteria) this;
}
public Criteria andAddressIsNull() {
addCriterion("address is null");
return (Criteria) this;
}
public Criteria andAddressIsNotNull() {
addCriterion("address is not null");
return (Criteria) this;
}
public Criteria andAddressEqualTo(String value) {
addCriterion("address =", value, "address");
return (Criteria) this;
}
public Criteria andAddressNotEqualTo(String value) {
addCriterion("address <>", value, "address");
return (Criteria) this;
}
public Criteria andAddressGreaterThan(String value) {
addCriterion("address >", value, "address");
return (Criteria) this;
}
public Criteria andAddressGreaterThanOrEqualTo(String value) {
addCriterion("address >=", value, "address");
return (Criteria) this;
}
public Criteria andAddressLessThan(String value) {
addCriterion("address <", value, "address");
return (Criteria) this;
}
public Criteria andAddressLessThanOrEqualTo(String value) {
addCriterion("address <=", value, "address");
return (Criteria) this;
}
public Criteria andAddressLike(String value) {
addCriterion("address like", value, "address");
return (Criteria) this;
}
public Criteria andAddressNotLike(String value) {
addCriterion("address not like", value, "address");
return (Criteria) this;
}
public Criteria andAddressIn(List<String> values) {
addCriterion("address in", values, "address");
return (Criteria) this;
}
public Criteria andAddressNotIn(List<String> values) {
addCriterion("address not in", values, "address");
return (Criteria) this;
}
public Criteria andAddressBetween(String value1, String value2) {
addCriterion("address between", value1, value2, "address");
return (Criteria) this;
}
public Criteria andAddressNotBetween(String value1, String value2) {
addCriterion("address not between", value1, value2, "address");
return (Criteria) this;
}
public Criteria andPostidIsNull() {
addCriterion("postid is null");
return (Criteria) this;
}
public Criteria andPostidIsNotNull() {
addCriterion("postid is not null");
return (Criteria) this;
}
public Criteria andPostidEqualTo(String value) {
addCriterion("postid =", value, "postid");
return (Criteria) this;
}
public Criteria andPostidNotEqualTo(String value) {
addCriterion("postid <>", value, "postid");
return (Criteria) this;
}
public Criteria andPostidGreaterThan(String value) {
addCriterion("postid >", value, "postid");
return (Criteria) this;
}
public Criteria andPostidGreaterThanOrEqualTo(String value) {
addCriterion("postid >=", value, "postid");
return (Criteria) this;
}
public Criteria andPostidLessThan(String value) {
addCriterion("postid <", value, "postid");
return (Criteria) this;
}
public Criteria andPostidLessThanOrEqualTo(String value) {
addCriterion("postid <=", value, "postid");
return (Criteria) this;
}
public Criteria andPostidLike(String value) {
addCriterion("postid like", value, "postid");
return (Criteria) this;
}
public Criteria andPostidNotLike(String value) {
addCriterion("postid not like", value, "postid");
return (Criteria) this;
}
public Criteria andPostidIn(List<String> values) {
addCriterion("postid in", values, "postid");
return (Criteria) this;
}
public Criteria andPostidNotIn(List<String> values) {
addCriterion("postid not in", values, "postid");
return (Criteria) this;
}
public Criteria andPostidBetween(String value1, String value2) {
addCriterion("postid between", value1, value2, "postid");
return (Criteria) this;
}
public Criteria andPostidNotBetween(String value1, String value2) {
addCriterion("postid not between", value1, value2, "postid");
return (Criteria) this;
}
public Criteria andRecmanIsNull() {
addCriterion("recman is null");
return (Criteria) this;
}
public Criteria andRecmanIsNotNull() {
addCriterion("recman is not null");
return (Criteria) this;
}
public Criteria andRecmanEqualTo(String value) {
addCriterion("recman =", value, "recman");
return (Criteria) this;
}
public Criteria andRecmanNotEqualTo(String value) {
addCriterion("recman <>", value, "recman");
return (Criteria) this;
}
public Criteria andRecmanGreaterThan(String value) {
addCriterion("recman >", value, "recman");
return (Criteria) this;
}
public Criteria andRecmanGreaterThanOrEqualTo(String value) {
addCriterion("recman >=", value, "recman");
return (Criteria) this;
}
public Criteria andRecmanLessThan(String value) {
addCriterion("recman <", value, "recman");
return (Criteria) this;
}
public Criteria andRecmanLessThanOrEqualTo(String value) {
addCriterion("recman <=", value, "recman");
return (Criteria) this;
}
public Criteria andRecmanLike(String value) {
addCriterion("recman like", value, "recman");
return (Criteria) this;
}
public Criteria andRecmanNotLike(String value) {
addCriterion("recman not like", value, "recman");
return (Criteria) this;
}
public Criteria andRecmanIn(List<String> values) {
addCriterion("recman in", values, "recman");
return (Criteria) this;
}
public Criteria andRecmanNotIn(List<String> values) {
addCriterion("recman not in", values, "recman");
return (Criteria) this;
}
public Criteria andRecmanBetween(String value1, String value2) {
addCriterion("recman between", value1, value2, "recman");
return (Criteria) this;
}
public Criteria andRecmanNotBetween(String value1, String value2) {
addCriterion("recman not between", value1, value2, "recman");
return (Criteria) this;
}
public Criteria andTelIsNull() {
addCriterion("tel is null");
return (Criteria) this;
}
public Criteria andTelIsNotNull() {
addCriterion("tel is not null");
return (Criteria) this;
}
public Criteria andTelEqualTo(String value) {
addCriterion("tel =", value, "tel");
return (Criteria) this;
}
public Criteria andTelNotEqualTo(String value) {
addCriterion("tel <>", value, "tel");
return (Criteria) this;
}
public Criteria andTelGreaterThan(String value) {
addCriterion("tel >", value, "tel");
return (Criteria) this;
}
public Criteria andTelGreaterThanOrEqualTo(String value) {
addCriterion("tel >=", value, "tel");
return (Criteria) this;
}
public Criteria andTelLessThan(String value) {
addCriterion("tel <", value, "tel");
return (Criteria) this;
}
public Criteria andTelLessThanOrEqualTo(String value) {
addCriterion("tel <=", value, "tel");
return (Criteria) this;
}
public Criteria andTelLike(String value) {
addCriterion("tel like", value, "tel");
return (Criteria) this;
}
public Criteria andTelNotLike(String value) {
addCriterion("tel not like", value, "tel");
return (Criteria) this;
}
public Criteria andTelIn(List<String> values) {
addCriterion("tel in", values, "tel");
return (Criteria) this;
}
public Criteria andTelNotIn(List<String> values) {
addCriterion("tel not in", values, "tel");
return (Criteria) this;
}
public Criteria andTelBetween(String value1, String value2) {
addCriterion("tel between", value1, value2, "tel");
return (Criteria) this;
}
public Criteria andTelNotBetween(String value1, String value2) {
addCriterion("tel not between", value1, value2, "tel");
return (Criteria) this;
}
public Criteria andApptimeIsNull() {
addCriterion("apptime is null");
return (Criteria) this;
}
public Criteria andApptimeIsNotNull() {
addCriterion("apptime is not null");
return (Criteria) this;
}
public Criteria andApptimeEqualTo(Date value) {
addCriterion("apptime =", value, "apptime");
return (Criteria) this;
}
public Criteria andApptimeNotEqualTo(Date value) {
addCriterion("apptime <>", value, "apptime");
return (Criteria) this;
}
public Criteria andApptimeGreaterThan(Date value) {
addCriterion("apptime >", value, "apptime");
return (Criteria) this;
}
public Criteria andApptimeGreaterThanOrEqualTo(Date value) {
addCriterion("apptime >=", value, "apptime");
return (Criteria) this;
}
public Criteria andApptimeLessThan(Date value) {
addCriterion("apptime <", value, "apptime");
return (Criteria) this;
}
public Criteria andApptimeLessThanOrEqualTo(Date value) {
addCriterion("apptime <=", value, "apptime");
return (Criteria) this;
}
public Criteria andApptimeIn(List<Date> values) {
addCriterion("apptime in", values, "apptime");
return (Criteria) this;
}
public Criteria andApptimeNotIn(List<Date> values) {
addCriterion("apptime not in", values, "apptime");
return (Criteria) this;
}
public Criteria andApptimeBetween(Date value1, Date value2) {
addCriterion("apptime between", value1, value2, "apptime");
return (Criteria) this;
}
public Criteria andApptimeNotBetween(Date value1, Date value2) {
addCriterion("apptime not between", value1, value2, "apptime");
return (Criteria) this;
}
public Criteria andAgreetimeIsNull() {
addCriterion("agreetime is null");
return (Criteria) this;
}
public Criteria andAgreetimeIsNotNull() {
addCriterion("agreetime is not null");
return (Criteria) this;
}
public Criteria andAgreetimeEqualTo(Date value) {
addCriterion("agreetime =", value, "agreetime");
return (Criteria) this;
}
public Criteria andAgreetimeNotEqualTo(Date value) {
addCriterion("agreetime <>", value, "agreetime");
return (Criteria) this;
}
public Criteria andAgreetimeGreaterThan(Date value) {
addCriterion("agreetime >", value, "agreetime");
return (Criteria) this;
}
public Criteria andAgreetimeGreaterThanOrEqualTo(Date value) {
addCriterion("agreetime >=", value, "agreetime");
return (Criteria) this;
}
public Criteria andAgreetimeLessThan(Date value) {
addCriterion("agreetime <", value, "agreetime");
return (Criteria) this;
}
public Criteria andAgreetimeLessThanOrEqualTo(Date value) {
addCriterion("agreetime <=", value, "agreetime");
return (Criteria) this;
}
public Criteria andAgreetimeIn(List<Date> values) {
addCriterion("agreetime in", values, "agreetime");
return (Criteria) this;
}
public Criteria andAgreetimeNotIn(List<Date> values) {
addCriterion("agreetime not in", values, "agreetime");
return (Criteria) this;
}
public Criteria andAgreetimeBetween(Date value1, Date value2) {
addCriterion("agreetime between", value1, value2, "agreetime");
return (Criteria) this;
}
public Criteria andAgreetimeNotBetween(Date value1, Date value2) {
addCriterion("agreetime not between", value1, value2, "agreetime");
return (Criteria) this;
}
public Criteria andSendtimeIsNull() {
addCriterion("sendtime is null");
return (Criteria) this;
}
public Criteria andSendtimeIsNotNull() {
addCriterion("sendtime is not null");
return (Criteria) this;
}
public Criteria andSendtimeEqualTo(Date value) {
addCriterion("sendtime =", value, "sendtime");
return (Criteria) this;
}
public Criteria andSendtimeNotEqualTo(Date value) {
addCriterion("sendtime <>", value, "sendtime");
return (Criteria) this;
}
public Criteria andSendtimeGreaterThan(Date value) {
addCriterion("sendtime >", value, "sendtime");
return (Criteria) this;
}
public Criteria andSendtimeGreaterThanOrEqualTo(Date value) {
addCriterion("sendtime >=", value, "sendtime");
return (Criteria) this;
}
public Criteria andSendtimeLessThan(Date value) {
addCriterion("sendtime <", value, "sendtime");
return (Criteria) this;
}
public Criteria andSendtimeLessThanOrEqualTo(Date value) {
addCriterion("sendtime <=", value, "sendtime");
return (Criteria) this;
}
public Criteria andSendtimeIn(List<Date> values) {
addCriterion("sendtime in", values, "sendtime");
return (Criteria) this;
}
public Criteria andSendtimeNotIn(List<Date> values) {
addCriterion("sendtime not in", values, "sendtime");
return (Criteria) this;
}
public Criteria andSendtimeBetween(Date value1, Date value2) {
addCriterion("sendtime between", value1, value2, "sendtime");
return (Criteria) this;
}
public Criteria andSendtimeNotBetween(Date value1, Date value2) {
addCriterion("sendtime not between", value1, value2, "sendtime");
return (Criteria) this;
}
public Criteria andStatusIsNull() {
addCriterion("status is null");
return (Criteria) this;
}
public Criteria andStatusIsNotNull() {
addCriterion("status is not null");
return (Criteria) this;
}
public Criteria andStatusEqualTo(String value) {
addCriterion("status =", value, "status");
return (Criteria) this;
}
public Criteria andStatusNotEqualTo(String value) {
addCriterion("status <>", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThan(String value) {
addCriterion("status >", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThanOrEqualTo(String value) {
addCriterion("status >=", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThan(String value) {
addCriterion("status <", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThanOrEqualTo(String value) {
addCriterion("status <=", value, "status");
return (Criteria) this;
}
public Criteria andStatusLike(String value) {
addCriterion("status like", value, "status");
return (Criteria) this;
}
public Criteria andStatusNotLike(String value) {
addCriterion("status not like", value, "status");
return (Criteria) this;
}
public Criteria andStatusIn(List<String> values) {
addCriterion("status in", values, "status");
return (Criteria) this;
}
public Criteria andStatusNotIn(List<String> values) {
addCriterion("status not in", values, "status");
return (Criteria) this;
}
public Criteria andStatusBetween(String value1, String value2) {
addCriterion("status between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andStatusNotBetween(String value1, String value2) {
addCriterion("status not between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andProductidIsNull() {
addCriterion("productid is null");
return (Criteria) this;
}
public Criteria andProductidIsNotNull() {
addCriterion("productid is not null");
return (Criteria) this;
}
public Criteria andProductidEqualTo(Integer value) {
addCriterion("productid =", value, "productid");
return (Criteria) this;
}
public Criteria andProductidNotEqualTo(Integer value) {
addCriterion("productid <>", value, "productid");
return (Criteria) this;
}
public Criteria andProductidGreaterThan(Integer value) {
addCriterion("productid >", value, "productid");
return (Criteria) this;
}
public Criteria andProductidGreaterThanOrEqualTo(Integer value) {
addCriterion("productid >=", value, "productid");
return (Criteria) this;
}
public Criteria andProductidLessThan(Integer value) {
addCriterion("productid <", value, "productid");
return (Criteria) this;
}
public Criteria andProductidLessThanOrEqualTo(Integer value) {
addCriterion("productid <=", value, "productid");
return (Criteria) this;
}
public Criteria andProductidIn(List<Integer> values) {
addCriterion("productid in", values, "productid");
return (Criteria) this;
}
public Criteria andProductidNotIn(List<Integer> values) {
addCriterion("productid not in", values, "productid");
return (Criteria) this;
}
public Criteria andProductidBetween(Integer value1, Integer value2) {
addCriterion("productid between", value1, value2, "productid");
return (Criteria) this;
}
public Criteria andProductidNotBetween(Integer value1, Integer value2) {
addCriterion("productid not between", value1, value2, "productid");
return (Criteria) this;
}
public Criteria andMoneyidIsNull() {
addCriterion("moneyid is null");
return (Criteria) this;
}
public Criteria andMoneyidIsNotNull() {
addCriterion("moneyid is not null");
return (Criteria) this;
}
public Criteria andMoneyidEqualTo(Integer value) {
addCriterion("moneyid =", value, "moneyid");
return (Criteria) this;
}
public Criteria andMoneyidNotEqualTo(Integer value) {
addCriterion("moneyid <>", value, "moneyid");
return (Criteria) this;
}
public Criteria andMoneyidGreaterThan(Integer value) {
addCriterion("moneyid >", value, "moneyid");
return (Criteria) this;
}
public Criteria andMoneyidGreaterThanOrEqualTo(Integer value) {
addCriterion("moneyid >=", value, "moneyid");
return (Criteria) this;
}
public Criteria andMoneyidLessThan(Integer value) {
addCriterion("moneyid <", value, "moneyid");
return (Criteria) this;
}
public Criteria andMoneyidLessThanOrEqualTo(Integer value) {
addCriterion("moneyid <=", value, "moneyid");
return (Criteria) this;
}
public Criteria andMoneyidIn(List<Integer> values) {
addCriterion("moneyid in", values, "moneyid");
return (Criteria) this;
}
public Criteria andMoneyidNotIn(List<Integer> values) {
addCriterion("moneyid not in", values, "moneyid");
return (Criteria) this;
}
public Criteria andMoneyidBetween(Integer value1, Integer value2) {
addCriterion("moneyid between", value1, value2, "moneyid");
return (Criteria) this;
}
public Criteria andMoneyidNotBetween(Integer value1, Integer value2) {
addCriterion("moneyid not between", value1, value2, "moneyid");
return (Criteria) this;
}
public Criteria andAgent1IsNull() {
addCriterion("agent1 is null");
return (Criteria) this;
}
public Criteria andAgent1IsNotNull() {
addCriterion("agent1 is not null");
return (Criteria) this;
}
public Criteria andAgent1EqualTo(String value) {
addCriterion("agent1 =", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1NotEqualTo(String value) {
addCriterion("agent1 <>", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1GreaterThan(String value) {
addCriterion("agent1 >", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1GreaterThanOrEqualTo(String value) {
addCriterion("agent1 >=", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1LessThan(String value) {
addCriterion("agent1 <", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1LessThanOrEqualTo(String value) {
addCriterion("agent1 <=", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1Like(String value) {
addCriterion("agent1 like", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1NotLike(String value) {
addCriterion("agent1 not like", value, "agent1");
return (Criteria) this;
}
public Criteria andAgent1In(List<String> values) {
addCriterion("agent1 in", values, "agent1");
return (Criteria) this;
}
public Criteria andAgent1NotIn(List<String> values) {
addCriterion("agent1 not in", values, "agent1");
return (Criteria) this;
}
public Criteria andAgent1Between(String value1, String value2) {
addCriterion("agent1 between", value1, value2, "agent1");
return (Criteria) this;
}
public Criteria andAgent1NotBetween(String value1, String value2) {
addCriterion("agent1 not between", value1, value2, "agent1");
return (Criteria) this;
}
public Criteria andAgent2IsNull() {
addCriterion("agent2 is null");
return (Criteria) this;
}
public Criteria andAgent2IsNotNull() {
addCriterion("agent2 is not null");
return (Criteria) this;
}
public Criteria andAgent2EqualTo(String value) {
addCriterion("agent2 =", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2NotEqualTo(String value) {
addCriterion("agent2 <>", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2GreaterThan(String value) {
addCriterion("agent2 >", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2GreaterThanOrEqualTo(String value) {
addCriterion("agent2 >=", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2LessThan(String value) {
addCriterion("agent2 <", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2LessThanOrEqualTo(String value) {
addCriterion("agent2 <=", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2Like(String value) {
addCriterion("agent2 like", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2NotLike(String value) {
addCriterion("agent2 not like", value, "agent2");
return (Criteria) this;
}
public Criteria andAgent2In(List<String> values) {
addCriterion("agent2 in", values, "agent2");
return (Criteria) this;
}
public Criteria andAgent2NotIn(List<String> values) {
addCriterion("agent2 not in", values, "agent2");
return (Criteria) this;
}
public Criteria andAgent2Between(String value1, String value2) {
addCriterion("agent2 between", value1, value2, "agent2");
return (Criteria) this;
}
public Criteria andAgent2NotBetween(String value1, String value2) {
addCriterion("agent2 not between", value1, value2, "agent2");
return (Criteria) this;
}
public Criteria andMobiIsNull() {
addCriterion("mobi is null");
return (Criteria) this;
}
public Criteria andMobiIsNotNull() {
addCriterion("mobi is not null");
return (Criteria) this;
}
public Criteria andMobiEqualTo(String value) {
addCriterion("mobi =", value, "mobi");
return (Criteria) this;
}
public Criteria andMobiNotEqualTo(String value) {
addCriterion("mobi <>", value, "mobi");
return (Criteria) this;
}
public Criteria andMobiGreaterThan(String value) {
addCriterion("mobi >", value, "mobi");
return (Criteria) this;
}
public Criteria andMobiGreaterThanOrEqualTo(String value) {
addCriterion("mobi >=", value, "mobi");
return (Criteria) this;
}
public Criteria andMobiLessThan(String value) {
addCriterion("mobi <", value, "mobi");
return (Criteria) this;
}
public Criteria andMobiLessThanOrEqualTo(String value) {
addCriterion("mobi <=", value, "mobi");
return (Criteria) this;
}
public Criteria andMobiLike(String value) {
addCriterion("mobi like", value, "mobi");
return (Criteria) this;
}
public Criteria andMobiNotLike(String value) {
addCriterion("mobi not like", value, "mobi");
return (Criteria) this;
}
public Criteria andMobiIn(List<String> values) {
addCriterion("mobi in", values, "mobi");
return (Criteria) this;
}
public Criteria andMobiNotIn(List<String> values) {
addCriterion("mobi not in", values, "mobi");
return (Criteria) this;
}
public Criteria andMobiBetween(String value1, String value2) {
addCriterion("mobi between", value1, value2, "mobi");
return (Criteria) this;
}
public Criteria andMobiNotBetween(String value1, String value2) {
addCriterion("mobi not between", value1, value2, "mobi");
return (Criteria) this;
}
public Criteria andSendtypeIsNull() {
addCriterion("sendtype is null");
return (Criteria) this;
}
public Criteria andSendtypeIsNotNull() {
addCriterion("sendtype is not null");
return (Criteria) this;
}
public Criteria andSendtypeEqualTo(String value) {
addCriterion("sendtype =", value, "sendtype");
return (Criteria) this;
}
public Criteria andSendtypeNotEqualTo(String value) {
addCriterion("sendtype <>", value, "sendtype");
return (Criteria) this;
}
public Criteria andSendtypeGreaterThan(String value) {
addCriterion("sendtype >", value, "sendtype");
return (Criteria) this;
}
public Criteria andSendtypeGreaterThanOrEqualTo(String value) {
addCriterion("sendtype >=", value, "sendtype");
return (Criteria) this;
}
public Criteria andSendtypeLessThan(String value) {
addCriterion("sendtype <", value, "sendtype");
return (Criteria) this;
}
public Criteria andSendtypeLessThanOrEqualTo(String value) {
addCriterion("sendtype <=", value, "sendtype");
return (Criteria) this;
}
public Criteria andSendtypeLike(String value) {
addCriterion("sendtype like", value, "sendtype");
return (Criteria) this;
}
public Criteria andSendtypeNotLike(String value) {
addCriterion("sendtype not like", value, "sendtype");
return (Criteria) this;
}
public Criteria andSendtypeIn(List<String> values) {
addCriterion("sendtype in", values, "sendtype");
return (Criteria) this;
}
public Criteria andSendtypeNotIn(List<String> values) {
addCriterion("sendtype not in", values, "sendtype");
return (Criteria) this;
}
public Criteria andSendtypeBetween(String value1, String value2) {
addCriterion("sendtype between", value1, value2, "sendtype");
return (Criteria) this;
}
public Criteria andSendtypeNotBetween(String value1, String value2) {
addCriterion("sendtype not between", value1, value2, "sendtype");
return (Criteria) this;
}
public Criteria andTitleidIsNull() {
addCriterion("titleID is null");
return (Criteria) this;
}
public Criteria andTitleidIsNotNull() {
addCriterion("titleID is not null");
return (Criteria) this;
}
public Criteria andTitleidEqualTo(String value) {
addCriterion("titleID =", value, "titleid");
return (Criteria) this;
}
public Criteria andTitleidNotEqualTo(String value) {
addCriterion("titleID <>", value, "titleid");
return (Criteria) this;
}
public Criteria andTitleidGreaterThan(String value) {
addCriterion("titleID >", value, "titleid");
return (Criteria) this;
}
public Criteria andTitleidGreaterThanOrEqualTo(String value) {
addCriterion("titleID >=", value, "titleid");
return (Criteria) this;
}
public Criteria andTitleidLessThan(String value) {
addCriterion("titleID <", value, "titleid");
return (Criteria) this;
}
public Criteria andTitleidLessThanOrEqualTo(String value) {
addCriterion("titleID <=", value, "titleid");
return (Criteria) this;
}
public Criteria andTitleidLike(String value) {
addCriterion("titleID like", value, "titleid");
return (Criteria) this;
}
public Criteria andTitleidNotLike(String value) {
addCriterion("titleID not like", value, "titleid");
return (Criteria) this;
}
public Criteria andTitleidIn(List<String> values) {
addCriterion("titleID in", values, "titleid");
return (Criteria) this;
}
public Criteria andTitleidNotIn(List<String> values) {
addCriterion("titleID not in", values, "titleid");
return (Criteria) this;
}
public Criteria andTitleidBetween(String value1, String value2) {
addCriterion("titleID between", value1, value2, "titleid");
return (Criteria) this;
}
public Criteria andTitleidNotBetween(String value1, String value2) {
addCriterion("titleID not between", value1, value2, "titleid");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated do_not_delete_during_merge Fri May 11 11:16:07 CST 2018
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table FreeHost_Fapiao
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} |
package com.onplan.service;
import com.onplan.adviser.alert.AlertEvent;
/**
* Notifies alerts and system events to the registered channels (eg. SMTP, JMS, Twitter, etc).
*/
public interface EventNotificationService {
/**
* Dispatches the alert event to via the active channels in a separated thread.
*
* @param alertEvent The alert event.
*/
public void notifyAlertEventAsync(AlertEvent alertEvent);
/**
* Dispatches the system event to via the active channels in a separated thread.
*
* @param systemEvent The system event.
*/
public void notifySystemEventAsync(final SystemEvent systemEvent);
}
|
package com.danielgomez.archiver;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implements archive operations with zip format
*/
public class ZipArchiver implements Archiver {
private static Logger LOGGER = LoggerFactory.getLogger( ZipArchiver.class );
/**
* Ensures the following conditions:
* <ul>
* <li>Input path exists</li>
* <li>Input path is a directory</li>
* <li>Input path is not empty</li>
* <li>Output path is a directory if it exists</li>
* </ul>
* Additionally, it creates the output path if it does not exist.
*
* @param options parameters
* @throws IOException when unable to determine conditions due to IO errors
*/
private static void checkArguments( IOOptions options ) throws IOException {
Path inputDir = options.getInput();
if ( Files.notExists( inputDir ) )
throw new FileNotFoundException( "Input '" + inputDir + "' does not exist" );
if ( !Files.isDirectory( inputDir ) )
throw new IllegalArgumentException( "Input '" + inputDir + "' is not a directory" );
try ( Stream<Path> children = Files.list( inputDir ) ) {
if ( !children.findAny().isPresent() )
throw new NoSuchFileException( "Input '" + inputDir + "' is empty" );
}
Path outputDir = options.getOutput();
if ( Files.exists( outputDir ) ) {
if ( !Files.isDirectory( outputDir ) )
throw new IllegalArgumentException( "Output '" + outputDir + "' is not a directory" );
} else
Files.createDirectories( outputDir );
}
/**
* Compresses a directory and the files inside it by doing the following processes:
* <ul>
* <li>
* Input directory is split into chunks. A chunk is a list of files in which the total file size do not
* exceed the maximum file size configured in the compression options. A file may also be chunked if it
* exceeds the limit.
* </li>
* <li>
* A corresponding zip file is generated for each chunk. If there is only one chunk, a single zip file is
* generated using the name of the input directory. Otherwise, multiple zip files are
* generated with a suffix of '.part.{n}' where 'n' is the chunk number. Chunks are written to a zip in a
* parallel-manner.
* </li>
* </ul>
* <p>
*
* @param options compression configuration
* @throws IOException when compression fails due to IO errors
*/
@Override
public void compress( CompressionOptions options ) throws IOException {
checkArguments( options );
Path inputDir = options.getInput();
Path outputDir = options.getOutput();
Path output = outputDir.resolve( inputDir.getFileName() + ".zip" );
Path tempDir = Files.createTempDirectory( "compress-" ).resolve( options.getInput().getFileName().toString() );
List<List<Path>> chunked = chunk( inputDir, options, tempDir );
if ( chunked.size() == 1 ) {
writeToZip( chunked.get( 0 ), output, options, tempDir );
} else {
IntStream.range( 0, chunked.size() )
.parallel()
.forEach( i -> {
try {
Path zipFile = partFile( output, "" + i );
writeToZip( chunked.get( i ), zipFile, options, tempDir );
} catch ( IOException e ) {
sneakyThrow( e );
}
} );
}
if ( Files.notExists( tempDir ) )
return;
try ( Stream<Path> walk = Files.list( tempDir ) ) {
walk.forEach( p -> {
try {
Files.delete( p );
} catch ( IOException e ) {
sneakyThrow( e );
}
} );
}
Files.delete( tempDir );
}
@Override
public void decompress( DecompressionOptions options ) throws IOException {
checkArguments( options );
Path inputDir = options.getInput();
Path outputDir = options.getOutput();
List<Path> inputFiles = Files.list( inputDir ).sorted()
.filter( path -> path.toString().endsWith( ".zip" ) )
.collect( Collectors.toList() );
if ( inputFiles.size() <= 0 )
throw new IllegalArgumentException( "Input directory '" + inputDir + " is empty" );
for ( Path inputFile : inputFiles ) {
ZipInputStream zis = new ZipInputStream( Files.newInputStream( inputFile ) );
ZipEntry zipEntry = zis.getNextEntry();
while ( zipEntry != null ) {
Path outputFile = outputDir.resolve( zipEntry.getName() );
if ( zipEntry.isDirectory() ) {
Files.createDirectories( outputFile );
} else {
outputFile = unpartFile( outputFile );
OutputStream fos = Files.newOutputStream( outputFile, CREATE, APPEND );
byte[] buffer = new byte[options.getBufferSize()];
int len;
while ( ( len = zis.read( buffer ) ) > 0 ) {
fos.write( buffer, 0, len );
}
fos.close();
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
}
/**
* Writes a list of path to a zip file
*
* @param contents paths to write
* @param zipFile the zip file
* @param options IO options
*/
private static void writeToZip( List<Path> contents, Path zipFile, IOOptions options, Path tempDir )
throws IOException {
try ( ZipOutputStream zos = new ZipOutputStream( Files.newOutputStream( zipFile ) ) ) {
for ( Path path : contents ) {
Path transformed;
if ( path.getFileName().toString().contains( ".part." ) )
transformed = tempDir.relativize( path );
else {
transformed = options.getInput().relativize( path );
}
String fileName = transformed.toString();
if ( Files.isRegularFile( path ) ) {
try ( InputStream fis = Files.newInputStream( path ) ) {
ZipEntry zipEntry = new ZipEntry( fileName );
zos.putNextEntry( zipEntry );
byte[] buffer = new byte[options.getBufferSize()];
int bufferReadLength;
while ( ( bufferReadLength = fis.read( buffer ) ) >= 0 ) {
zos.write( buffer, 0, bufferReadLength );
}
zos.closeEntry();
}
LOGGER.debug( "Written file={}", fileName );
} else {
fileName += "/";
zos.putNextEntry( new ZipEntry( fileName ) );
zos.closeEntry();
LOGGER.debug( "Written directory={}", fileName );
}
}
}
}
private static <E extends Throwable> void sneakyThrow( Throwable e ) throws E {
throw ( E ) e;
}
private static List<List<Path>> chunk( Path dir, CompressionOptions options, Path tempDir ) throws IOException {
ChunkingFileVisitor visitor = new ChunkingFileVisitor( options, tempDir );
Files.walkFileTree( dir, visitor );
return visitor.getChunks();
}
private static Path partFile( Path path, String partNumber ) {
String fileName = path.getFileName().toString();
if ( fileName.contains( "." ) ) {
int extensionIndex = fileName.lastIndexOf( "." );
String baseName = fileName.substring( 0, extensionIndex );
String extension = fileName.substring( extensionIndex );
return path.getParent().resolve( baseName + ".part." + partNumber + extension );
}
return path.getParent().resolve( fileName + ".part." + partNumber );
}
private static Path unpartFile( Path path ) {
String fileName = path.getFileName().toString();
if ( fileName.matches( ".*part.[0-9]+.*" ) ) {
String baseName = fileName.substring( 0, fileName.indexOf( ".part" ) );
String extension = fileName.substring( fileName.lastIndexOf( "." ) );
return path.getParent().resolve( baseName + extension );
}
return path;
}
/**
* A file visitor that chunks file paths such that each chunk does not exceed max file size. This class asserts that
* a single path does not exceed max file size, otherwise an {@link IllegalArgumentException} is thrown.
*/
private static class ChunkingFileVisitor extends SimpleFileVisitor<Path> {
private List<List<Path>> chunks = new ArrayList<>();
private List<Path> currentChunk = new ArrayList<>();
private long currentChunkSize = 0;
private CompressionOptions options;
private final Path tempDir;
public ChunkingFileVisitor( CompressionOptions options, Path tempDir ) {
this.options = options;
this.tempDir = tempDir;
}
public List<List<Path>> getChunks() {
if ( currentChunk.size() > 0 ) {
chunks.add( currentChunk );
currentChunk = Collections.emptyList();
}
return chunks;
}
private long getMaxFileSize() {
return options.getMaxFileSize();
}
@Override
public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) throws IOException {
if ( file.getFileName().toString().equals( ".DS_Store" ) )
return FileVisitResult.CONTINUE;
super.visitFile( file, attrs );
long size = Files.size( file );
if ( getMaxFileSize() > 0 && size + currentChunkSize > getMaxFileSize() ) {
if ( size > getMaxFileSize() ) {
for ( Path part : refine( file, size, tempDir ) ) {
visitFile( part, attrs );
}
return FileVisitResult.CONTINUE;
}
chunks.add( currentChunk );
currentChunk = new ArrayList<>();
currentChunkSize = 0;
addToChunk( file, size );
} else {
addToChunk( file, size );
LOGGER.trace( "File '{}' added on chunk '{}'", file, chunks.size() );
}
return FileVisitResult.CONTINUE;
}
private void addToChunk( Path file, long size ) {
currentChunk.add( file );
currentChunkSize += size;
LOGGER.trace( "'{}' added on chunk '{}'", file, chunks.size() );
}
@Override
public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs ) throws IOException {
if ( dir.equals( options.getInput() ) )
return FileVisitResult.CONTINUE;
super.preVisitDirectory( dir, attrs );
addToChunk( dir, 0 );
return FileVisitResult.CONTINUE;
}
static void readWrite( InputStream raf, OutputStream bw, long numBytes ) throws IOException {
byte[] buf = new byte[( int ) numBytes];
int val = raf.read( buf );
if ( val != -1 ) {
bw.write( buf );
}
}
/**
* Splits a file into multiple files such that each part of the file does not exceed max file size
*
* @param path the file to split
* @param size the size of the file
* @return list of parts that were generated
* @throws IOException when splitting fails
*/
private List<Path> refine( Path path, long size, Path tempDir ) throws IOException {
List<Path> createdParts = new ArrayList<>();
long parts = size / getMaxFileSize();
long sizePerPart = getMaxFileSize();
long remainingSize = size % getMaxFileSize();
int bufferSize = 1024;
try ( InputStream is = Files.newInputStream( path ) ) {
for ( int i = 0; i < parts; i++ ) {
Path part = tempDir.resolve( options.getInput().relativize( partFile( path, "" + i ) ).toString() );
Files.createDirectories( part.getParent() );
OutputStream bw = Files.newOutputStream( part );
if ( sizePerPart > bufferSize ) {
long numReads = sizePerPart / bufferSize;
long numRemainingRead = sizePerPart % bufferSize;
for ( int j = 0; j < numReads; j++ ) {
readWrite( is, bw, bufferSize );
}
if ( numRemainingRead > 0 ) {
readWrite( is, bw, numRemainingRead );
}
} else {
readWrite( is, bw, sizePerPart );
}
createdParts.add( part );
bw.close();
}
if ( remainingSize > 0 ) {
Path part = tempDir.resolve( options.getInput().relativize( partFile( path, "" + parts ) ).toString() );
try ( OutputStream bw = Files.newOutputStream( part ) ) {
readWrite( is, bw, remainingSize );
createdParts.add( part );
}
}
}
return createdParts;
}
}
}
|
package service;
import java.util.ArrayList;
import entity.Product;
import exception.DAOException;
import exception.ProductException;
public interface IProductService {
public void add(Product product) throws DAOException, ProductException;
public void modifyNum(int id, int num) throws DAOException,
ProductException;
public void modifyPrice(int id, double price) throws DAOException,
ProductException;
public void delete(int id) throws ProductException, DAOException;
public Product lookByName(String name) throws DAOException,
ProductException;
public ArrayList<Product> LookAll() throws DAOException, ProductException;
public Product lookById(int id) throws DAOException, ProductException;
public int searchPageNum() throws ProductException, DAOException;
public ArrayList<Product> LookAll(int page) throws DAOException,
ProductException;
}
|
package practice;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.io.FileHandler;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TakeScreenshot {
public static WebDriver driver;
@BeforeClass
public void setUpBrowser() {
System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe");
//Create Chrome driver's instance
driver = new ChromeDriver();
driver.manage().window().maximize();
//Set implicit wait of 10 seconds
//This is required for managing waits in selenium webdriver
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://selfcare.actcorp.in/web/hyd/home");
}
@Test
public void testMethod() throws IOException {
WebElement elm = driver.findElement(By.xpath("//a[@class='logo']"));
File src = ((TakesScreenshot)elm).getScreenshotAs(OutputType.FILE);
FileHandler.copy(src, new File("./Screenshots/pic.png"));
//Using WebDriver4
File src1 = driver.findElement(By.xpath("//a[@class='logo']")).getScreenshotAs(OutputType.FILE);
FileHandler.copy(src1, new File("./Screenshots/photo.png"));
}
@AfterClass
public void quitTheBrowser() {
driver.quit();
}
}
|
package pl.cwanix.opensun.db.account;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import pl.cwanix.opensun.db.account.entity.UserEntity;
import pl.cwanix.opensun.db.account.repository.UserEntityRepository;
import pl.cwanix.opensun.model.account.AccountDataSource;
import pl.cwanix.opensun.model.account.UserModel;
@Service
@RequiredArgsConstructor
public class AccountDataSourceImpl implements AccountDataSource {
private final ModelMapper modelMapper;
private final UserEntityRepository userEntityRepository;
@Override
public UserModel findUser(final String name) {
final UserEntity entity = userEntityRepository.findByName(name);
return modelMapper.map(entity, UserModel.class);
}
}
|
package sp.designpatterns.DecoratorExample;
public class ItalianPizzero extends Pizza{
ItalianPizzero(String description){
this.description=description;
}
@Override
public double getCost() {
// TODO Auto-generated method stub
return 70;
}
}
|
package com.xampy.namboo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import com.xampy.namboo.R;
import com.xampy.namboo.api.dataModel.DataBaseUser;
import com.xampy.namboo.api.database.AppDataBaseManager;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import com.xampy.namboo.api.dataModel.DataBaseUser;
import com.xampy.namboo.api.database.AppDataBaseManager;
import java.util.concurrent.TimeUnit;
public class NambooPostActivity extends AppCompatActivity {
private static final long DELAY_TO_APP = 2000;
private long startTime;
private DataBaseUser currentUser;
private boolean mUserLogged;
private FirebaseAuth mAuth;
private static FirebaseUser ResultedUser;
private boolean mContinueTo;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_namboo_post);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
mContinueTo = false;
final long startTime = System.currentTimeMillis();
new Thread(new Runnable() {
@Override
public void run() {
while(System.currentTimeMillis() - startTime < 2000);
openMainActivity();
}
}).start();
}
private void openMainActivity() {
//[START get instance of firebase auth
//FirebaseAuth auth = FirebaseAuth.getInstance();
//[END get instance of firebase auth
//[START database checking]
AppDataBaseManager appDataBaseManager = new AppDataBaseManager(getApplicationContext());
currentUser = AppDataBaseManager.DB_USER_TABLE.getUser(); //Start getting the user
mUserLogged = false;
//Check if user is null
//and if, we init the database with data
if (currentUser == null) {
appDataBaseManager.initDatabaseContent(); //Construct a new default user
currentUser = AppDataBaseManager.DB_USER_TABLE.getUser();
Log.i("USER DATABASE", currentUser.getUsername());
} else {
//Avoid default user values
if (currentUser.getTel().startsWith("+") && !currentUser.getUid().equals("@none")) {
mUserLogged = true;
} else {
mUserLogged = false;
mContinueTo = true; //Allow access
}
}
Intent home_activity = new Intent(NambooPostActivity.this, MainActivity.class);
home_activity.putExtra("USER_LOGIN_STATE", mUserLogged);
startActivity(home_activity);
//Finish this fullscreen activity
finish();
//[END database checking]
}
}
|
/**
* Bitcoind
* The REST API can be enabled with the `-rest` option. The interface runs on the same port as the JSON-RPC interface, by default port `8332` for **mainnet**, port `18332` for **testnet**, and port `18443` for **regtest**.
*
* OpenAPI spec version: 0.16
* Contact: johan@lepetitbloc.net
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.*;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class ScriptPubKey {
@SerializedName("asm")
private String asm = null;
@SerializedName("hex")
private String hex = null;
@SerializedName("reqSigs")
private Integer reqSigs = null;
public enum TypeEnum {
nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash, witness_unknown,
};
@SerializedName("type")
private TypeEnum type = null;
@SerializedName("addresses")
private List<String> addresses = null;
/**
**/
@ApiModelProperty(value = "")
public String getAsm() {
return asm;
}
public void setAsm(String asm) {
this.asm = asm;
}
/**
**/
@ApiModelProperty(value = "")
public String getHex() {
return hex;
}
public void setHex(String hex) {
this.hex = hex;
}
/**
**/
@ApiModelProperty(value = "")
public Integer getReqSigs() {
return reqSigs;
}
public void setReqSigs(Integer reqSigs) {
this.reqSigs = reqSigs;
}
/**
**/
@ApiModelProperty(value = "")
public TypeEnum getType() {
return type;
}
public void setType(TypeEnum type) {
this.type = type;
}
/**
**/
@ApiModelProperty(value = "")
public List<String> getAddresses() {
return addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ScriptPubKey scriptPubKey = (ScriptPubKey) o;
return (this.asm == null ? scriptPubKey.asm == null : this.asm.equals(scriptPubKey.asm)) &&
(this.hex == null ? scriptPubKey.hex == null : this.hex.equals(scriptPubKey.hex)) &&
(this.reqSigs == null ? scriptPubKey.reqSigs == null : this.reqSigs.equals(scriptPubKey.reqSigs)) &&
(this.type == null ? scriptPubKey.type == null : this.type.equals(scriptPubKey.type)) &&
(this.addresses == null ? scriptPubKey.addresses == null : this.addresses.equals(scriptPubKey.addresses));
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (this.asm == null ? 0: this.asm.hashCode());
result = 31 * result + (this.hex == null ? 0: this.hex.hashCode());
result = 31 * result + (this.reqSigs == null ? 0: this.reqSigs.hashCode());
result = 31 * result + (this.type == null ? 0: this.type.hashCode());
result = 31 * result + (this.addresses == null ? 0: this.addresses.hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ScriptPubKey {\n");
sb.append(" asm: ").append(asm).append("\n");
sb.append(" hex: ").append(hex).append("\n");
sb.append(" reqSigs: ").append(reqSigs).append("\n");
sb.append(" type: ").append(type).append("\n");
sb.append(" addresses: ").append(addresses).append("\n");
sb.append("}\n");
return sb.toString();
}
}
|
package com.tencent.mm.plugin.appbrand.widget.input.autofill;
import android.widget.EditText;
import com.samsung.android.sdk.look.airbutton.SlookAirButtonFrequentContactAdapter;
import com.tencent.mm.plugin.appbrand.jsapi.d.f$a;
import com.tencent.mm.plugin.appbrand.page.p;
import com.tencent.mm.plugin.appbrand.widget.input.autofill.h.a;
import com.tencent.mm.plugin.appbrand.widget.input.z;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
class d$1 implements h {
final /* synthetic */ WeakReference fQJ;
final /* synthetic */ WeakReference gKn;
d$1(WeakReference weakReference, WeakReference weakReference2) {
this.gKn = weakReference;
this.fQJ = weakReference2;
}
public final void a(String str, a aVar) {
EditText editText = (EditText) this.gKn.get();
p pVar = (p) this.fQJ.get();
if (editText != null && pVar != null) {
int inputId = ((z) editText).getInputId();
f$a f_a = new f$a();
Map hashMap = new HashMap();
hashMap.put(SlookAirButtonFrequentContactAdapter.ID, str);
hashMap.put("type", aVar.name().toLowerCase());
hashMap.put("inputId", Integer.valueOf(inputId));
f_a.aC(pVar.mAppId, pVar.hashCode()).x(hashMap).h(new int[]{pVar.hashCode()});
}
}
}
|
package dao;
import model.City;
import model.Coach;
import model.Country;
import model.FootballClub;
import model.League;
import model.News;
import model.Player;
public interface NewsDao extends BaseDao<Long, News> {
void addTags(News news, Country country, City city, Coach coach, Player player, FootballClub club, League league);
News getNewsWithTags(Long id);
}
|
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.05.11 um 01:33:35 PM CEST
//
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml;
import java.math.BigInteger;
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.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für IstAnalyseType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="IstAnalyseType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="IstAnalyseIdent" type="{http://www-fls.thyssen.com/xml/schema/qcs}IstAnalyseIdentType"/>
* <element name="Materialklasse" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/>
* <element name="StahlmarkenKurzbezeichnung" type="{http://www-fls.thyssen.com/xml/schema/qcs}StringMax5" minOccurs="0"/>
* <element name="StahlmarkenKurzbezeichnungDFS" type="{http://www-fls.thyssen.com/xml/schema/qcs}StringMax5" minOccurs="0"/>
* <element name="K_Wert" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/>
* <element name="Element" type="{http://www-fls.thyssen.com/xml/schema/qcs}ElementType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "IstAnalyseType", propOrder = {
"istAnalyseIdent",
"materialklasse",
"stahlmarkenKurzbezeichnung",
"stahlmarkenKurzbezeichnungDFS",
"kWert",
"element"
})
public class IstAnalyseType {
@XmlElement(name = "IstAnalyseIdent", required = true)
protected IstAnalyseIdentType istAnalyseIdent;
@XmlElement(name = "Materialklasse")
protected BigInteger materialklasse;
@XmlElement(name = "StahlmarkenKurzbezeichnung")
protected String stahlmarkenKurzbezeichnung;
@XmlElement(name = "StahlmarkenKurzbezeichnungDFS")
protected String stahlmarkenKurzbezeichnungDFS;
@XmlElement(name = "K_Wert")
protected Double kWert;
@XmlElement(name = "Element")
protected List<ElementType> element;
/**
* Ruft den Wert der istAnalyseIdent-Eigenschaft ab.
*
* @return
* possible object is
* {@link IstAnalyseIdentType }
*
*/
public IstAnalyseIdentType getIstAnalyseIdent() {
return istAnalyseIdent;
}
/**
* Legt den Wert der istAnalyseIdent-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link IstAnalyseIdentType }
*
*/
public void setIstAnalyseIdent(IstAnalyseIdentType value) {
this.istAnalyseIdent = value;
}
/**
* Ruft den Wert der materialklasse-Eigenschaft ab.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getMaterialklasse() {
return materialklasse;
}
/**
* Legt den Wert der materialklasse-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setMaterialklasse(BigInteger value) {
this.materialklasse = value;
}
/**
* Ruft den Wert der stahlmarkenKurzbezeichnung-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStahlmarkenKurzbezeichnung() {
return stahlmarkenKurzbezeichnung;
}
/**
* Legt den Wert der stahlmarkenKurzbezeichnung-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStahlmarkenKurzbezeichnung(String value) {
this.stahlmarkenKurzbezeichnung = value;
}
/**
* Ruft den Wert der stahlmarkenKurzbezeichnungDFS-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStahlmarkenKurzbezeichnungDFS() {
return stahlmarkenKurzbezeichnungDFS;
}
/**
* Legt den Wert der stahlmarkenKurzbezeichnungDFS-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStahlmarkenKurzbezeichnungDFS(String value) {
this.stahlmarkenKurzbezeichnungDFS = value;
}
/**
* Ruft den Wert der kWert-Eigenschaft ab.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getKWert() {
return kWert;
}
/**
* Legt den Wert der kWert-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setKWert(Double value) {
this.kWert = value;
}
/**
* Gets the value of the element 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 element property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getElement().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ElementType }
*
*
*/
public List<ElementType> getElement() {
if (element == null) {
element = new ArrayList<ElementType>();
}
return this.element;
}
}
|
package com.tencent.mm.plugin.account.security.a;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.bvd;
import com.tencent.mm.protocal.c.bve;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
public final class c extends l implements k {
public String bKv;
public String byN;
public String deviceName;
private b diG;
private e diJ;
public c(String str, String str2, String str3) {
a aVar = new a();
aVar.dIG = new bvd();
aVar.dIH = new bve();
aVar.uri = "/cgi-bin/micromsg-bin/updatesafedevice";
aVar.dIF = 361;
aVar.dII = 0;
aVar.dIJ = 0;
this.diG = aVar.KT();
this.byN = str;
this.deviceName = str2;
this.bKv = str3;
bvd bvd = (bvd) this.diG.dID.dIL;
bvd.rvq = str;
bvd.jPe = str2;
bvd.reT = str3;
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
x.i("MicroMsg.NetscenUpdateSafeDevice", "errType = " + i2 + ", errCode = " + i3);
this.diJ.a(i2, i3, str, this);
}
public final int getType() {
return 361;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
if (bi.oW(this.byN) || bi.oW(this.deviceName) || bi.oW(this.bKv)) {
x.e("MicroMsg.NetscenUpdateSafeDevice", "null device is or device name or device type");
return -1;
}
this.diJ = eVar2;
return a(eVar, this.diG, this);
}
}
|
/*
* Copyright (c) 2016, Oracle and/or its affiliates.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.ac.man.cs.llvm.ir.types;
import uk.ac.man.cs.llvm.ir.model.ValueSymbol;
public final class StructureType implements AggregateType, ValueSymbol {
private String name = ValueSymbol.UNKNOWN;
private final boolean isPacked;
private final Type[] types;
public StructureType(boolean isPacked, Type[] types) {
this.isPacked = isPacked;
this.types = types;
}
@Override
public int getAlignment() {
return types == null || types.length == 0 ? Long.BYTES : types[0].getAlignment();
}
@Override
public Type getElementType(int index) {
return types[index];
}
@Override
public int getElementCount() {
return types.length;
}
@Override
public String getName() {
return name;
}
@Override
public Type getType() {
return this;
}
public boolean isPacked() {
return isPacked;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public int sizeof() {
int size = 0;
for (Type type : types) {
size += type.sizeof() + calculatePadding(type.getAlignment(), size);
}
return size;
}
@Override
public int sizeof(int alignment) {
int size = 0;
for (Type type : types) {
size = size + type.sizeof(alignment) + calculatePadding(Math.min(alignment, type.getAlignment()), size);
}
return size;
}
public String toDeclarationString() {
StringBuilder str = new StringBuilder();
if (isPacked) {
str.append("<{ ");
} else {
str.append("{ ");
}
for (int i = 0; i < types.length; i++) {
Type type = types[i];
if (i > 0) {
str.append(", ");
}
if (type instanceof PointerType && ((PointerType) type).getPointeeType() == this) {
str.append("%").append(getName()).append("*");
} else {
str.append(type);
}
}
if (isPacked) {
str.append(" }>");
} else {
str.append(" }");
}
return str.toString();
}
@Override
public String toString() {
if (name.equals(ValueSymbol.UNKNOWN)) {
return toDeclarationString();
} else {
return "%" + name;
}
}
private int calculatePadding(int alignment, int address) {
if (isPacked || alignment == 1) {
return 0;
}
int mask = alignment - 1;
return (alignment - (address & mask)) & mask;
}
}
|
package org.geoserver.wcs2_0.post;
import static org.junit.Assert.assertNotNull;
import org.geoserver.wcs2_0.WCSTestSupport;
import org.junit.Test;
import org.w3c.dom.Document;
public class DescribeCoverageTest extends WCSTestSupport {
@Test
public void testDescribeCoveragePOST() throws Exception {
String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<wcs:DescribeCoverage xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n" +
" xmlns:wcs='http://www.opengis.net/wcs/2.0' xmlns:gml='http://www.opengis.net/gml/3.2'\n" +
" xsi:schemaLocation='http://www.opengis.net/wcs/2.0 http://schemas.opengis.net/wcs/2.0/wcsAll.xsd'\n" +
" service=\"WCS\" version=\"2.0.1\">\n" +
" <wcs:CoverageId>wcs__BlueMarble</wcs:CoverageId>\n" +
"</wcs:DescribeCoverage>";
Document dom = postAsDOM("wcs", request);
assertNotNull(dom);
print(dom, System.out);
checkValidationErrors(dom, WCS20_SCHEMA);
}
}
|
import java.awt.*;
public class ep6_4 {
private Frame f;
private Button b1;
private Button b2;
public static void main(String args[]) {
ep6_4 that = new ep6_4();
that.go();
}
public void go() {
f = new Frame("GUI example");
f.setLayout(new FlowLayout());
// 设置布局管理器为FlowLayout
b1 = new Button("Press Me");
// 按钮上显示字符"Press Me"
b2 = new Button("Don't Press Me");
f.add(b1);
f.add(b2);
f.pack();
// 紧凑排列,让窗口尽量小,小到刚刚能够包容住b1、b2两个按钮
f.setVisible(true);
}
}
|
/*
* Copyright 2016 Philadelphia authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.paritytrading.philadelphia.coinbase;
import static com.paritytrading.philadelphia.coinbase.CoinbaseTags.*;
import static com.paritytrading.philadelphia.fix42.FIX42MsgTypes.*;
import static com.paritytrading.philadelphia.fix42.FIX42Tags.*;
import static java.nio.charset.StandardCharsets.*;
import com.paritytrading.philadelphia.FIXMessage;
import com.paritytrading.philadelphia.FIXValue;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* Common definitions for Coinbase Pro FIX API.
*/
public class Coinbase {
private static final char SOH = '\u0001';
private Coinbase() {
}
/**
* <p>Sign a Logon(A) message. Before calling this method, the following
* required fields must already be present in the message:</p>
*
* <ul>
* <li>SendingTime(52)</li>
* <li>MsgSeqNum(34)</li>
* <li>SenderCompID(49)</li>
* <li>TargetCompID(56)</li>
* <li>Password(554)</li>
* </ul>
*
* <p>This method adds a RawData(96) field to the message.</p>
*
* @param message a Logon(A) message
* @param secret the secret
* @throws IllegalStateException if one or more of the required fields are
* missing
*/
public static void sign(FIXMessage message, String secret) {
StringBuilder presign = new StringBuilder();
appendField(message, SendingTime, "SendingTime(52)", presign);
presign.append(SOH);
presign.append(Logon);
presign.append(SOH);
appendField(message, MsgSeqNum, "MsgSeqNum(34)", presign);
presign.append(SOH);
appendField(message, SenderCompID, "SenderCompID(49)", presign);
presign.append(SOH);
appendField(message, TargetCompID, "TargetCompID(56)", presign);
presign.append(SOH);
appendField(message, Password, "Password(554)", presign);
Key key = new SecretKeySpec(Base64.getDecoder().decode(secret), "HmacSHA256");
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(key);
mac.update(presign.toString().getBytes(US_ASCII));
String sign = Base64.getEncoder().encodeToString(mac.doFinal());
message.addField(RawData).setString(sign);
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private static void appendField(FIXMessage message, int tag, String fieldName, StringBuilder s) {
FIXValue value = message.valueOf(tag);
if (value == null)
throw new IllegalStateException(fieldName + " not found");
s.append(value);
}
}
|
package ThreadDemo;
/**
*
* @author Bohdan Skrypnyk
*/
class A {
synchronized void foo(B b) {
String name = new Thread().getName();
System.out.println(name + " entered in method A.foo();");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("Class B Interrupted");
}
System.out.println(name + " entered in method A.foo();");
b.last();
}
synchronized void last() {
System.out.println("Method A.last(); ");
}
}
class B {
synchronized void bar(A a) {
String name = new Thread().getName();
System.out.println(name + " entered in method B.bar();");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("Class B Interrupted");
}
System.out.println(name + " entered in method A.last();");
a.last();
}
synchronized void last() {
System.out.println("Method B.last(); ");
}
}
class DeadLock implements Runnable {
A a = new A();
B b = new B();
DeadLock() {
Thread.currentThread().setName("Main Thread");
Thread tred = new Thread(this, "Rival Thread");
tred.start();
a.foo(b); // get lock for object A
// in this thread
System.out.println("Back to main thread");
}
@Override
public void run() {
b.bar(a);// get lock for object B
// in another thread
System.out.println("Back to another thread");
}
public static void main(String args[]) {
new DeadLock();
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapreduce.task.reduce;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalDirAllocator;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.mapred.Counters;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RawKeyValueIterator;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.Task;
import org.apache.hadoop.mapred.TaskStatus;
import org.apache.hadoop.mapred.TaskUmbilicalProtocol;
import org.apache.hadoop.mapred.Task.CombineOutputCollector;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.util.Progress;
@InterfaceAudience.Private
@InterfaceStability.Unstable
public class Shuffle<K, V> implements ExceptionReporter {
private static final Log LOG = LogFactory.getLog(Shuffle.class);
private static final int PROGRESS_FREQUENCY = 2000;
private final TaskAttemptID reduceId;
private final JobConf jobConf;
private final Reporter reporter;
private final ShuffleClientMetrics metrics;
private final TaskUmbilicalProtocol umbilical;
private final ShuffleScheduler<K,V> scheduler;
private final MergeManager<K, V> merger;
private Throwable throwable = null;
private String throwingThreadName = null;
private final Progress copyPhase;
private final TaskStatus taskStatus;
private final Task reduceTask; //Used for status updates
public Shuffle(TaskAttemptID reduceId, JobConf jobConf, FileSystem localFS,
TaskUmbilicalProtocol umbilical,
LocalDirAllocator localDirAllocator,
Reporter reporter,
CompressionCodec codec,
Class<? extends Reducer> combinerClass,
CombineOutputCollector<K,V> combineCollector,
Counters.Counter spilledRecordsCounter,
Counters.Counter reduceCombineInputCounter,
Counters.Counter shuffledMapsCounter,
Counters.Counter reduceShuffleBytes,
Counters.Counter failedShuffleCounter,
Counters.Counter mergedMapOutputsCounter,
TaskStatus status,
Progress copyPhase,
Progress mergePhase,
Task reduceTask) {
this.reduceId = reduceId;
this.jobConf = jobConf;
this.umbilical = umbilical;
this.reporter = reporter;
this.metrics = new ShuffleClientMetrics(reduceId, jobConf);
this.copyPhase = copyPhase;
this.taskStatus = status;
this.reduceTask = reduceTask;
scheduler =
new ShuffleScheduler<K,V>(jobConf, status, this, copyPhase,
shuffledMapsCounter,
reduceShuffleBytes, failedShuffleCounter);
merger = new MergeManager<K, V>(reduceId, jobConf, localFS,
localDirAllocator, reporter, codec,
combinerClass, combineCollector,
spilledRecordsCounter,
reduceCombineInputCounter,
mergedMapOutputsCounter,
this, mergePhase);
}
@SuppressWarnings("unchecked")
public RawKeyValueIterator run() throws IOException, InterruptedException {
// Start the map-completion events fetcher thread
final EventFetcher<K,V> eventFetcher =
new EventFetcher<K,V>(reduceId, umbilical, scheduler, this);
eventFetcher.start();
// Start the map-output fetcher threads
final int numFetchers = jobConf.getInt(MRJobConfig.SHUFFLE_PARALLEL_COPIES, 5);
Fetcher<K,V>[] fetchers = new Fetcher[numFetchers];
for (int i=0; i < numFetchers; ++i) {
fetchers[i] = new Fetcher<K,V>(jobConf, reduceId, scheduler, merger,
reporter, metrics, this,
reduceTask.getJobTokenSecret());
fetchers[i].start();
}
// Wait for shuffle to complete successfully
while (!scheduler.waitUntilDone(PROGRESS_FREQUENCY)) {
reporter.progress();
synchronized (this) {
if (throwable != null) {
throw new ShuffleError("error in shuffle in " + throwingThreadName,
throwable);
}
}
}
// Stop the event-fetcher thread
eventFetcher.interrupt();
try {
eventFetcher.join();
} catch(Throwable t) {
LOG.info("Failed to stop " + eventFetcher.getName(), t);
}
// Stop the map-output fetcher threads
for (Fetcher<K,V> fetcher : fetchers) {
fetcher.interrupt();
}
for (Fetcher<K,V> fetcher : fetchers) {
fetcher.join();
}
fetchers = null;
// stop the scheduler
scheduler.close();
copyPhase.complete(); // copy is already complete
taskStatus.setPhase(TaskStatus.Phase.SORT);
reduceTask.statusUpdate(umbilical);
// Finish the on-going merges...
RawKeyValueIterator kvIter = null;
try {
kvIter = merger.close();
} catch (Throwable e) {
throw new ShuffleError("Error while doing final merge " , e);
}
// Sanity check
synchronized (this) {
if (throwable != null) {
throw new ShuffleError("error in shuffle in " + throwingThreadName,
throwable);
}
}
return kvIter;
}
public synchronized void reportException(Throwable t) {
if (throwable == null) {
throwable = t;
throwingThreadName = Thread.currentThread().getName();
// Notify the scheduler so that the reporting thread finds the
// exception immediately.
synchronized (scheduler) {
scheduler.notifyAll();
}
}
}
public static class ShuffleError extends IOException {
private static final long serialVersionUID = 5753909320586607881L;
ShuffleError(String msg, Throwable t) {
super(msg, t);
}
}
}
|
package com.tencent.mm.ak;
import android.os.Looper;
import com.tencent.mm.a.e;
import com.tencent.mm.ak.a.a;
import com.tencent.mm.ak.g.3;
import com.tencent.mm.bt.h.d;
import com.tencent.mm.g.a.ov;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.ar;
import com.tencent.mm.model.p;
import com.tencent.mm.modelsfs.SFSContext;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.bd;
import java.util.HashMap;
public class o implements ar {
private static HashMap<Integer, d> cVM;
private b dWA = null;
private p dWB = null;
private c dWC = new c<ov>() {
{
this.sFo = ov.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
bd bdVar = ((ov) bVar).bZP.bGS;
i Pd = o.Pd();
e br = o.Pf().br(bdVar.field_msgId);
br.hJ(0);
o.Pf().a(Long.valueOf(br.dTK), br);
int i = br.ON() ? 1 : 0;
String o = o.Pf().o(br.dTL, "", "");
if (o == null || o.equals("") || !e.cn(o)) {
x.e("MicroMsg.ImgService", "sendMsgImage: filePath is null or empty");
} else {
ah.A(new i$6(Pd, br, i));
}
return false;
}
};
private a dWD = null;
private SFSContext dWE = null;
private SFSContext dWF = null;
private g dWu;
private i dWv;
private c dWw;
private j dWx = new j();
private d dWy = null;
private h dWz = new h();
private static synchronized o Pc() {
o oVar;
synchronized (o.class) {
oVar = (o) p.v(o.class);
}
return oVar;
}
public static i Pd() {
if (Pc().dWv == null) {
Pc().dWv = new i();
}
return Pc().dWv;
}
public static c Pe() {
g.Eg().Ds();
if (Pc().dWw == null) {
Pc().dWw = new c();
}
return Pc().dWw;
}
public static g Pf() {
g.Eg().Ds();
if (Pc().dWu == null) {
Pc().dWu = new g(g.Ei().dqq);
}
return Pc().dWu;
}
public static d Pg() {
g.Eg().Ds();
if (Pc().dWy == null) {
Pc().dWy = new d();
}
return Pc().dWy;
}
public static b Ph() {
g.Eg().Ds();
if (Pc().dWA == null) {
Pc().dWA = new b(Looper.getMainLooper());
}
return Pc().dWA;
}
public static p Pi() {
g.Eg().Ds();
if (Pc().dWB == null) {
Pc().dWB = new p();
}
return Pc().dWB;
}
public static a Pj() {
g.Eg().Ds();
if (Pc().dWD == null) {
Pc().dWD = a.Pq();
}
return Pc().dWD;
}
public static SFSContext Pk() {
return null;
}
public final void onAccountRelease() {
o Pc = Pc();
if (Pc.dWv != null) {
i iVar = Pc.dWv;
iVar.bFj = 0;
g.Eh().dpP.b(110, iVar);
}
if (Pc.dWA != null) {
b bVar = Pc.dWA;
synchronized (bVar.dTg) {
bVar.dTg.clear();
bVar.dTh = 0;
Pg().a(bVar);
}
com.tencent.mm.sdk.b.a.sFg.c(bVar.dTs);
com.tencent.mm.sdk.b.a.sFg.c(bVar.dTt);
}
if (Pc.dWy != null) {
d dVar = Pc.dWy;
x.i("ModelImage.DownloadImgService", "on detach");
x.i("ModelImage.DownloadImgService", "cancel all net scene");
dVar.dTC = true;
dVar.b(dVar.dTA);
while (dVar.dTy.size() > 0) {
dVar.b((d$b) dVar.dTy.get(0));
}
dVar.OL();
g.Eh().dpP.b(109, dVar);
}
if (Pc.dWB != null) {
p pVar = Pc.dWB;
x.i("MicroMsg.UrlImageCacheService", "detach");
pVar.dWH.clear();
pVar.dWJ = true;
}
Pl();
com.tencent.mm.ab.d.c.b(Integer.valueOf(3), this.dWz);
com.tencent.mm.ab.d.c.b(Integer.valueOf(23), this.dWz);
com.tencent.mm.cache.e.a.a("local_cdn_img_cache", null);
com.tencent.mm.sdk.b.a.sFg.c(this.dWC);
if (Pc.dWD != null) {
Pc.dWD.detach();
Pc.dWD = null;
}
if (Pc.dWE != null) {
Pc.dWE.release();
Pc.dWE = null;
}
if (Pc.dWF != null) {
Pc.dWF.release();
Pc.dWF = null;
}
}
public static void Pl() {
g gVar = Pc().dWu;
if (gVar != null) {
x.i("MicroMsg.ImgInfoStorage", "clearCacheMap stack:%s", new Object[]{bi.cjd()});
gVar.dUr.a(new 3(gVar));
}
a aVar = Pc().dWD;
if (aVar != null) {
aVar.detach();
}
}
static {
HashMap hashMap = new HashMap();
cVM = hashMap;
hashMap.put(Integer.valueOf("IMGINFO_TABLE".hashCode()), new 2());
}
public final HashMap<Integer, d> Ci() {
return cVM;
}
public final void gi(int i) {
}
public final void bn(boolean z) {
com.tencent.mm.ab.d.c.a(Integer.valueOf(3), this.dWz);
com.tencent.mm.ab.d.c.a(Integer.valueOf(23), this.dWz);
com.tencent.mm.cache.e.a.a("local_cdn_img_cache", this.dWx);
com.tencent.mm.sdk.b.a.sFg.b(this.dWC);
}
public final void bo(boolean z) {
}
}
|
/*
* 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 usuarios;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Administrator
*/
public class UsuarioTest {
@Test
public void user(){
Usuario user = new Usuario();
user.setNombre("Pedro");
assertEquals("Pedro",user.getNombre());
}
@Test
public void testConstructor(){
Usuario usr = new Usuario();
}
@Test
public void testReservar(){
}
}
|
package com.kafkatestserver.kafkatestserver;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class KafkaTestServerApplicationTests {
@Test
void contextLoads() {
}
}
|
package com.duanxr.yith.easy;
/**
* @author 段然 2021/5/26
*/
public class NumberOfRectanglesThatCanFormTheLargestSquare {
/**
* You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi.
*
* You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4.
*
* Let maxLen be the side length of the largest square you can obtain from any of the given rectangles.
*
* Return the number of rectangles that can make a square with a side length of maxLen.
*
*
*
* Example 1:
*
* Input: rectangles = [[5,8],[3,9],[5,12],[16,5]]
* Output: 3
* Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5].
* The largest possible square is of length 5, and you can get it out of 3 rectangles.
* Example 2:
*
* Input: rectangles = [[2,3],[3,7],[4,3],[3,7]]
* Output: 3
*
*
* Constraints:
*
* 1 <= rectangles.length <= 1000
* rectangles[i].length == 2
* 1 <= li, wi <= 109
* li != wi
*
* 给你一个数组 rectangles ,其中 rectangles[i] = [li, wi] 表示第 i 个矩形的长度为 li 、宽度为 wi 。
*
* 如果存在 k 同时满足 k <= li 和 k <= wi ,就可以将第 i 个矩形切成边长为 k 的正方形。例如,矩形 [4,6] 可以切成边长最大为 4 的正方形。
*
* 设 maxLen 为可以从矩形数组 rectangles 切分得到的 最大正方形 的边长。
*
* 请你统计有多少个矩形能够切出边长为 maxLen 的正方形,并返回矩形 数目 。
*
*
*
* 示例 1:
*
* 输入:rectangles = [[5,8],[3,9],[5,12],[16,5]]
* 输出:3
* 解释:能从每个矩形中切出的最大正方形边长分别是 [5,3,5,5] 。
* 最大正方形的边长为 5 ,可以由 3 个矩形切分得到。
* 示例 2:
*
* 输入:rectangles = [[2,3],[3,7],[4,3],[3,7]]
* 输出:3
*
*
* 提示:
*
* 1 <= rectangles.length <= 1000
* rectangles[i].length == 2
* 1 <= li, wi <= 109
* li != wi
*
*/
class Solution {
public int countGoodRectangles(int[][] rectangles) {
int maxLen = 0;
int count = 0;
for (int[] rect : rectangles) {
int cLen = Math.min(rect[0], rect[1]);
if (cLen == maxLen) {
count++;
} else if (cLen > maxLen) {
maxLen = cLen;
count = 1;
}
}
return count;
}
}
}
|
package LightProcessing.common.lib;
import java.awt.Event;
import java.util.ArrayList;
import java.util.Random;
import LightProcessing.common.block.BlockLightTreeSapling;
import net.minecraft.block.Block;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.entity.player.BonemealEvent;
public class Events {
@ForgeSubscribe
public void bonemealUsed(BonemealEvent event) {
if (event.world.getBlockId(event.X, event.Y, event.Z) == LPBlocks.BlockLightTreeSapling.blockID) {
((BlockLightTreeSapling)LPBlocks.BlockLightTreeSapling).growTree(event.world, event.X, event.Y, event.Z, event.world.rand);
}
}
} |
package intergratingdefaultmethods;
import java.util.Comparator;
public class SortByRankThenSuit implements Comparator<Card> {
@Override
public int compare(Card o1, Card o2) {
int comVal = o1.getRank().value() - o2.getRank().value();
if(comVal !=0) return comVal;
else return o1.getSuit().value() - o2.getSuit().value();
}
public static void main(String[] args) {
StandardDeck standardDeck = new StandardDeck();
standardDeck.shuffle();
standardDeck.sort((o1,o2)->o1.getRank().value() - o2.getRank().value());
standardDeck.sort(Comparator.comparing((card -> card.getRank())));
standardDeck.sort(Comparator.comparing(Card::getRank));
standardDeck.sort((firstCard,secondCard)->{
int compare = firstCard.getRank().value() - secondCard.getRank().value();
if(compare !=0) return compare;
else return firstCard.getSuit().value() - secondCard.getSuit().value();
});
standardDeck.sort(
Comparator.comparing(Card::getRank).thenComparing(Comparator.comparing(Card::getSuit)));
//sort the deck of playing cards first by descending order of rank
standardDeck.sort(Comparator.comparing((Card::getRank)).reversed().thenComparing(Comparator.comparing(Card::getSuit)));
}
}
|
package solution;
import domain.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
/**
* User: jieyu
* Date: 12/4/16.
*/
public class CountCompleteTreeNodes222 {
public int countNodes(TreeNode root) {
if (root == null) return 0;
int lLevel = 1, rLevel = 1;
TreeNode lp = root.left, rp = root.right;
while(lp != null) {
lp = lp.left;
lLevel++;
if (rp != null) {
rp = rp.right;
rLevel++;
}
}
if (lLevel != 1 && lLevel == rLevel) return (1 << lLevel) - 1;
else {
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
public int countNodes2(TreeNode root) {
int level = searchLeft(root);
return count(root, level);
}
private int count(TreeNode root, int levelNum) {
if (root == null) return 0;
int count = 1;
int level = levelNum - 1;
int midLevel = searchLeft(root.right);
if (level == midLevel) {
count += (1 << level) - 1;
count += count(root.right, midLevel);
} else {
count += (1 << midLevel) - 1;
count += count(root.left, level);
}
return count;
}
private int searchLeft(TreeNode root) {
int level = 0;
TreeNode p = root;
while (p != null) {
p = p.left;
level++;
}
return level;
}
}
|
/**
* Using string class return a string if it starts with "not" as unchanged
* @author prathyusha
*
*/
public class String1
{
private String s1;
private String s2;
public String getS1()
{
return s1;
}
public void setS1(String s1)
{
this.s1 = s1;
}
public String getS2()
{
return s2;
}
public void setS2(String s2)
{
this.s2 = s2;
}
// using notString method return true if string starts with not
public String notString(String s1)
{
if (s1.equals("not"))
{
return s1;
}
else
{
return s2;
}
}
public String startingStr(String s1)
{
if (s1.startsWith("not"))
{
return s1;
}
else
{
return s2;
}
}
}
|
package com.example.suneel.dboperations.database;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by suneel on 2/14/2018.
*/
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="skdatabase.db";
Context context;
private static String dbPath = "/data/data/com.example.suneel.dboperations.database/databases/";
private static DBHelper dbInstance=null;
private SQLiteDatabase db;
public DBHelper(Context context) {
super(context, DATABASE_NAME,null, 1);
this.context=context;
}
public static DBHelper getInstance(Context ctx) {
if (dbInstance == null) {
dbInstance = new DBHelper(ctx.getApplicationContext());
try {
dbInstance.createDataBase();
dbInstance.openDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return dbInstance;
}
public void createDataBase() throws IOException {
if (!checkDataBase()) {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
public void openDataBase() throws SQLException, IOException {
String fullDbPath = dbPath + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(fullDbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
private boolean checkDataBase() {
File dbFile = new File(dbPath + DATABASE_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
try {
InputStream input = context.getAssets().open(DATABASE_NAME);
String outPutFileName = dbPath + DATABASE_NAME;
OutputStream output = new FileOutputStream(outPutFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
Log.v("error", e.toString());
}
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
|
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/*
* シリアライズのサンプル
*/
public class Write {
/**
* @param args
*/
public static void main(String[] args) {
try{
Person a2c = new Person("Atsushi","Wada", 35);
Person alan = new Person("Alan","Teruyama", 6);
alan.setParent(a2c);
System.out.println(a2c.getAge());
System.out.println(a2c.getFirstName());
Person who = (Person) alan.clone();
who.getParent().setAge(40);
System.out.println(who.getParent().getAge());
System.out.println(alan.getParent().getAge());
FileOutputStream fos = new FileOutputStream("alan.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(alan);
oos.close();
FileInputStream fis = new FileInputStream("alan.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Person read = (Person) ois.readObject(); //シリアライズしてでシリアライズしたものは完全に別のインスタンスがコピーされると考えてよい。つまり、前のインスタンスが参照していた値もコピーされる(ディープコピー)
System.out.println("read : "+read.getParent().getAge());
System.out.println("who : "+who.getParent().getAge());
System.out.println("alan : "+alan.getParent().getAge());
read.getParent().setAge(80);
System.out.println("and changed parent's age -----");
System.out.println("read : "+read.getParent().getAge());
System.out.println("who : "+who.getParent().getAge());
System.out.println("alan : "+alan.getParent().getAge());
}catch(Exception e){
System.out.println("miss!"+ e);
}
System.out.println("success!!");
}
}
|
package com.deltastuido.shared;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;
import javax.ejb.Singleton;
import javax.enterprise.inject.Produces;
import javax.inject.Named;
@Singleton
public class IdGenerator {
private static final int MAX_VARIANT = 1_000_000;
private static AtomicInteger atomic = new AtomicInteger();
private static DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern("YYYYMMddHHmmss");
public String generateId(String prefix) {
return prefix + "-" + generateId();
}
@Produces
@Named("id")
public String generateId() {
LocalDateTime now = LocalDateTime.now();
String id1 = now.format(datetimeFormatter);
IntUnaryOperator updateFunction = (int i) -> {
if (i >= MAX_VARIANT) {
return 0;
}
return i + 1;
};
return String.format("%s%06d", id1, atomic.updateAndGet(updateFunction));
}
private static final int maxVariant_refund = 1_000_000;
private static AtomicInteger atomic_refund = new AtomicInteger();
private static DateTimeFormatter datetimeFormatter_refund = DateTimeFormatter.ofPattern("YYYYMMddHHmmss");
public String refundGenerateId(int alias) {
LocalDateTime now = LocalDateTime.now();
String id1 = now.format(datetimeFormatter_refund);
IntUnaryOperator updateFunction = (int i) -> {
if (i >= maxVariant_refund) {
return 0;
}
return i + 1;
};
return String.format("%s%02d%08d", id1, alias,atomic_refund.updateAndGet(updateFunction));
}
public static void main(String[] args) {
IdGenerator idGenerator = new IdGenerator();
for(int i=0;i<10000;i++)
System.out.println(idGenerator.refundGenerateId(1));
}
}
|
package com.takshine.wxcrm.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.takshine.core.service.CRMService;
import com.takshine.wxcrm.domain.Messages;
import com.takshine.wxcrm.message.tplmsg.ValColor;
import com.takshine.wxcrm.service.TemplateMsgService;
/**
* 模板消息 页面控制器
*
* @author [liulin Date:2014-01-10]
*
*/
@Controller
@RequestMapping("/tplmsg")
public class TemplateMsgController {
// 日志
protected static Logger logger = Logger.getLogger(TemplateMsgController.class.getName());
@Autowired
@Qualifier("cRMService")
private CRMService cRMService;
/**
* 发送 消息
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/send")
@ResponseBody
public String send(Messages msg, HttpServletRequest request,
HttpServletResponse response) throws Exception {
//发送参数
String openId = "on478t5q-IsPn-KcWs5G7FEGqi2Q";// on478tyhwR3fkCAOQpd6lT0rUjxc
String topcolor = "#00DB00";
String url = "http://www.takshine.com";
//日程任务
Map<String, ValColor> map = new HashMap<String, ValColor>();
map.put("first", new ValColor("您好,请留意日历事件:","#4A4AFF"));//标题值
map.put("schedule", new ValColor("准备每月的总结","#4A4AFF"));//事件值
map.put("time", new ValColor("每月30日","#FF0000"));//时间值
map.put("remark", new ValColor("明天8:00将再次提醒。","#4A4AFF"));//备注值
//发送消息
JSONObject rst = cRMService.getDbService().getTemplateMsgService().sendScheduleMsg(openId, topcolor, url, map);
logger.info(rst.getString("errcode"));
//审批结果
map.clear();
map.put("first", new ValColor("彭总,您好:","#4A4AFF"));//标题值
map.put("keyword1", new ValColor("『银电网络智能监控系统』项目差旅费报销,金额为¥215元整。","#4A4AFF"));//审批事项
map.put("keyword2", new ValColor("通过","#FF0000"));//审批结果
map.put("remark", new ValColor("2014/8/25 10:12:22","#4A4AFF"));//备注值
//发送消息
rst = cRMService.getDbService().getTemplateMsgService().sendApproveMsg(openId, topcolor, url, map);
logger.info(rst.getString("errcode"));
//待办工作任务
map.clear();
map.put("first", new ValColor("你好,你还有3项待办工作。","#4A4AFF"));//标题值
map.put("work", new ValColor("客户生日关怀、客户保险到期等3项工作","#4A4AFF"));//待办工作
map.put("remark", new ValColor("请按时完成待办工作。","#4A4AFF"));//备注值
//发送消息
rst = cRMService.getDbService().getTemplateMsgService().sendToDoWorkMsg(openId, topcolor, url, map);
logger.info(rst.getString("errcode"));
return "success";
}
}
|
package com.dahua.design.structural.proxy.jdkdynamic;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKDynamicProxy<T> implements InvocationHandler{
private T target;
public JDKDynamicProxy(T target) {
this.target = target;
}
public static <T> T getProxy(T t){
/**
* ClassLoader loader,
* Class<?>[] interfaces,
* InvocationHandler h
*/
Object proxyInstance = Proxy.newProxyInstance(t.getClass().getClassLoader(),
t.getClass().getInterfaces(),
new JDKDynamicProxy(t));
return (T)proxyInstance;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("开始JDK动态代理啦啦啦啦");
Object returnString = method.invoke(target, args);
return returnString;
}
}
|
package LambdaExpressions.Introduction;
class AnotherClass {
String doSomething() {
UpperConcat uc = (s1, s2) -> {
System.out.println("The lambda expression's class is: " + getClass().getSimpleName());
String result = s1.toUpperCase() + " " + s2.toUpperCase();
return result;
};
System.out.println("The AnotherClass class's name is: " + getClass().getSimpleName());
return Main.doStringStuff(uc, "String1", "String2");
}
} |
package com.mantisclaw.italianpride15.ridesharehome;
import com.parse.ParseObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by italianpride15 on 2/23/15.
*/
public class ServiceAvailability {
public Map<String, ParseObject> rideShareDictionary;
public Integer numberOfAvailableServices;
public ServiceAvailability(List<ParseObject> rideShareList) {
rideShareDictionary = new HashMap<>();
for (ParseObject object : rideShareList) {
rideShareDictionary.put(object.getString("ServiceName"), object);
}
numberOfAvailableServices = rideShareList.size();
}
}
|
import java.io.IOException;
import java.net.URL;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.RefreshHandler;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class YahooLogin {
public static String doLogin(String strURI) throws Exception {
// Create and initialize WebClient object
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3);
webClient.setThrowExceptionOnScriptError(false);
webClient.setRefreshHandler(new RefreshHandler() {
public void handleRefresh(Page page, URL url, int arg) throws IOException {
System.out.println("handleRefresh");
}
});
// visit Yahoo Mail login page and get the Form object
HtmlPage page = (HtmlPage) webClient.getPage(strURI);
HtmlForm form = page.getFormByName("login_form");
// Enter login and passwd
form.getInputByName("login").setValueAttribute("ferreyraru");
form.getInputByName("passwd").setValueAttribute("udemmudemm");
page = (HtmlPage) form.getButtonByName(".save").click();
HtmlForm form_autorize = page.getFormByName("authorize");
page = (HtmlPage) form_autorize.getButtonByName("commit").click();
HtmlElement elem = (HtmlElement) page.getElementById("oauth_verifier");
String code = elem.asText();
webClient.closeAllWindows();
return code;
}
}
|
/*
* ProductAddInterFrm.java
*
* Created on __DATE__, __TIME__
*/
package com.view;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import com.dao.ProductDao;
import com.dao.ProductTypeDao;
import com.model.Product;
import com.model.ProductType;
import com.util.Dbutil;
import com.util.StringUtil;
/**
*
* @author __USER__
*/
public class ProductAddInterFrm extends javax.swing.JInternalFrame {
Dbutil dbutil = new Dbutil();
ProductTypeDao productTypeDao = new ProductTypeDao();
ProductDao productDao = new ProductDao();
/** Creates new form ProductAddInterFrm */
public ProductAddInterFrm() {
initComponents();
this.setLocation(200, 50);
this.fillProductType();
if (this.jcb_ProductType.getItemCount() > 0) {
this.jcb_ProductType.setSelectedIndex(0);
}
}
private void fillProductType() {
Connection con = null;
ProductType productType = null;
try {
con = dbutil.getCon();
ResultSet rs = productTypeDao.productTypeList(con,
new ProductType());
while (rs.next()) {
productType = new ProductType();
productType.setId(rs.getInt("id"));
productType.setProductTypeName(rs.getString("productTypeName"));
this.jcb_ProductType.addItem(productType);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
dbutil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/** 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.
*/
//GEN-BEGIN:initComponents
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
productNameTxt = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
productTimeTxt = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
priceTxt = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jcb_ProductType = new javax.swing.JComboBox();
jLabel5 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
productDescTxt = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setClosable(true);
setIconifiable(true);
setTitle("\u5546\u54c1\u6dfb\u52a0");
jLabel1.setText("\u5546\u54c1\u540d\u79f0");
jLabel2.setText("\u751f\u4ea7\u65e5\u671f");
jLabel3.setText("\u4ef7\u683c");
jLabel4.setText("\u5546\u54c1\u7c7b\u522b");
jLabel5.setText("\u5546\u54c1\u63cf\u8ff0");
productDescTxt.setColumns(20);
productDescTxt.setRows(5);
jScrollPane1.setViewportView(productDescTxt);
jButton1.setIcon(new javax.swing.ImageIcon("./images\\add.png")); // NOI18N
jButton1.setText("\u6dfb\u52a0");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setIcon(new javax.swing.ImageIcon("./images\\reset.png")); // NOI18N
jButton2.setText("\u91cd\u7f6e");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(27, 27, 27)
.addComponent(jcb_ProductType, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 221, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(90, 90, 90)))
.addGap(90, 90, 90))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(147, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel3))
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(priceTxt, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)
.addComponent(productNameTxt, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(59, 59, 59)
.addComponent(jLabel2)
.addGap(38, 38, 38)
.addComponent(productTimeTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(75, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(productTimeTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(productNameTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(priceTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jcb_ProductType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(43, 43, 43))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap())))
);
pack();
}// </editor-fold>
//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String productName = this.productNameTxt.getText();
String productTime = this.productTimeTxt.getText();
String price = this.priceTxt.getText();
String productDesc = this.productDescTxt.getText();
if (StringUtil.isEmpty(productName)) {
JOptionPane.showMessageDialog(null, " 商品名称不能为空!");
return;
}
if (StringUtil.isEmpty(productTime)) {
JOptionPane.showMessageDialog(null, " 生产日期不能为空!");
return;
}
if (StringUtil.isEmpty(price)) {
JOptionPane.showMessageDialog(null, " 价钱不能为空!");
return;
}
ProductType productType = (ProductType) this.jcb_ProductType
.getSelectedItem();
int productTypeId = productType.getId();
Product product = new Product(productName, productTime, Float
.parseFloat(price), productDesc, productTypeId);
Connection con = null;
try {
con = dbutil.getCon();
int addNum = productDao.productAdd(con, product);
if (addNum == 1) {
JOptionPane.showMessageDialog(null, "商品添加成功");
this.resetValue();
} else {
JOptionPane.showMessageDialog(null, "商品添加失败");
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "商品添加失败");
} finally {
try {
dbutil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
this.resetValue();
}
private void resetValue() {
this.productNameTxt.setText("");
this.productTimeTxt.setText("");
this.priceTxt.setText("");
if (this.jcb_ProductType.getItemCount() > 0) {
this.jcb_ProductType.setSelectedIndex(0);
}
this.productDescTxt.setText("");
}
//GEN-BEGIN:variables
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JComboBox jcb_ProductType;
private javax.swing.JTextField priceTxt;
private javax.swing.JTextArea productDescTxt;
private javax.swing.JTextField productNameTxt;
private javax.swing.JTextField productTimeTxt;
// End of variables declaration//GEN-END:variables
} |
package br.com.jadechatbot.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.jadechatbot.beans.Usuario;
import br.com.jadechatbot.bo.ValidacaoCadastro;
import br.com.jadechatbot.dao.CadastroDAO;
/**
* Servlet que efetuara o cadastro do usuario
* passndo por todas as regras da BO e de validação feitas no client.
* @author rm83220
*/
@WebServlet("/CadastroServlet")
public class CadastroServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CadastroServlet() throws Exception {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String strNmUsuario = request.getParameter("nm_usuario");
String strTxEmail = request.getParameter("tx_email");
String strNrTelefone = request.getParameter("nr_telefone");
String strDtNasc = request.getParameter("dt_nasc");
String strTxSenha = request.getParameter("tx_senha");
String strTxSenha2 = request.getParameter("tx_senha2");
char strNrNivelAcesso = '1';
String strbTurmaCdTurma = request.getParameter("tb_turma_cd_turma");
ValidacaoCadastro bo = new ValidacaoCadastro();
Usuario usuario = null;
try {
CadastroDAO cadastroDAO = new CadastroDAO();
if (cadastroDAO.selectVerificacaoEmail(strTxEmail) == true) {
request.setAttribute("error", "Email já cadastrado, tente novamente");
request.getRequestDispatcher("/cadastro.jsp").forward(request, response);
} else {
usuario = new Usuario(strNmUsuario, strTxEmail, strNrTelefone, strDtNasc,
bo.validacaoSenhas(strTxSenha, strTxSenha2), strNrNivelAcesso, bo.codTurma(strbTurmaCdTurma));
cadastroDAO.cadastroUsuario(usuario);
request.setAttribute("userName", usuario.getNmUsuario());
request.getRequestDispatcher("/cadastro-sucesso.jsp").forward(request, response);
}
} catch (Exception e1) {
request.setAttribute("error", "Cadastro invalido tente novamente");
request.getRequestDispatcher("/cadastro.jsp").forward(request, response);
}
}
}
|
package arrays;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int bigCapacity = 1_000_000;
MyArrayList<Integer> malForBubble = new MyArrayList<>();
MyArrayList<Integer> malForSelection = new MyArrayList<>();
MyArrayList<Integer> malForInsertion = new MyArrayList<>();
for (int i = 0; i < bigCapacity; i++) {
malForBubble.add(rand.nextInt(bigCapacity));
malForSelection.add(rand.nextInt(bigCapacity));
malForInsertion.add(rand.nextInt(bigCapacity));
}
long bubbleSortTime = System.currentTimeMillis();
malForBubble.bubbleSort();
System.out.println("Bubble sort: " + (System.currentTimeMillis() - bubbleSortTime));
long selectionSortTime = System.currentTimeMillis();
malForSelection.selectionSort();
System.out.println("Selection sort: " + (System.currentTimeMillis() - selectionSortTime));
long insertionSortTime = System.currentTimeMillis();
malForInsertion.insertionSort();
System.out.println("Insertion sort: " + (System.currentTimeMillis() - insertionSortTime));
}
}
|
package jneiva.hexbattle.unidade;
import jneiva.hexbattle.componente.Vida;
public interface ISelecionavel {
public Vida getVida();
}
|
package com.github.bobby.base;
//: polymorphism/PolyConstructors.java
//Constructors and polymorphism
//don��t produce what you might expect.
import static net.mindview.util.Print.*;
class Glyph {
private static String baseStr = "static String field";
static {
System.out.println("baseStr = " + baseStr);
System.out.println("Glyph.enclosing_method(static)");
}
{
System.out.println("Glyph.enclosing_method(noraml)");
}
Glyph() {
print("Glyph() before draw()");
draw();
print("Glyph() after draw()");
}
void draw() {
print("Glyph.draw()");
}
}
class RoundGlyph extends Glyph {
private int radius = 1;
private Glyph glyph = new Glyph();
static {
System.out.println("RoundGlyph.enclosing_method(static)");
}
{
System.out.println("RoundGlyph.enclosing_method(noraml)");
System.out.println(" radius = " + radius);
System.out.println("new glyph() = " + glyph);
}
RoundGlyph(int r) {
radius = r;
print("RoundGlyph.RoundGlyph(), radius = " + radius);
}
void draw() {
print("RoundGlyph.draw(), radius = " + radius);
}
}
public class PolyConstructors {
public static void main(String[] args) {
new RoundGlyph(5);
}
}
|
package cq._13_Reflection.Field;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import org.junit.Test;
import cq._13_Reflection.TestReflection.Person;
public class TestField {
/**
* 获取属性
* @throws NoSuchFieldException
* @throws SecurityException
*
*/
@Test
public void testField() throws Exception{
Class<Person> clazz = Person.class;
//1.getFields()
//获取运行时类 及其父类的public属性
Field[] fields = clazz.getFields();
for(int i=0; i<fields.length; i++){
System.out.println("本类及其父类的属性:"+fields[i]);
}
System.out.println("-------------------------");
//2.获取该类本身的属性
Field[] fieldSelf = clazz.getDeclaredFields();
for(Field f:fieldSelf){
System.out.println("本类的属性:"+f);
System.out.println("属性的名字:"+f.getName());
//3获取每个属性的权限修饰符
int mod = f.getModifiers();
String mdfStr = Modifier.toString(mod);
System.out.println("权限修饰符:"+mdfStr);
//4.获取属性的类型
Class type = f.getType();
System.out.println("属性的类型:"+type.getName());
System.out.println("");
}
//5获取本类的特定属性
//getField(String fieldName):获取运行时类中声明为public的指定属性名为fieldName的属性
Field age = clazz.getField("age");
System.out.println("-------------------");
System.out.println(age);
//由于属性权限修饰符的限制,为了保证可以给属性赋值,
//需要在操作前使得此属性可被操作。
age.setAccessible(true);
//6运行时赋值
Person p = clazz.newInstance();
System.out.println("p:"+p);
//
age.set(p, 16);
System.out.println("p2:"+p);
System.out.println(age.get(p));
}
}
|
package com.company.c4q.whiteboardingexcercises;
/**
* Given a string, take the last char and return a new string with the last char added at the front and back, so "cat" yields "tcatt". The original string will be length 1 or more.
*/
public class ModifyCharsInString {
public static void main(String[] args) {
System.out.println(modify("cat"));
}
static String modify(String s) {
StringBuilder sb = new StringBuilder(s);
sb.insert(0, s.charAt(s.length() - 1)).append(s.charAt(s.length() - 1));
return sb.toString();
}
}
|
package stepDefinition;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import pageObjects.HorizontalSliderPage;
import utils.TestContext;
import static org.testng.Assert.*;
public class HorizontalSliderSteps
{
private TestContext testContext;
private HorizontalSliderPage sliderPage;
public HorizontalSliderSteps(TestContext context)
{
testContext = context;
sliderPage = testContext.getPageObjectManager().getHorizontalSliderPage();
}
@When("^the user moves the slider to position \"([^\"]*)\"$")
public void theUserMovesTheSliderToPosition(String position)
{
sliderPage.setSliderValue(position);
}
@Then("^the page displays the slider was moved to position \"([^\"]*)\"$")
public void thePageDisplaysTheSliderWasMovedToPosition(String position)
{
assertEquals(sliderPage.getSliderValue(), position, "Value incorrect");
}
}
|
package fr.lteconsulting;
public class Magic
{
public static void main( String[] args )
{
Jeu maMain = new Jeu( 10 );
maMain.piocher( new Terrain( Couleur.Bleu ) );
maMain.piocher( new Creature( 6, "Golem", 4, 6 ) );
maMain.piocher( new Sortilege( 1, "Croissance Gigantesque", "La créature ciblée gagne +3/+3 jusqu'à la fin du tour" ) );
System.out.println( "Là, j'ai en stock :" );
maMain.afficher();
maMain.joue();
}
}
|
package com.xu.easyweb.util.extjs.filter;
import com.xu.easyweb.util.annotation.Invisible;
import org.apache.commons.lang.StringUtils;
import java.lang.reflect.Method;
/**
* Created with IntelliJ IDEA.
* User: zht
* Date: 12-8-23
* Time: 下午6:32
* To change this template use File | Settings | File Templates.
*/
public class InvisibleFilter extends AbstractMethodFilter {
private String prohibit;
public InvisibleFilter(final String prohibit) {
this.prohibit = prohibit;
}
public InvisibleFilter() {
}
public boolean apply(final Method method) {
if (method.isAnnotationPresent(Invisible.class)) {
Invisible anno = method.getAnnotation(Invisible.class);
String[] value = anno.value();
if(value != null && value.length > 0) {
for (int i = 0; i < value.length; i++) {
if (!StringUtils.isEmpty(prohibit) && prohibit.equals(value[i])) {
return true;
}
}
} else{
return true;
}
}
return false;
}
}
|
package com.jincarry.db;
import com.jincarry.entity.TaskLog;
import com.jincarry.entity.Vis;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.*;
/**
* Created by jincarry on 16-9-23.
*/
public class BasicStoreTest {
@Test
public void getVisList() throws Exception {
}
@Test
public void initRecord() throws Exception {
}
@Test
public void updateRecord() throws Exception {
// 51
Vis vis = new Vis();
vis.setVid("1329");
vis.setUsername("gzife_20132205041027");
vis.setAfter_answer_state(3);
vis.setLength(999);
vis.setState(0);
vis.setAnswer_state(666);
BasicStore.updateRecord(vis);
}
@Test
public void getRestVisList(){
List<Vis> vises = BasicStore.getRestVisList("gzife_20132205041027");
System.out.println(vises.iterator().next().getName());
}
@Test
public void initLogger(){
TaskLog taskLog = new TaskLog();
taskLog.setUsername("ggg");
taskLog.setPassword("123456");
taskLog.setRest(999);
}
@Test
public void updateLogger(){
TaskLog taskLog = new TaskLog();
taskLog.setUsername("ggg");
taskLog.setRest(0);
}
} |
import java.time.DayOfWeek;
public class Belegung {
private int unterrichtsEinheit;
private Raum raum;
private Lehrer lehrer;
private Fach fach;
private DayOfWeek wochentag;
public Belegung(int unterrichtsEinheit){
this.unterrichtsEinheit = unterrichtsEinheit;
}
public Belegung(DayOfWeek wochentag, int unterrichtsEinheit){
this.wochentag = wochentag;
this.unterrichtsEinheit = unterrichtsEinheit;
}
public Lehrer getLehrer(){
return lehrer;
}
public Klasse getKlasse() {
return raum.getKlasse();
}
public DayOfWeek getWochentag(){
return wochentag;
}
public int getUnterrichtsEinheit(){
return unterrichtsEinheit;
}
public Fach getFach() {
return fach;
}
public Raum getRaum() {
return raum;
}
} |
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
class TakeBlackPointsFromImage extends JPanel {
private static String image;
private static final long serialVersionUID = 1L;
private Color imgColor = Color.BLACK;
private static int SHADE = 190;
public static BufferedImage readImage(String fileLocation) {
BufferedImage img = null;
try {
img = ImageIO.read(new File(fileLocation));
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
public static int takeNumberOfDesiredPixels(){
BufferedImage image22 = readImage(image);
image22 = toBlackAndWhite(image22);
int numOfPix = 0;
int width = image22.getWidth();
int height = image22.getHeight();
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int pixel = image22.getRGB(i, j);
int red = (pixel >> 16) & 0x000000FF;
int green = (pixel >> 8) & 0x000000FF;
int blue = (pixel) & 0x000000FF;
for (int p=0;p<SHADE;p++){
if (red == p && green == p && blue == p) {
numOfPix++;
}
}
}
}
return numOfPix;
}
public static int[] getXCoordinates() {
BufferedImage image22 = readImage(image);
image22 = toBlackAndWhite(image22);
int width = image22.getWidth();
int height = image22.getHeight();
int[] ArrayX = new int[takeNumberOfDesiredPixels()];
int d = -1;
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
int pixel = image22.getRGB(w, h);
int red = (pixel >> 16) & 0x000000FF;
/**
* Shift all bits to the right as 16 bit
* then multiply or sth like filter with
* 0x000000FF then get the only last 8 bit
* which is the red information
* between 0 and 255
* **/
int green = (pixel >> 8) & 0x000000FF;
/**
* Shift all bits to the rigt as 8 bit
* then multiply or sth like filter with
* 0x000000FF then get the only last 8 bit
* which is the green information
* between 0 and 255
* **/
int blue = (pixel) & 0x000000FF;
/**
* multiply or sth like filter with
* 0x000000FF then get the only last 8 bit
* which is the blue information
* between 0 and 255
* **/
for (int i=0;i<SHADE;i++){
if (red == i && green == i && blue == i) {
d++;
ArrayX[d] = w;
}
}
}
}
return ArrayX;
}
public static int[] getYCoordinates() {
BufferedImage image22 = readImage(image);
image22 = toBlackAndWhite(image22);
int width = image22.getWidth();
int height = image22.getHeight();
int[] ArrayY = new int[takeNumberOfDesiredPixels()];
int d = -1;
//stack overflow helped here :)
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
int pixel = image22.getRGB(w, h);
int red = (pixel >> 16) & 0x000000FF;
int green = (pixel >> 8) & 0x000000FF;
int blue = (pixel) & 0x000000FF;
for (int i=0;i<SHADE;i++){
if (red == i && green == i && blue == i) {
d++;
ArrayY[d] = h;
}
}
}
}
return ArrayY;
}
@Override
protected void paintComponent(Graphics g) {
int c[] =getXCoordinates();
int a = c.length;
int d[] =getYCoordinates();
g.setColor(imgColor);
for (int y = 0; y < a; y++) {
g.drawLine(c[y],d[y],c[y],d[y]);
}
}
public void changeColor(Color col){
imgColor = col;
}
public void changeShade(int num){
SHADE = num;
}
public void changeImg(String img){
image = img;
}
//converts to greyscale
private static BufferedImage toBlackAndWhite(BufferedImage image){
try {
int width = image.getWidth();
int height = image.getHeight();
for(int i=0; i<height; i++){
for(int j=0; j<width; j++){
Color c = new Color(image.getRGB(j, i));
int red = (int)(c.getRed() * 0.299);
int green = (int)(c.getGreen() * 0.587);
int blue = (int)(c.getBlue() *0.114);
Color newColor = new Color(red+green+blue,
red+green+blue,red+green+blue);
image.setRGB(j,i,newColor.getRGB());
}
}
return image;
} catch (Exception e) {}
return image;
}
} |
package com.redhat.vizuri.insurance;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Claim implements Serializable {
private static final long serialVersionUID = 8817532564043280353L;
private String id;
private long processId;
private Incident incident;
private Customer customer;
private List<Questionnaire> questionnaires = new ArrayList<Questionnaire>();
private List<Photo> photos = new ArrayList<Photo>();
private boolean approved;
private Double statedValue = 0d;
private Double adjustedValue = 0d;
private List<Comment> comments = new ArrayList<Comment>();
public Claim() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Incident getIncident() {
return incident;
}
public void setIncident(Incident incident) {
this.incident = incident;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<Questionnaire> getQuestionnaires() {
return questionnaires;
}
public void setQuestionnaires(List<Questionnaire> questionnaires) {
this.questionnaires = questionnaires;
}
public void addQuestionnaire(Questionnaire q) {
this.questionnaires.add(q);
}
public List<Photo> getPhotos() {
return photos;
}
public void setPhotos(List<Photo> photos) {
this.photos = photos;
}
public void addPhoto(Photo photo) {
this.photos.add(photo);
}
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
public Double getStatedValue() {
return statedValue;
}
public void setStatedValue(Double statedValue) {
this.statedValue = statedValue;
}
public Double getAdjustedValue() {
return adjustedValue;
}
public void setAdjustedValue(Double adjustedValue) {
this.adjustedValue = adjustedValue;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public void addComment(Comment comment) {
this.comments.add(comment);
}
@Override
public String toString() {
return "Claim [id=" + id + ", incident=" + incident + ", questionnaires=" + questionnaires + ", photos=" + photos + ", approved=" + approved + ", statedValue=" + statedValue + ", adjustedValue=" + adjustedValue + ", messages=" + comments + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Claim other = (Claim) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public long getProcessId() {
return processId;
}
public void setProcessId(long processId) {
this.processId = processId;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.