text stringlengths 10 2.72M |
|---|
package com.simha.springBootawslambda;
import java.util.List;
import java.util.function.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringBootAwsLambdaApplication {
@Autowired
private BookDAORepo bookDaoRepo;
public static void main(String[] args) {
SpringApplication.run(SpringBootAwsLambdaApplication.class, args);
}
@Bean
public Supplier<List<Orders>> getAllOrders()
{
return ()->bookDaoRepo.getOrders();
}
}
|
package com.example.timemate;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.CalendarView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.timemate.Database.AppDatabase;
import com.example.timemate.Database.OneDay;
import com.example.timemate.Database.OneDayDao;
import com.example.timemate.Database.TotalData;
import com.example.timemate.Database.TotalDataDao;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
public class ChartActivity extends AppCompatActivity implements View.OnClickListener {
private RecyclerView rv_days;
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static ArrayList<ODData> arrayList;
private static List<OneDay> rvODItems;
private static TextView tv_WDT, tv_EDT, tv_SDT, tv_week_work, tv_week_exercise, tv_week_study, tv_total_work, tv_total_exercise, tv_total_study, tv_month, tv_totalInfo;
private Animation fab_open_day, fab_open_week, fab_open_month, fab_open_time, fab_close, panelup_cal, paneldown_cal;
private Boolean isFabOpen = false, isCalVisible = false;
private FloatingActionButton fab_main, fab_day, fab_month, fab_time;
private LinearLayout LLO_chart_day, LLO_chart_month, LLO_calendar, LLO_chart_total;
private CalendarView calendar;
private static ProgressBar pb_month, pb_day;
private static int cnt_month = -1, cnt_day = -1;
static Context context;
private static int temp_month;
private AppDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chart);
db = AppDatabase.getAppDatabase(this); // 데이터베이스 가져오기
rv_days = findViewById(R.id.rv_days);
calendar = findViewById(R.id.calendar);
tv_WDT = findViewById(R.id.tv_WDT);
tv_EDT = findViewById(R.id.tv_EDT);
tv_SDT = findViewById(R.id.tv_SDT);
tv_week_work = findViewById(R.id.tv_week_work);
tv_week_exercise = findViewById(R.id.tv_week_exercise);
tv_week_study = findViewById(R.id.tv_week_study);
tv_total_work = findViewById(R.id.tv_total_work);
tv_total_exercise = findViewById(R.id.tv_total_exercise);
tv_total_study = findViewById(R.id.tv_total_study);
tv_month = findViewById(R.id.tv_month);
tv_totalInfo = findViewById(R.id.tv_totalInfo);
// 애니메이션
fab_main = findViewById(R.id.fab_main);
fab_day = findViewById(R.id.fab_day);
fab_month = findViewById(R.id.fab_month);
fab_time = findViewById(R.id.fab_time);
// 리니어 레이아웃
LLO_chart_day = findViewById(R.id.LLO_chart_day);
LLO_chart_month = findViewById(R.id.LLO_chart_month);
LLO_calendar = findViewById(R.id.LLO_calendar);
LLO_chart_total = findViewById(R.id.LLO_chart_total);
context = getApplicationContext();
// 프로그레스 바
pb_month = findViewById(R.id.pb_month);
pb_day = findViewById(R.id.pb_day);
rv_days.setHasFixedSize(true); // 얘는 그냥 달아주긴하는데 뭔지 정확히 모름
layoutManager = new LinearLayoutManager(this);
rv_days.setLayoutManager(layoutManager);
rv_days.addItemDecoration(new RecyclerViewDecoration(10));
arrayList = new ArrayList<>(); // OOData 객체를 담을 어레이 리스트(어댑터로 쏴줄것)
rvODItems = new ArrayList<>();
new DayAsyncTask(db.oneDayDao()).execute();
new MonthAsyncTask(db.oneDayDao()).execute();
new TotalAsyncTask(db.totalDataDao()).execute();
adapter = new OneDayAdapater(arrayList, this);
rv_days.setAdapter(adapter); // 리사이클러 뷰에 어댑터 연결
// 애니메이션 연결
fab_open_day = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open_day);
fab_open_week = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open_week);
fab_open_month = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open_month);
fab_open_time = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open_time);
fab_close = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_close);
panelup_cal = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.panelup_cal);
paneldown_cal = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.paneldown_cal);
fab_main.setOnClickListener(this);
fab_day.setOnClickListener(this);
fab_month.setOnClickListener(this);
fab_time.setOnClickListener(this);
// 패널업 애니메이션 리스너
panelup_cal.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
LLO_calendar.setVisibility(View.VISIBLE);
LLO_calendar.clearAnimation();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
// 패널다운 애니메이션 리스너
paneldown_cal.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
LLO_calendar.setVisibility(View.INVISIBLE);
LLO_calendar.clearAnimation();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
// 달력에서 특정 날짜를 선택하면 그 날짜를 가지고 일일 통계의 리싸이클러 뷰를 재구성한다.
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
new CalDayAsyncTask(db.oneDayDao()).execute(year, month + 1, dayOfMonth);
LLO_calendar.startAnimation(paneldown_cal);
isCalVisible = false;
LLO_chart_month.setVisibility(View.INVISIBLE);
LLO_chart_total.setVisibility(View.INVISIBLE);
LLO_chart_day.setVisibility(View.VISIBLE);
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fab_main:
anim();
break;
case R.id.fab_day:
if (isCalVisible) {
fab_main.setImageResource(R.drawable.fltbtn);
fab_day.setImageResource(R.drawable.day);
fab_month.setImageResource(R.drawable.month);
fab_time.setImageResource(R.drawable.clk);
LLO_calendar.startAnimation(paneldown_cal);
isCalVisible = false;
anim();
break;
} else {
fab_main.setImageResource(R.drawable.fltbtn2);
fab_day.setImageResource(R.drawable.day2);
fab_month.setImageResource(R.drawable.month2);
fab_time.setImageResource(R.drawable.clk2);
LLO_calendar.startAnimation(panelup_cal);
isCalVisible = true;
anim();
break;
}
case R.id.fab_month:
LLO_chart_day.setVisibility(View.INVISIBLE);
LLO_chart_total.setVisibility(View.INVISIBLE);
LLO_chart_month.setVisibility(View.VISIBLE);
if (isCalVisible) {
LLO_calendar.startAnimation(paneldown_cal);
isCalVisible = false;
}
// pbMonth();
break;
case R.id.fab_time:
LLO_chart_day.setVisibility(View.INVISIBLE);
LLO_chart_month.setVisibility(View.INVISIBLE);
LLO_chart_total.setVisibility(View.VISIBLE);
if (isCalVisible) {
LLO_calendar.startAnimation(paneldown_cal);
isCalVisible = false;
}
break;
}
}
// 애니메이션 적용
public void anim() {
if (isFabOpen) {
fab_day.startAnimation(fab_close);
fab_month.startAnimation(fab_close);
fab_time.startAnimation(fab_close);
fab_day.setClickable(false);
fab_month.setClickable(false);
fab_time.setClickable(false);
isFabOpen = false;
} else {
fab_day.startAnimation(fab_open_day);
fab_month.startAnimation(fab_open_month);
fab_time.startAnimation(fab_open_time);
fab_day.setClickable(true);
fab_month.setClickable(true);
fab_time.setClickable(true);
isFabOpen = true;
}
}
// 데이터 가져오기
public static class DayAsyncTask extends AsyncTask<OneDay, OneDay, Void> {
private OneDayDao mOneDayDao;
public DayAsyncTask(OneDayDao oneDayDao) {
this.mOneDayDao = oneDayDao;
}
@Override // 백그라운드 작업
protected Void doInBackground(OneDay... oneDays) {
if (!arrayList.isEmpty()) arrayList.clear();
if (!rvODItems.isEmpty()) rvODItems.clear();
Calendar cal = new GregorianCalendar();
int year = cal.get(Calendar.YEAR); // 연
int month = cal.get(Calendar.MONTH) + 1; // 월
int day = cal.get(Calendar.DATE); // 일
Log.e("오늘날짜", Integer.toString(year));
Log.e("오늘날짜", Integer.toString(month));
Log.e("오늘날짜", Integer.toString(day));
if (mOneDayDao.getAllItemsByDayInfo(year, month, day).size() != 0) { // 오늘 저장된 것이 하나라도 있다면
rvODItems = mOneDayDao.getAllItemsByDayInfo(year, month, day); // 오늘 정보만 가져온다
Log.e("오늘저장된게있는경우", Integer.toString(rvODItems.size()));
} else { // 오늘 저장된 놈이 하나도 없는 상태라면, 저장된 데이터가 있는 가장 최근의 날 정보들 보여주자
for (int i = 1; ; i++) {
Calendar cal2 = new GregorianCalendar();
cal2.add(Calendar.DAY_OF_MONTH, -i);
int y = cal2.get(Calendar.YEAR); // 연
int m = cal2.get(Calendar.MONTH) + 1; // 월
int d = cal2.get(Calendar.DATE); // 일
if (mOneDayDao.getAllItemsByDayInfo(y, m, d).size() != 0) {
rvODItems = mOneDayDao.getAllItemsByDayInfo(y, m, d);
Log.e("오늘저장된게없는경우 Y", Integer.toString(y));
Log.e("오늘저장된게없는경우 M", Integer.toString(m));
Log.e("오늘저장된게없는경우 D", Integer.toString(d));
break;
} else continue;
}
}
for (OneDay oneDay : rvODItems) {
ODData temp = new ODData(oneDay.getCategory(), oneDay.getTime());
arrayList.add(temp);
}
// 가장 최근 것이 rv에서 가장 위로 올라오도록 리스트를 뒤집어준다.
Collections.reverse(arrayList);
// onProgressUpdate로 가장 최근 저장된 OneDay 객체를 보낸다
publishProgress(rvODItems.get(rvODItems.size() - 1));
return null;
}
protected void onProgressUpdate(OneDay... oneDays) {
final long tempW, tempE, tempS;
OneDay last = oneDays[0];
tempW = last.getWork_dayTotal();
tempE = last.getExercise_dayTotal();
tempS = last.getStudy_dayTotal();
String tw = String.format("%02dHR %02dMIN", tempW / 1000 / 60 / 60, (tempW / 1000 / 60) % 60);
String te = String.format("%02dHR %02dMIN", tempE / 1000 / 60 / 60, (tempE / 1000 / 60) % 60);
String ts = String.format("%02dHR %02dMIN", tempS / 1000 / 60 / 60, (tempS / 1000 / 60) % 60);
tv_WDT.setText(tw);
tv_EDT.setText(te);
tv_SDT.setText(ts);
final Timer t = new Timer();
TimerTask tt = new TimerTask() {
@Override
public void run() {
cnt_day++;
Log.d("dddd", "" + cnt_day);
pb_day.setProgress(cnt_day);
if (cnt_day == ((tempW + tempE + tempS) / 1000 / 60 % 60) || cnt_day == 60)
t.cancel();
}
};
t.schedule(tt, 0, 20);
cnt_day = -1;
}
}
public static class CalDayAsyncTask extends AsyncTask<Integer, OneDay, Void> {
private OneDayDao mOneDayDao;
private boolean empty = false;
public CalDayAsyncTask(OneDayDao oneDayDao) {
this.mOneDayDao = oneDayDao;
}
@Override
protected Void doInBackground(Integer... integers) {
Log.d("integers", Integer.toString(integers[0]));
Log.d("integers", Integer.toString(integers[1]));
Log.d("integers", Integer.toString(integers[2]));
Log.d("size", Integer.toString(mOneDayDao.getAllItemsByDayInfo(integers[0], integers[1], integers[2]).size()));
if (!arrayList.isEmpty()) arrayList.clear();
if (!rvODItems.isEmpty()) rvODItems.clear();
if (!mOneDayDao.getAllItemsByDayInfo(integers[0], integers[1], integers[2]).isEmpty()) {
rvODItems = mOneDayDao.getAllItemsByDayInfo(integers[0], integers[1], integers[2]);
ArrayList<ODData> temp = new ArrayList<>();
for (OneDay oneDay : rvODItems) {
temp.add(new ODData(oneDay.getCategory(), oneDay.getTime()));
}
arrayList.addAll(temp);
Collections.reverse(arrayList);
Log.d("integers", Integer.toString(rvODItems.size()));
publishProgress(rvODItems.get(rvODItems.size() - 1));
Log.d("arraylist사이즈", Integer.toString(arrayList.size()));
} else {
empty = true;
// onProgressUpdate를 호출하기 위한 더미 객체 보냄
publishProgress(new OneDay(0, 0, 0, 0, 1, 1, 1, 1, 1));
}
Log.d("사이즈", "" + mOneDayDao.getAllItemsByDayInfo(integers[0], integers[1], integers[2]).size());
return null;
}
protected void onProgressUpdate(OneDay... oneDays) {
Log.d("비었냐", "" + empty);
if (empty)
Toast.makeText(context, "해당 날짜에는 기록이 없어요", Toast.LENGTH_SHORT).show();
else {
adapter.notifyDataSetChanged();
final long tempW, tempE, tempS;
OneDay last = oneDays[0];
tempW = last.getWork_dayTotal();
tempE = last.getExercise_dayTotal();
tempS = last.getStudy_dayTotal();
String tw = String.format("%02dHR %02dMIN", tempW / 1000 / 60 / 60, (tempW / 1000 / 60) % 60);
String te = String.format("%02dHR %02dMIN", tempE / 1000 / 60 / 60, (tempE / 1000 / 60) % 60);
String ts = String.format("%02dHR %02dMIN", tempS / 1000 / 60 / 60, (tempS / 1000 / 60) % 60);
tv_WDT.setText(tw);
tv_EDT.setText(te);
tv_SDT.setText(ts);
final Timer t = new Timer();
TimerTask tt = new TimerTask() {
@Override
public void run() {
cnt_day++;
Log.d("dddd", "" + cnt_day);
pb_day.setProgress(cnt_day);
if (cnt_day == ((tempW + tempE + tempS) / 1000 / 60 % 60) || cnt_day == 60) t.cancel();
}
};
t.schedule(tt, 0, 20);
cnt_day = -1;
}
}
}
public static class MonthAsyncTask extends AsyncTask<OneDay, List<Long>, Void> {
private OneDayDao mOneDayDao;
public MonthAsyncTask(OneDayDao oneDayDao) {
this.mOneDayDao = oneDayDao;
}
@Override
protected Void doInBackground(OneDay... oneDays) {
List<OneDay> temp = mOneDayDao.getAllItems();
OneDay last = temp.get(temp.size() - 1);
int tempDay = last.getDay(); // 가장 최근에 기록된 녀석의 날짜를 가져온다
Log.d("가장최근날짜", "" + last.getDay());
List<Long> tempInt = new ArrayList();
int cursor = temp.size() - 1;
long a = 0, b = 0, c = 0;
for (int i = cursor; i >= 0; i--) {
Log.d("해당 커서", "" + i);
Log.d("해당 월", "" + (temp.get(i).getMonth()));
Log.d("해당 날짜", "" + temp.get(i).getDay());
if (i == cursor) {
a += temp.get(i).getWork_dayTotal();
b += temp.get(i).getExercise_dayTotal();
c += temp.get(i).getStudy_dayTotal();
} else if ((temp.get(i + 1).getDay() != temp.get(i).getDay()) && (temp.get(i + 1).getMonth() == temp.get(i).getMonth())) { // 날짜가 같다면 굳이 연산하지 않는다
a += temp.get(i).getWork_dayTotal();
b += temp.get(i).getExercise_dayTotal();
c += temp.get(i).getStudy_dayTotal();
} else if (temp.get(i + 1).getMonth() != temp.get(i).getMonth())
break;
else continue;
}
tempInt.add(a);
tempInt.add(b);
tempInt.add(c);
publishProgress(tempInt);
return null;
}
protected void onProgressUpdate(List<Long>... lists) {
final long a = lists[0].get(0);
final long b = lists[0].get(1);
final long c = lists[0].get(2);
final long d = a + b + c;
String aa = String.format("%02dHR %02dMIN", a / 1000 / 60 / 60, (a / 1000 / 60) % 60);
String bb = String.format("%02dHR %02dMIN", b / 1000 / 60 / 60, (b / 1000 / 60) % 60);
String cc = String.format("%02dHR %02dMIN", c / 1000 / 60 / 60, (c / 1000 / 60) % 60);
String dd = String.format("%02dHOUR %02dMIN", d / 1000 / 60 / 60, (d / 1000 / 60) % 60);
tv_week_work.setText(aa);
tv_week_exercise.setText(bb);
tv_week_study.setText(cc);
tv_month.setText(dd);
pb_month.setProgress(((int) ((a + b + c) / 1000 / 60 / 60)) * 2);
//temp_month=((int) ((a + b + c) / 1000 / 60 / 60)) * 2;
/*final Timer t = new Timer();
TimerTask tt = new TimerTask() {
@Override
public void run() {
cnt_month++;
Log.d("dddd", "" + cnt_month);
pb_month.setProgress(cnt_month);
if (cnt_month == ((a+b+c) / 1000 / 60 % 60)) t.cancel();
}
};
t.schedule(tt, 0, 20);
cnt_month = -1;*/
}
}
public static class TotalAsyncTask extends AsyncTask<TotalData, TotalData, Void> {
private TotalDataDao mTotalDataDao;
public TotalAsyncTask(TotalDataDao totalDataDao) {
this.mTotalDataDao = totalDataDao;
}
@Override
protected Void doInBackground(TotalData... totalDatas) {
TotalData temp = mTotalDataDao.getAllItems().get(0);
publishProgress(temp);
return null;
}
protected void onProgressUpdate(TotalData... totalDatas) {
long a = totalDatas[0].getWork_Total();
long b = totalDatas[0].getExercise_Total();
long c = totalDatas[0].getStudy_Total();
long d = a + b + c;
String aa = String.format("%02dHR %02dMIN", a / 1000 / 60 / 60, (a / 1000 / 60) % 60);
String bb = String.format("%02dHR %02dMIN", b / 1000 / 60 / 60, (b / 1000 / 60) % 60);
String cc = String.format("%02dHR %02dMIN", c / 1000 / 60 / 60, (c / 1000 / 60) % 60);
String dd = String.format("%02dHOUR %02dMIN", d / 1000 / 60 / 60, (d / 1000 / 60) % 60);
tv_total_work.setText(aa);
tv_total_exercise.setText(bb);
tv_total_study.setText(cc);
tv_totalInfo.setText(dd);
}
}
@Override
public void onBackPressed() {
if (isFabOpen) {
fab_day.startAnimation(fab_close);
fab_month.startAnimation(fab_close);
fab_time.startAnimation(fab_close);
fab_day.setClickable(false);
fab_month.setClickable(false);
fab_time.setClickable(false);
isFabOpen = false;
} else if (isCalVisible && isFabOpen) {
fab_day.startAnimation(fab_close);
fab_month.startAnimation(fab_close);
fab_time.startAnimation(fab_close);
fab_day.setClickable(false);
fab_month.setClickable(false);
fab_time.setClickable(false);
isFabOpen = false;
} else if (isCalVisible && !isFabOpen) {
LLO_calendar.startAnimation(paneldown_cal);
isCalVisible = false;
} else {
finish();
}
}
/* public void pbMonth() {
final Timer t = new Timer();
TimerTask tt = new TimerTask() {
@Override
public void run() {
// tempTT는 ms단위임
cnt_month++;
pb_month.setProgress(cnt_month);
if (cnt_month == temp_month) t.cancel();
}
};
t.schedule(tt, 0, 20);
cnt_month = -1;
}*/
}
|
/*
* 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 lambda;
public class MyQuickSort<T> {
private T array[];
private int length;
private Functional<T> func;
public void sort(T[] inputArr,Functional<T> func, boolean Ascending) {
if (inputArr == null || inputArr.length == 0) {
return;
}
this.array = inputArr;
this.func = func;
length = inputArr.length;
if(Ascending) quickSort(0, length - 1);
else quickSortDesc(0, length-1);
}
private void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
// calculate pivot number, I am taking pivot as middle index number
Object o = func.ComparableObject(array[lowerIndex+(higherIndex-lowerIndex)/2]);
Comparable<Object> pivot = (Comparable)o;
// Divide into two arrays
while (i <= j) {
/**
* In each iteration, we will identify a number from left side which
* is greater then the pivot value, and also we will identify a number
* from right side which is less then the pivot value. Once the search
* is done, then we exchange both numbers.
*/
while (Compare(((Comparable)func.ComparableObject(array[i])), pivot) < 0) {
i++;
}
while (Compare(((Comparable)func.ComparableObject(array[j])), pivot) > 0 ) {
j--;
}
if (i <= j) {
exchangeNumbers(i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
}
private void quickSortDesc(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
// calculate pivot number, I am taking pivot as middle index number
Object o = func.ComparableObject(array[lowerIndex+(higherIndex-lowerIndex)/2]);
Comparable<Object> pivot = (Comparable)o;
// Divide into two arrays
while (i <= j) {
/**
* In each iteration, we will identify a number from left side which
* is greater then the pivot value, and also we will identify a number
* from right side which is less then the pivot value. Once the search
* is done, then we exchange both numbers.
*/
while (Compare(pivot,((Comparable)func.ComparableObject(array[i]))) <0 ) {
i++;
}
while (Compare(pivot,((Comparable)func.ComparableObject(array[j])))>0 ) {
j--;
}
if (i <= j) {
exchangeNumbers(i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j)
quickSortDesc(lowerIndex, j);
if (i < higherIndex)
quickSortDesc(i, higherIndex);
}
private void exchangeNumbers(int i, int j) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private int Compare(Comparable<Object> o1,Comparable<Object> o2)
{
if (o1 == null)
{
return (o2 == null) ? 0 : -1;
}
if (o2 == null)
{
return 1;
}
return o1.compareTo(o2);
}
/*public static void main(String a[]){
MyQuickSort sorter = new MyQuickSort();
Integer[] input = {24,2,45,20,56,75,2,56,99,53,12};
sorter.sort(input,o-> o);
for(int i:input){
System.out.print(i);
System.out.print(" ");
}
}*/
}
|
package com.duofei.beans.circularDepend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author duofei
* @date 2020/7/16
*/
@Component
public class ServiceB {
{
System.out.println("serviceB" + 1);
}
public ServiceB(){
System.out.println("serviceB instant...");
}
@Autowired
private ServiceA serviceA;
}
|
package com.tencent.mm.plugin.mall.ui;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.bg.d;
import com.tencent.mm.model.q;
import com.tencent.mm.platformtools.ab;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.protocal.c.ccq;
class MallIndexOSUI$3 implements OnClickListener {
final /* synthetic */ MallIndexOSUI kZI;
final /* synthetic */ ccq kZK;
MallIndexOSUI$3(MallIndexOSUI mallIndexOSUI, ccq ccq) {
this.kZI = mallIndexOSUI;
this.kZK = ccq;
}
public final void onClick(View view) {
h.mEJ.h(13867, new Object[]{ab.a(this.kZK.syr), Integer.valueOf(this.kZI.kYc)});
Intent intent = new Intent();
intent.putExtra("rawUrl", ab.a(this.kZK.syr));
intent.putExtra("geta8key_username", q.GF());
intent.putExtra("pay_channel", 1);
d.b(this.kZI, "webview", "com.tencent.mm.plugin.webview.ui.tools.WebViewUI", intent);
}
}
|
package com.simbircite.demo.util.spring;
import java.beans.PropertyEditorSupport;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
public class CustomDateTimeEditor extends PropertyEditorSupport {
DateTimeFormatter formatter = null;
public CustomDateTimeEditor(DateTimeFormatter formatter) {
super();
this.formatter = formatter;
}
@Override
public String getAsText() {
DateTime value = (DateTime) getValue();
return (value == null)
? ""
: value.toString(formatter);
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
try {
setValue(DateTime.parse(text, formatter));
} catch (IllegalArgumentException ignore) {
setValue(null);
}
}
} |
/* Use these two sites for help understanding how an Illinois Driver's license number is created (these will be used in the Person class, not in this one)
http://www.highprogrammer.com/alan/numbers/dl_us_shared.html
http://www.highprogregardscom/alan/numbers/soundex.html
*/
/* A person should have a first name, last name, middle initial, birthday, birthmonth, birthyear, and gender... Read the comments to determine what needs to be completed*/
// NOTE: Anything you need to do will be in ALL CAPS
public class Person
{
// CREATE INSTANCE VARIABLES
private String lastName = "";
private String middleInitial = "";
private String firstName = "";
private boolean isMale = false;
private String gender = "";
private int[] dob = new int[3];
public static final String RED_BOLD_BRIGHT = "\033[1;91m";
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\033[0;90m"; // B
public static final String ANSI_RED = "\033[0;91m"; // 1
public static final String ANSI_GREEN = "\033[0;92m"; // 2
public static final String ANSI_YELLOW = "\033[0;93m"; // 3
public static final String ANSI_BLUE = "\033[0;94m"; // 4
public static final String ANSI_PURPLE = "\033[0;95m"; // 5+
public static final String ANSI_CYAN = "\033[0;96m";
public static final String ANSI_WHITE = "\033[0;97m";
// WRITE CONSTRUCTOR
public Person(String lastName, String middleInitial, String firstName, String isMale, int month, int day, int year) {
this.isMale = isMale.equals("M") || isMale.equals("MALE");
this.lastName = lastName.toUpperCase();
this.middleInitial = middleInitial.toUpperCase();
this.firstName = firstName.toUpperCase();
this.dob[0] = month;
this.dob[1] = day;
this.dob[2] = year;
if(this.isMale)
gender = "MALE";
else
gender = "FEMALE";
}
// FIND THE SOUNDEX CODE
// DO THIS METHOD LAST... IT'S THE HARDEST :)
// USE http://www.highprogrammer.com/alan/numbers/soundex.html FOR RULES
public String getName() {
if(middleInitial.length() >= 1)
return firstName + " " + middleInitial + " " + lastName;
else
return firstName + " " + lastName;
}
public String getSSSS(){
String result = "";
result += lastName.substring(0, 1);
String tempL = "";
boolean skip = false;
int lastCode = -1;
for(int i = 0; i < lastName.length(); i++) {
if(skip){
skip = false;
continue;
}
if(i < lastName.length() - 1 && SSSScode(lastName.substring(i, i+1)) == SSSScode(lastName.substring(i+1, i+2)) || SSSScode(lastName.substring(i, i+1)) == lastCode) {
lastCode = SSSScode(lastName.substring(i, i+1));
skip = true;
} else {
lastCode = -1;
}
if(i < lastName.length() - 1 && lastName.substring(i, i+1).equals("W") || lastName.substring(i, i+1).equals("H")) {
skip = true;
}
tempL += lastName.substring(i, i + 1);
}
// System.out.println(tempL);
int remaining = 3;
for(int i = 1; i < tempL.length(); i++) {
if(remaining <= 0)
break;
int temp = SSSScode(tempL.substring(i, i + 1));
if(temp > 0) {
result += temp;
remaining--;
}
else
continue;
}
for(int i = 0; i < remaining; i++)
result += 0;
return result;
}
public int SSSScode(String s) {
int code = 0;
switch(s) {
case "B":
case "F":
case "P":
case "V":
code = 1;
break;
case "C":
case "G":
case "J":
case "K":
case "Q":
case "S":
case "X":
case "Z":
code = 2;
break;
case "D":
case "T":
code = 3;
break;
case "L":
code = 4;
break;
case "M":
case "N":
code = 5;
break;
case "R":
code = 6;
break;
default:
code = 0;
break;
}
return code;
}
// FIND FFF CODE...
// NOTE: There are some helper methods already written for you... PLEASE use them!
public String getFFF(){
String result = "";
int f = 0;
if(getFirstNameCode() != 0) {
f += getFirstNameCode();
} else {
f = getFirstInitialCode(firstName.substring(0,1));
}
f += getMiddleInitialCode();
result += f;
return String.format("%03d", new Integer(result));
}
// COMPLETE THE DDD CODE
public String getDDD(){
int result = 0;
result += ((dob[0]-1)*31)+dob[1];
if(!isMale){
result+=600;
}
String res = "";
res+=result;
res = String.format("%03d", new Integer(res));
return res;
}
// WRITE A METHOD THAT WILL RETURN THE ENTIRE DRIVER'S LICENSE NUMBER
public String gN(){
String str = "" + getSSSS() + getFFF() + String.format("%02d", new Integer(dob[2])) + getDDD();
return str.substring(0,4) + "-" + str.substring(4,8) + "-" + str.substring(8,12);
}
// Do NOT change this code... but DO USE this code... it is tedious, and would not have had value for you to write it on your own.
private int getFirstNameCode ()
{
int fff = 0;
if (firstName.equals("ALBERT") ||
firstName.equals("ALICE"))
{
fff = 20;
}
else if (firstName.equals("ANN") ||
firstName.equals("ANNA") ||
firstName.equals("ANNE")||
firstName.equals("ANNIE")||
firstName.equals("ARTHUR"))
{
fff = 40;
}
else if (firstName.equals("BERNARD") ||
firstName.equals("BETTE") ||
firstName.equals("BETTIE")||
firstName.equals("BETTY"))
{
fff = 80;
}
else if (firstName.equals("CARL") ||
firstName.equals("CATHERINE"))
{
fff = 120;
}
else if (firstName.equals("CHARLES") ||
firstName.equals("CLARA"))
{
fff = 140;
}
else if (firstName.equals("DORTHY") ||
firstName.equals("DONALD"))
{
fff = 180;
}
else if (firstName.equals("EDWARD") ||
firstName.equals("ELIZABETH"))
{
fff = 220;
}
else if (firstName.equals("FLORENCE") ||
firstName.equals("FRANK"))
{
fff = 260;
}
else if (firstName.equals("GEORGE") ||
firstName.equals("GRACE"))
{
fff = 300;
}
else if (firstName.equals("HAROLD") ||
firstName.equals("HARRIET"))
{
fff = 340;
}
else if (firstName.equals("HARRY") ||
firstName.equals("HAZEL"))
{
fff = 360;
}
else if (firstName.equals("JAMES") ||
firstName.equals("JANE") ||
firstName.equals("JAYNE"))
{
fff = 440;
}
else if (firstName.equals("JEAN") ||
firstName.equals("JOHN"))
{
fff = 460;
}
else if (firstName.equals("JOAN") ||
firstName.equals("JOSEPH"))
{
fff = 480;
}
else if (firstName.equals("MARGARET") ||
firstName.equals("MARTIN"))
{
fff = 560;
}
else if (firstName.equals("MARVIN") ||
firstName.equals("MARY"))
{
fff = 580;
}
else if (firstName.equals("MELVIN") ||
firstName.equals("MILDRED"))
{
fff = 600;
}
else if (firstName.equals("PATRICIA") ||
firstName.equals("PAUL"))
{
fff = 680;
}
else if (firstName.equals("RICHARD") ||
firstName.equals("RUBY"))
{
fff = 740;
}
else if (firstName.equals("ROBERT") ||
firstName.equals("RUTH"))
{
fff = 760;
}
else if (firstName.equals("THELMA") ||
firstName.equals("THOMAS"))
{
fff = 820;
}
else if (firstName.equals("WALTER") ||
firstName.equals("WANDA"))
{
fff = 900;
}
else if (firstName.equals("WILLIAM") ||
firstName.equals("WILMA"))
{
fff = 920;
}
return fff;
}
// Do NOT change this code... but DO USE this code... it is tedious, and would not have had value for you to write it on your own.
private int getFirstInitialCode(String firstInitial)
{
int fff = 0;
if (firstInitial.equals("A")) fff = 0;
else if (firstInitial.equals("B")) fff = 60;
else if (firstInitial.equals("C")) fff = 100;
else if (firstInitial.equals("D")) fff = 160;
else if (firstInitial.equals("E")) fff = 200;
else if (firstInitial.equals("F")) fff = 240;
else if (firstInitial.equals("G")) fff = 280;
else if (firstInitial.equals("H")) fff = 320;
else if (firstInitial.equals("I")) fff = 400;
else if (firstInitial.equals("J")) fff = 420;
else if (firstInitial.equals("K")) fff = 500;
else if (firstInitial.equals("L")) fff = 520;
else if (firstInitial.equals("M")) fff = 540;
else if (firstInitial.equals("N")) fff = 620;
else if (firstInitial.equals("O")) fff = 640;
else if (firstInitial.equals("P")) fff = 660;
else if (firstInitial.equals("Q")) fff = 700;
else if (firstInitial.equals("R")) fff = 720;
else if (firstInitial.equals("S")) fff = 780;
else if (firstInitial.equals("T")) fff = 800;
else if (firstInitial.equals("U")) fff = 840;
else if (firstInitial.equals("V")) fff = 860;
else if (firstInitial.equals("W")) fff = 880;
else if (firstInitial.equals("X")) fff = 940;
else if (firstInitial.equals("Y")) fff = 960;
else if (firstInitial.equals("Z")) fff = 980;
return fff;
}
// Do NOT change this code... but DO USE this code... it is tedious, and would not have had value for you to write it on your own.
private int getMiddleInitialCode()
{
int fff = 0;
if (middleInitial.equals("A")) fff = 1;
else if (middleInitial.equals("B")) fff = 2;
else if (middleInitial.equals("C")) fff = 3;
else if (middleInitial.equals("D")) fff = 4;
else if (middleInitial.equals("E")) fff = 5;
else if (middleInitial.equals("F")) fff = 6;
else if (middleInitial.equals("G")) fff = 7;
else if (middleInitial.equals("H")) fff = 8;
else if (middleInitial.equals("I")) fff = 9;
else if (middleInitial.equals("J")) fff = 10;
else if (middleInitial.equals("K")) fff = 11;
else if (middleInitial.equals("L")) fff = 12;
else if (middleInitial.equals("M")) fff = 13;
else if (middleInitial.equals("N")) fff = 14;
else if (middleInitial.equals("O")) fff = 14;
else if (middleInitial.equals("P")) fff = 15;
else if (middleInitial.equals("Q")) fff = 15;
else if (middleInitial.equals("R")) fff = 16;
else if (middleInitial.equals("S")) fff = 17;
else if (middleInitial.equals("T")) fff = 18;
else if (middleInitial.equals("U")) fff = 18;
else if (middleInitial.equals("V")) fff = 18;
else if (middleInitial.equals("W")) fff = 19;
else if (middleInitial.equals("X")) fff = 19;
else if (middleInitial.equals("Y")) fff = 19;
else if (middleInitial.equals("Z")) fff = 19;
return fff;
}
public String toString() {
return "NAME: " + (ANSI_PURPLE + getName() + ANSI_RESET) + "\n" +
("DOB: " + ANSI_GREEN + String.format("%02d", new Integer(dob[0])) + "/" + String.format("%02d", new Integer(dob[1])) + "/" + String.format("%02d", new Integer(dob[2])) + ANSI_RESET) + "\n" +
("GENDER: " + ANSI_RED + gender) + "\n" +
(ANSI_BLUE + "\u001b[4m" + gN()) + ANSI_RESET + "\n" +
("");
}
// ("SSSS: " + ANSI_GREEN + getSSSS()+ ANSI_RESET) + "\n" +
// ("FFF: " + ANSI_GREEN + getFFF()+ ANSI_RESET) + "\n" +
// ("DDD: " + ANSI_GREEN + getDDD()+ ANSI_RESET) + "\n" +
}
|
package me.ductrader.javapractice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Human implements Comparable<Human> {
private String name;
private int salary;
public Human(String name, int salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public int getSalary() {
return salary;
}
@Override
public String toString() {
return this.getName() + " - Salary: " + this.getSalary();
}
@Override
public int compareTo(Human human) {
return this.getSalary() - human.getSalary();
}
}
public class Main {
public static void main(String[] args) {
List<Human> people = new ArrayList<Human>();
Human brian = new Human("Brian", 100);
people.add(brian);
Human alex = new Human("Alex", 250);
people.add(alex);
Human sophie = new Human("Sophie", 200);
people.add(sophie);
Human joseph = new Human("Joseph", 175);
people.add(joseph);
Collections.sort(people);
people.forEach(person -> System.out.println(person));
}
}
|
package domain;
// Generated Jan 20, 2010 12:31:25 AM by Hibernate Tools 3.2.1.GA
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Rangies generated by hbm2java
*/
@Entity
@Table(name="rangies"
,catalog="catalog"
)
public class Range implements java.io.Serializable {
private int id;
private String name;
private Date created;
private Date modified;
private Set<User> userses = new HashSet<User>(0);
public Range() {
}
public Range(int id, String name, Date created, Date modified) {
this.id = id;
this.name = name;
this.created = created;
this.modified = modified;
}
public Range(int id, String name, Date created, Date modified, Set<User> userses) {
this.id = id;
this.name = name;
this.created = created;
this.modified = modified;
this.userses = userses;
}
@Id
@Column(name="id", unique=true, nullable=false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="name", nullable=false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created", nullable=false, length=19)
public Date getCreated() {
return this.created;
}
public void setCreated(Date created) {
this.created = created;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="modified", nullable=false, length=19)
public Date getModified() {
return this.modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
@ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JoinTable(name="usersrangies", catalog="catalog", joinColumns = {
@JoinColumn(name="range_id", nullable=false, updatable=false) }, inverseJoinColumns = {
@JoinColumn(name="user_id", nullable=false, updatable=false) })
public Set<User> getUserses() {
return this.userses;
}
public void setUserses(Set<User> userses) {
this.userses = userses;
}
@Override
public String toString() {
return this.name;
}
}
|
class Hw7_1{
public static void main (String [] args){
int [] scores = new int [50];
int [] hist = new int [10];
for(int i=0; i<scores.length; i++){
scores[i]=(int)(Math.random()*101);
if (scores[i]==100) hist[9]++;
else hist[scores[i]/10]++;
}
for(int i=0;i<10 ;i++){
System.out.printf("%2d:", i*10+5);
for(int j=0;j<hist[i];j++){
System.out.print("*");
}
System.out.println();
}
}
} |
package com.philippe.app.service.json;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jsonpatch.JsonPatchException;
import java.io.IOException;
public interface JsonService {
/**
* To provide differences between 2 JSON Strings initialState and newState.
*/
JsonNode provideDifferences(final String initialState, final String newState) throws IOException;
/**
* To apply the patch onto the initial JSON edenJsonNode.
*/
JsonNode applyPatch(final JsonNode edenJsonNode, final String patch) throws IOException, JsonPatchException;
}
|
package it.univaq.rtv.Model;
import java.util.Random;
public class SingletonDado {
private static SingletonDado istance = null;
private Random numero;
private int lati;
/**
* @return
*/
public static SingletonDado getIstance(){
if(istance==null){
istance = new SingletonDado();
istance.numero = new Random();
istance.lati=6;
}
return istance;
}
/**
*
*/
protected SingletonDado(){
}
/**
* @return
*/
public int lancia() {
int n=1+this.numero.nextInt(this.lati);
return n;
}
} |
package com.example.revzik.dosimeter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioGroup;
import android.widget.Toast;
public class AppSettingsActivity extends AppCompatActivity {
private RadioGroup calibration;
private RadioGroup lex8;
private RadioGroup spl;
private RadioGroup peak;
private Button back;
private Button loadCal;
private Button saveCal;
private CheckBox reset;
private Calibrator calibrator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appsettingslayout);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setComponents();
Intent intent = getIntent();
calibrator = (Calibrator)intent.getSerializableExtra(HomeActivity.CALIBRATOR);
if(calibrator.getCurve() == 1) {
calibration.check(R.id.cal_a);
} else if(calibrator.getCurve() == 2) {
calibration.check(R.id.cal_c);
} else {
calibration.check(R.id.cal_lin);
}
int lex8Curve = intent.getIntExtra(HomeActivity.LEX8_CURVE, 1);
if(lex8Curve == 1) {
lex8.check(R.id.lex8_a);
} else if(lex8Curve == 2) {
lex8.check(R.id.lex8_c);
} else {
lex8.check(R.id.lex8_lin);
}
int splCurve = intent.getIntExtra(HomeActivity.SPL_CURVE, 1);
if(splCurve == 1) {
spl.check(R.id.spl_a);
} else if(splCurve == 2) {
spl.check(R.id.spl_c);
} else {
spl.check(R.id.spl_lin);
}
int peakCurve = intent.getIntExtra(HomeActivity.PEAK_CURVE, 2);
if(peakCurve == 1) {
peak.check(R.id.peak_a);
} else if(peakCurve == 2) {
peak.check(R.id.peak_c);
} else {
peak.check(R.id.peak_lin);
}
saveCal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(calibrator.canUseStorage()) {
if (calibrator.save()) {
Toast.makeText(getApplicationContext(), R.string.cal_save_success, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), R.string.cal_save_fail, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), R.string.storage_denied, Toast.LENGTH_LONG).show();
}
}
});
loadCal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(calibrator.canUseStorage()) {
if (calibrator.load()) {
Toast.makeText(getApplicationContext(), R.string.cal_load_success, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), R.string.cal_load_fail, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), R.string.storage_denied, Toast.LENGTH_LONG).show();
}
}
});
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
if(calibration.getCheckedRadioButtonId() == R.id.cal_a) {
calibrator.setCurve(1);
} else if(calibration.getCheckedRadioButtonId() == R.id.cal_c) {
calibrator.setCurve(2);
} else {
calibrator.setCurve(3);
}
intent.putExtra(HomeActivity.CALIBRATOR, calibrator);
if(lex8.getCheckedRadioButtonId() == R.id.lex8_a) {
intent.putExtra(HomeActivity.LEX8_CURVE, 1);
} else if(lex8.getCheckedRadioButtonId() == R.id.lex8_c) {
intent.putExtra(HomeActivity.LEX8_CURVE, 2);
} else {
intent.putExtra(HomeActivity.LEX8_CURVE, 3);
}
if(spl.getCheckedRadioButtonId() == R.id.spl_a) {
intent.putExtra(HomeActivity.SPL_CURVE, 1);
} else if(spl.getCheckedRadioButtonId() == R.id.spl_c) {
intent.putExtra(HomeActivity.SPL_CURVE, 2);
} else {
intent.putExtra(HomeActivity.SPL_CURVE, 3);
}
if(peak.getCheckedRadioButtonId() == R.id.peak_a) {
intent.putExtra(HomeActivity.PEAK_CURVE, 1);
} else if(peak.getCheckedRadioButtonId() == R.id.peak_c) {
intent.putExtra(HomeActivity.PEAK_CURVE, 2);
} else {
intent.putExtra(HomeActivity.PEAK_CURVE, 3);
}
if(reset.isChecked()) {
intent.putExtra(HomeActivity.SHOULD_RESET, true);
} else {
intent.putExtra(HomeActivity.SHOULD_RESET, false);
}
setResult(RESULT_OK, intent);
finish();
}
});
}
public void setComponents() {
calibration = findViewById(R.id.cal_setting);
lex8 = findViewById(R.id.lex8_setting);
spl = findViewById(R.id.SPL_setting);
peak = findViewById(R.id.peak_setting);
back = findViewById(R.id.back_button);
loadCal = findViewById(R.id.load_cal);
saveCal = findViewById(R.id.save_cal);
reset = findViewById(R.id.reset_measurement);
}
}
|
package bridge.design.pattern.example1;
public class BridgePatternTest {
public static void main(String args[]){
Shape circle=new Circle();
Pattern solidPattern=new SolidFillPattern();
circle.applyPattern(solidPattern);
circle.draw();
Shape triangle=new Triangle();
Pattern strippedPattern=new StrippedFillPattern();
triangle.applyPattern(strippedPattern);
triangle.draw();
}
}
|
package br.com.giorgetti.games.squareplatform.gameobjects.interaction.auto;
import br.com.giorgetti.games.squareplatform.gameobjects.sprite.Animation;
import br.com.giorgetti.games.squareplatform.main.GamePanel;
import br.com.giorgetti.games.squareplatform.media.MediaPlayer;
import java.awt.*;
/**
* Coin that gives points to the player and moves through the screen.
*
* Created by fgiorgetti on 08/07/17.
*/
public class Coin extends AutoInteractiveSprite {
private static MediaPlayer mediaPlayer = new MediaPlayer("/sounds/coin.wav", MediaPlayer.MediaType.SFX);
private final int HEIGHT = 20;
private final int WIDTH = 14;
private final int SCORE = 10;
public Coin() {
this.width = WIDTH;
this.height = HEIGHT;
loadAnimation(Animation.newAnimation(Coin.class.getSimpleName(),
"/sprites/objects/coin.png", 14).delay(100));
setAnimation(Coin.class.getSimpleName());
}
@Override
protected int getJumpSpeed() {
return 10;
}
public Coin(int x, int y) {
this();
this.x = x;
this.y = y;
this.xSpeed = 1;
jump();
}
@Override
public void executeInteraction() {
mediaPlayer.play(false);
map.getPlayer().addScore(SCORE);
map.removeSprite(this);
mediaPlayer.remove();
}
@Override
public void draw(Graphics2D g) {
g.drawImage(getCurrentAnimation(),
getX() - getHalfWidth() - map.getX(),
GamePanel.HEIGHT - getY() - getHalfHeight() + map.getY(),
getWidth(), getHeight(), null);
if ( debug ) {
System.out.printf("X=%d/Y=%d --- MAP X=%d/Y=%d\n", getX(), getY(), map.getX(), map.getY());
g.setColor(Color.black);
g.fillOval(getX() - getHalfWidth() - map.getX() - 1, GamePanel.HEIGHT - getY() - getHalfHeight() + map.getY() + 1, WIDTH, HEIGHT);
g.setColor(Color.yellow);
g.fillOval(getX() - getHalfWidth() - map.getX(), GamePanel.HEIGHT - getY() - getHalfHeight() + map.getY(), WIDTH, HEIGHT);
}
}
}
|
package com.esc.fms.entity;
public class RoleRefPermission {
private Integer recordID;
private Integer roleID;
private Integer permissionID;
public Integer getRecordID() {
return recordID;
}
public void setRecordID(Integer recordID) {
this.recordID = recordID;
}
public Integer getRoleID() {
return roleID;
}
public void setRoleID(Integer roleID) {
this.roleID = roleID;
}
public Integer getPermissionID() {
return permissionID;
}
public void setPermissionID(Integer permissionID) {
this.permissionID = permissionID;
}
} |
package scriptinterface.execution.returnvalues;
/**
* Can be returned by a function call. This includes results, errors etc.
*/
public abstract class ExecutionReturn {
/**
* Indicates, that there is no value. Can for example be returned in functions which do not return a result.
*/
public static final ExecutionReturn VOID = new ExVoid();
/**
* Indicates, that something is undefined.
*/
public static final ExecutionReturn UNDEF = new ExUndef();
/**
* Supposed to quit the program if returned.
*/
public static final ExecutionReturn QUIT = new ExQuit();
/**
* Indicates whether or not this execution return is a reason to interrupt script execution (e.g. error).
*
* @return true, if and only if script execution should be stopped.
*/
public boolean isStopExecution() {
return false;
}
/**
* Returns a user-readable string representation of this instance.
*
* @return the string representation of this instance.
*/
public String getStringRepresentation() {
return toString();
}
/**
* Returns the value as a constant in valid script syntax.
*
* @return the value in its constant representation.
*/
public String getScriptConstantRepresentation() {
return getStringRepresentation();
}
private static class ExVoid extends ExecutionReturn {
@Override
public String toString() {
return "<void>";
}
@Override
public String getScriptConstantRepresentation() {
return "";
}
}
private static class ExUndef extends ExecutionReturn {
@Override
public String toString() {
return "<undefined>";
}
}
private static class ExQuit extends ExecutionReturn {
@Override
public String toString() {
return "Quit";
}
@Override
public boolean isStopExecution() {
return true;
}
}
}
|
package com.sparknetworks.loveos.domain;
import java.net.URI;
public class UserMatched {
private Profile relatedProfile;
private URI mainPhotoUrl;
private boolean favorited;
private String displayName;
private Integer contactsExchanged;
private Double compatibilityScore;
private Integer age;
private Integer heightInCm;
private City city;
private String religion;
private String jobTitle;
private UserMatched(Profile relatedProfile) {
this.relatedProfile = relatedProfile;
}
public static UserMatched createUserMatchedRelatedToProfile(Profile relatedProfile) {
return new UserMatched(relatedProfile);
}
public void setMainPhoto(URI mainPhotoUrl) {
this.mainPhotoUrl = mainPhotoUrl;
}
public boolean hasPhoto() {
return mainPhotoUrl != null;
}
public void setFavorited() {
this.favorited = true;
}
public boolean isFavorited() {
return favorited;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
public URI getMainPhotoUrl() {
return mainPhotoUrl;
}
public void setContactsExchanged(Integer contactsExchanged) {
this.contactsExchanged = contactsExchanged;
}
public Integer getContactsExchanged() {
return contactsExchanged;
}
public boolean hasCompatibilityScoreWithinRange(Range<Double> range) {
return range.isWithinRange(this.compatibilityScore);
}
public void setCompatibilityScore(Double compatibilityScore) {
this.compatibilityScore = compatibilityScore;
}
public void setAge(Integer age) {
this.age = age;
}
public boolean isAgedBetween(Range<Integer> ageRange) {
return ageRange.isWithinRange(this.age);
}
public void setHeightInCm(Integer heightInCm) {
this.heightInCm = heightInCm;
}
public boolean hasHeightBetween(Range<Integer> heightInCmRange) {
return heightInCmRange.isWithinRange(this.heightInCm);
}
public boolean distanceFromProfileCityIsWithinRadius(Double distanceRadiusInKm) {
return this.relatedProfile.getCity().distanceInKmTo(this.getCity()) <= distanceRadiusInKm;
}
public void setCity(City city) {
this.city = city;
}
public City getCity() {
return city;
}
public void setReligion(String religion) {
this.religion = religion;
}
public String getReligion() {
return religion;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getJobTitle() {
return jobTitle;
}
public Double getCompatibilityScore() {
return this.compatibilityScore;
}
public Integer getHeightInCm() {
return this.heightInCm;
}
public Integer getAge() {
return age;
}
public String getCityName() {
return city == null ? null : city.getName();
}
public Double getCityLatitude() {
return city == null ? null : city.getLat();
}
public Double getCityLongitude() {
return city == null ? null : city.getLon();
}
}
|
package action;
import dto.Cv;
import dto.Page;
import dto.Teacher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import repository.CvRepository;
import service.TeacherService;
import utils.WebResponse;
import utils.rest.annotation.Get;
import utils.rest.annotation.Post;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
/**
* Created by Esther on 2016/8/20.
*/
@Controller
@RequestMapping("/teacher")
public class TeacherAction {
@Resource
TeacherService teacherService;
@Resource
CvRepository cvRepository;
@Post("/list")
@ResponseBody
public HashMap<String, Object> list(@RequestBody Page page){
return teacherService.list(page);
}
@Get("/cv")
@ResponseBody
public WebResponse getCv(@RequestParam("id") Long id){
return WebResponse.success(cvRepository.selectCv(id));
}
@Get("/add")
@ResponseBody
public WebResponse addTeacher(@RequestParam("name")String name,@RequestParam("password") String password){
return WebResponse.success(teacherService.addTeacher(name, password));
}
@Get("deleteTea")
@ResponseBody
public WebResponse deleteTeacher(@RequestParam("id")Long id){
return WebResponse.success(teacherService.deleteTeacher(id));
}
@Get("login")
@ResponseBody
public WebResponse login(HttpServletRequest request,@RequestParam("name")String name,@RequestParam("password")String password){
Teacher teacher = new Teacher();
teacher.setName(name);
teacher.setPassword(password);
teacher = teacherService.login(teacher);
if(teacher==null){
return WebResponse.fail();
}
request.getSession().setAttribute("id", teacher.getId());
return WebResponse.success(teacher);
}
@Get("updatePassword")
@ResponseBody
public WebResponse updatePassword(HttpServletRequest request,@RequestParam("password")String password){
Long id=(Long)request.getSession().getAttribute("id");
Teacher teacher = new Teacher();
teacher.setId(id);
teacher.setPassword(password);
return WebResponse.success(teacherService.updatePassword(teacher));
}
@Get("isselect")
@ResponseBody
public WebResponse isselect(){
return WebResponse.success(teacherService.isselect());
}
@Get("getCV")
@ResponseBody
public WebResponse getCV(@RequestParam("id")Long id){
HashMap<String,Object> cv = new HashMap<String, Object>();
Teacher teacher = teacherService.selectById(id);
if(teacher.getCvid()==null){
cv.put("teacher",teacher);
return WebResponse.success(cv);
}else {
cv.put("teacher",teacher);
cv.put("cv", cvRepository.selectCv(teacher.getCvid()));
return WebResponse.success(cv);
}
}
@Post("updateTea")
@ResponseBody
public WebResponse updateTea(@RequestBody Teacher teacher){
return WebResponse.success(teacherService.updateInformation(teacher));
}
@Post("updateCV")
@ResponseBody
public WebResponse updateCV(@RequestBody Cv cv){
return WebResponse.success(cvRepository.updateCv(cv));
}
@Post("addCV")
@ResponseBody
public WebResponse addCV(HttpServletRequest request,@RequestBody Cv cv){
Long id=(Long)request.getSession().getAttribute("id");
Long cvid=cvRepository.addCv(cv);
if(teacherService.updateCvid(cvid,id)>0){
return WebResponse.success();
}
return WebResponse.fail();
}
/**
* 列出老师可以选择的学生列表
* @return
*/
@Post("listStudent")
@ResponseBody
public HashMap<String, Object> listStudent(HttpServletRequest request,@RequestBody Page page){
Long id=(Long)request.getSession().getAttribute("id");
return teacherService.listStudent(id, page);
}
/**
* 老师拒绝学生的申请
* @param studentid
* @return
*/
@Get("reject")
@ResponseBody
public WebResponse reject(@RequestParam("studentid")Long studentid){
return WebResponse.success(teacherService.nextTeacher(studentid));
}
/**
* 导师选择一个学生
* @param studentid
* @return
*/
@Get("selectStu")
@ResponseBody
public WebResponse selectStu(HttpServletRequest request,@RequestParam("studentid")Long studentid){
Long id=(Long)request.getSession().getAttribute("id");
return WebResponse.success(teacherService.selectStu(studentid, id));
}
/**
* 导师选择的学生列表
* @return
*/
@Post("selectStudents")
@ResponseBody
public HashMap<String, Object> selectStudents(HttpServletRequest request,@RequestBody Page page){
Long id=(Long)request.getSession().getAttribute("id");
return teacherService.selectStudents(id,page);
}
/**
* 加入后删除学生
* @param studentid
* @return
*/
@Get("deleteStu")
@ResponseBody
public WebResponse delete(HttpServletRequest request,@RequestParam("studentid")Long studentid){
Long id=(Long)request.getSession().getAttribute("id");
return WebResponse.success(teacherService.deleteStudent(studentid, id));
}
}
|
/**
* DNet eBusiness Suite
* Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package net.nan21.dnet.module.bd.business.impl.comment;
import java.util.List;
import javax.persistence.EntityManager;
import net.nan21.dnet.core.api.session.Session;
import net.nan21.dnet.core.business.service.entity.AbstractEntityService;
import net.nan21.dnet.module.bd.business.api.comment.ICommentService;
import net.nan21.dnet.module.bd.domain.impl.comment.Comment;
import net.nan21.dnet.module.bd.domain.impl.comment.CommentType;
/**
* Repository functionality for {@link Comment} domain entity. It contains
* finder methods based on unique keys as well as reference fields.
*
*/
public class Comment_Service extends AbstractEntityService<Comment>
implements
ICommentService {
public Comment_Service() {
super();
}
public Comment_Service(EntityManager em) {
super();
this.setEntityManager(em);
}
@Override
public Class<Comment> getEntityClass() {
return Comment.class;
}
/**
* Find by reference: type
*/
public List<Comment> findByType(CommentType type) {
return this.findByTypeId(type.getId());
}
/**
* Find by ID of reference: type.id
*/
public List<Comment> findByTypeId(String typeId) {
return (List<Comment>) this
.getEntityManager()
.createQuery(
"select e from Comment e where e.clientId = :clientId and e.type.id = :typeId",
Comment.class)
.setParameter("clientId",
Session.user.get().getClient().getId())
.setParameter("typeId", typeId).getResultList();
}
}
|
package genopt.ricardo.simulacao;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.TreeMap;
public final class RecordFile {
final Map<String, Float> records;
private static Float round(Float d, int decimalPlace) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.floatValue();
}
private RecordFile(Map<String, Float> records) {
this.records = records;
}
public RecordFile(String filePath) throws FileNotFoundException, IOException {
this.records = new TreeMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
addEntry(line);
}
}
}
private void addEntry(String line) {
if (line.contains("Date/Time")) {
return;
}
final String[] tokens = line.split(",");
records.put(tokens[0], Float.parseFloat(tokens[1]));
}
public RecordFile subtract(RecordFile other) {
final Map<String, Float> temp = new TreeMap<>();
for (Map.Entry<String, Float> e : this.records.entrySet()) {
final Float otherVal = other.records.get(e.getKey());
if (otherVal == null) {
System.err.println("Could not find the corresponding timestamp for " + e.getKey());
continue;
}
temp.put(e.getKey(), e.getValue() - otherVal);
}
return new RecordFile(temp);
}
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Date/Time,Subtracted Temperature \n");
for (Map.Entry<String, Float> e : this.records.entrySet()) {
sb.append(e.getKey() + "," + round(e.getValue(), 2) + "\n");
}
sb.append("\n");
return sb.toString();
}
}
|
package com.qy.zgz.kamiduo.Model;
/**
* 版本信息
*/
public class Version {
private int versionid;
private String url;
public int getVersionid() {
return versionid;
}
public void setVersionid(int versionid) {
this.versionid = versionid;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
package com.joakims.Abstraction;
import org.w3c.dom.css.Rect;
public class ShapeTester {
public static void main(String args[]) {
Rectangle rectangle = new Rectangle("Yellow", 10, 15);
Circle circle = new Circle("Black", 6);
Shape s = new Rectangle("Green", 5, 2);
System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Circle area: " + circle.getArea());
System.out.println(rectangle.draw());
System.out.println(circle.draw());
System.out.println(s.draw());
}
}
|
package edu.byu.cs.superasteroids.model;
import android.graphics.Rect;
/**
* Created by Azulius on 2/24/16.
*/
public class PositionedObject extends VisibleObject {
}
|
package com.services.utils.redis.objs;
import com.services.utils.redis.common.RedisBase;
import redis.clients.jedis.Jedis;
import redis.clients.util.SafeEncoder;
import java.util.List;
/**
* 对存储结构为String类型的操作
*/
public class Strings {
/**
* 根据key获取记录
*
* @param key
* @return 值
*/
public String get(String key) {
Jedis jedis = RedisBase.getJedis();
String redis_value;
try {
redis_value = jedis.get(key);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 根据key获取记录
*
* @param key
* @return 值
*/
private byte[] get(byte[] key) {
Jedis jedis = RedisBase.getJedis();
byte[] redis_value;
try {
redis_value = jedis.get(key);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 添加有过期时间的记录
*
* @param key
* @param seconds 过期时间,以秒为单位
* @param value
* @return String 操作状态
*/
public String setEx(String key, int seconds, String value) {
Jedis jedis = RedisBase.getJedis();
String redis_value;
try {
redis_value = jedis.setex(key, seconds, value);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 添加有过期时间的记录
*
* @param key
* @param seconds 过期时间,以秒为单位
* @param value
* @return String 操作状态
*/
private String setEx(byte[] key, int seconds, byte[] value) {
Jedis jedis = RedisBase.getJedis();
String redis_value;
try {
redis_value = jedis.setex(key, seconds, value);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 添加一条记录,仅当给定的key不存在时才插入
*
* @param key
* @param value
* @return long 状态码,1插入成功且key不存在,0未插入,key存在
*/
public long setnx(String key, String value) {
Jedis jedis = RedisBase.getJedis();
long redis_value;
try {
redis_value = jedis.setnx(key, value);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 添加记录,如果记录已存在将覆盖原有的value
*
* @param key
* @param value
* @return 状态码
*/
public String set(String key, String value) {
return set(SafeEncoder.encode(key), SafeEncoder.encode(value));
}
/**
* 添加记录,如果记录已存在将覆盖原有的value
*
* @param key
* @param value
* @return 状态码
*/
private String set(String key, byte[] value) {
return set(SafeEncoder.encode(key), value);
}
/**
* 添加记录,如果记录已存在将覆盖原有的value
*
* @param key
* @param value
* @return 状态码
*/
private String set(byte[] key, byte[] value) {
Jedis jedis = RedisBase.getJedis();
String redis_value;
try {
redis_value = jedis.set(key, value);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 从指定位置开始插入数据,插入的数据会覆盖指定位置以后的数据<br/>
* 例:String str1="123456789";<br/>
* 对str1操作后setRange(key,4,0000),str1="123400009";
*
* @param key
* @param offset
* @param value
* @return long value的长度
*/
public long setRange(String key, long offset, String value) {
Jedis jedis = RedisBase.getJedis();
long redis_value;
try {
redis_value = jedis.setrange(key, offset, value);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 在指定的key中追加value
*
* @param key
* @param value
* @return long 追加后value的长度
**/
public long append(String key, String value) {
Jedis jedis = RedisBase.getJedis();
long redis_value;
try {
redis_value = jedis.append(key, value);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 将key对应的value减去指定的值,只有value可以转为数字时该方法才可用
*
* @param key
* @param number 要减去的值
* @return long 减指定值后的值
*/
public long decrBy(String key, long number) {
Jedis jedis = RedisBase.getJedis();
long redis_value;
try {
redis_value = jedis.decrBy(key, number);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* <b>可以作为获取唯一id的方法</b><br/>
* 将key对应的value加上指定的值,只有value可以转为数字时该方法才可用
*
* @param key
* @param number 要减去的值
* @return long 相加后的值
*/
public long incrBy(String key, long number) {
Jedis jedis = RedisBase.getJedis();
long redis_value;
try {
redis_value = jedis.incrBy(key, number);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 对指定key对应的value进行截取
*
* @param key
* @param startOffset 开始位置(包含)
* @param endOffset 结束位置(包含)
* @return String 截取的值
*/
public String getrange(String key, long startOffset, long endOffset) {
Jedis jedis = RedisBase.getJedis();
String redis_value;
try {
redis_value = jedis.getrange(key, startOffset, endOffset);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 获取并设置指定key对应的value<br/>
* 如果key存在返回之前的value,否则返回null
*
* @param key
* @param value
* @return String 原始value或null
*/
public String getSet(String key, String value) {
Jedis jedis = RedisBase.getJedis();
String redis_value;
try {
redis_value = jedis.getSet(key, value);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 批量获取记录,如果指定的key不存在返回List的对应位置将是null
*
* @param keys
* @return List<String> 值得集合
*/
public List<String> mget(String... keys) {
Jedis jedis = RedisBase.getJedis();
List<String> redis_value;
try {
redis_value = jedis.mget(keys);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 批量存储记录
*
* @param keysvalues 例:keysvalues="key1","value1","key2","value2";
* @return String 状态码
*/
public String mset(String... keysvalues) {
Jedis jedis = RedisBase.getJedis();
String redis_value;
try {
redis_value = jedis.mset(keysvalues);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
/**
* 获取key对应的值的长度
*
* @param key
* @return value值得长度
*/
public long strlen(String key) {
Jedis jedis = RedisBase.getJedis();
long redis_value;
try {
redis_value = jedis.strlen(key);
} finally {
RedisBase.returnJedis(jedis);
}
return redis_value;
}
} |
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 notXX
* luma <stubma@163.com>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.qq.net;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import edu.tsinghua.lumaqq.qq.packets.OutPacket;
import edu.tsinghua.lumaqq.qq.packets.PacketParseException;
/**
* 发送接收包的接口.
*
* @author notxx
* @author luma
*/
public interface IPort extends IConnection {
/**
* 获得对应的通道
*
* @return 对应的通道
*/
public SelectableChannel channel();
/**
* @return
* NIO事件处理器
*/
public INIOHandler getNIOHandler();
/**
* @return
* 发送队列中的下一个包,如果没有,返回null
*/
public OutPacket remove();
/**
* 发送队列是否是空的
*
* @return 是空的返回true, 否则返回false
*/
public boolean isEmpty();
/**
* 接收一个包到接收队列
*
* @return 如果还有数据可以接收返回true, 否则返回false.
* @throws IOException
* 一般IO错误.
* @throws PacketParseException
* 包格式错误.
*/
public void receive() throws IOException, PacketParseException;
/**
* 从发送队列发送一个包.
*
* @return 如果还有包需要发送返回true, 否则返回false.
* @throws IOException
* 一般IO错误.
*/
public void send() throws IOException;
/**
* 立即发送一个包,不添加到发送队列
* @param packet
*/
public void send(OutPacket packet);
/**
* 立即发送ByteBuffer中的内容,不添加到发送队列
* @param buffer
*/
public void send(ByteBuffer buffer);
/**
* @return true表示已经连接上
*/
public boolean isConnected();
} |
package com.elvarg.world.entity.combat.hit;
/**
* Represents a Hit mask type/color.
* @author Gabriel Hannason
*/
public enum HitMask {
BLUE,
RED,
GREEN,
YELLOW;
} |
/*
* 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 simplechatexample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import static simplechatexample.simpleChatexample.end;
/**
*
* @author anwar
*/
public class simpleChatServerSocket extends Thread{
Socket client=null;
ServerSocket server=null;
public simpleChatServerSocket(int port){
try {
server=new ServerSocket(port);
} catch (IOException ex) {
Logger.getLogger(simpleChatServerSocket.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run() {
try {
client=server.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
String input;
// new ChatClientSocket("192.168.0.104",2000).start();
while(true){
input=in.readLine();
System. out.println("chatServer1 : "+input);
if(input.equalsIgnoreCase("exit") || end.equalsIgnoreCase("exit"))
{
end="exit";
break;
}
}
in.close();
client.close();
server.close();
System.out.println("close");
} catch (IOException ex) {
Logger.getLogger(simpleChatServerSocket.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
package Exerciese526;
import java.util.Scanner;
import java.util.Stack;
public class DeleteK_min {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Stack<Integer> stack = new Stack<>();
while (scanner.hasNext()) {
stack.push(scanner.nextInt());
}
int length = stack.size();
int[] data = new int[length];
for (int i = 0; i < length; i++) {
data[i] = stack.pop();
}
int k = data[length-2];
}
}
|
package com.restapi.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Newspaper") // Response Status: 404
public class NewspaperNotFoundException extends RuntimeException {
/**
* Unique ID for Serialized object
*/
private static final long serialVersionUID = -8790211652911971729L;
public NewspaperNotFoundException(Long newspaperId) {
super("The newspaper with id " + newspaperId + " doesn't exist");
}
}
|
package com.ajay.TIAA;
import java.util.Arrays;
public class ArrayCyclRoration {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
int n = 2;
cyclRotate(arr, n);
}
private static void cyclRotate(int[] arr, int n) {
int rot = 0;
while (rot != n) {
int element = arr[arr.length - 1];
for (int i = arr.length - 2; i >= 0; i--) {
arr[i + 1] = arr[i];
}
arr[0] = element;
rot++;
}
System.out.println(Arrays.toString(arr));
}
}
|
package com.pineapple.mobilecraft.tumcca.fragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.pineapple.mobilecraft.R;
import com.pineapple.mobilecraft.TumccaApplication;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
/**
* 要使用BaseListFragment,要实现{@link ListItem}, {@link ItemLoader}, {@link ListViewHolder}
* 如果要扩展BaseListFragment,请继承BaseListFragment,并在自己的layout中include fragment_base_list.xml
*
*/
public class BaseListFragment<VH extends BaseListFragment.ListViewHolder>extends Fragment {
public interface ListItem {
/**
* 用于将数据绑定到viewHolder上显示
* @param viewHolder
*/
public void bindViewHolder(BaseListFragment.ListViewHolder viewHolder);
/**
* 创建一个ViewHolder
*
* @param
* @return
*/
public BaseListFragment.ListViewHolder getViewHolder(LayoutInflater inflater);
/**
* 返回item id
* @return
*/
public long getId();
}
/**
* 数据加载器
*/
public interface ItemLoader {
/**
* 该方法在子线程中调用,加载头部数据,当用户下拉list时,或者本Fragment第一次载入时,会调用此方法
*/
public List<ListItem> loadHead();
/**
* 该方法在子线程中调用,当用户上滑list时,加载尾部数据。
*/
public List<ListItem> loadTail(int page);
}
/**
* 在原有ViewHolder基础之上扩展,可以获取ViewHolder关联的Fragment
*/
public static abstract class ListViewHolder extends RecyclerView.ViewHolder{
BaseListFragment mFragment = null;
public ListViewHolder(View itemView) {
super(itemView);
}
public BaseListFragment getFragment(){
return mFragment;
}
}
/**
* 普通模式
*/
public static final int MODE_NORMAL = 0;
/**
* 可以上下拖动
*/
public static final int MODE_PULL_DRAG = 1;
/**
* 固定高度,高度根据包含的item数量调整
*/
public static final int MODE_FIXED_HEIGHT = 2;
/**
* LayoutManager 暂时只包括LinearLayoutManager即ListView
*/
private LinearLayoutManager mlayoutManager;
/**
* 数据载入模式,默认为普通模式
*/
int mLoadMode = MODE_NORMAL;
/**
* 下拉加载控件
*/
SwipeRefreshLayout mSwipeRefreshLayout;
/**
* ListView控件
*/
RecyclerView mRecyclerView;
ItemLoader mItemLoader;
BaseListAdapter mAdapter;
/**
* 数据容器
*/
List<ListItem> mItems = new ArrayList<ListItem>();
/**
* Fragment所属的Activity
*/
Activity mActivity;
boolean mScrollingIdle = false;
/**
* 数据当前的页面数
*/
int mCurrentPage = 1;
/**
* layout文件id
*/
int mLayoutId = 0;
public BaseListFragment() {
// Required empty public constructor
mAdapter = new BaseListAdapter();
mLayoutId = R.layout.fragment_base_list;
}
/**
* 用于扩展类使用,可以加载自定义的layout
* @param layoutId
*/
protected void setLayout(int layoutId){
mLayoutId = layoutId;
}
public void setMode(int mode) {
if (mode >= MODE_NORMAL && mode <= MODE_FIXED_HEIGHT) {
mLoadMode = mode;
}
}
public void setItemLoader(ItemLoader loader) {
mItemLoader = loader;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
@Override
public void onStart() {
super.onStart();
if (null != mItemLoader) {
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
addHead(mItemLoader.loadHead());
}
});
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(mLayoutId, container, false);
buildView(view, savedInstanceState);
return view;
}
/**
* 子类重载此方法来进行扩展
* @param view
*/
protected void buildView(View view, Bundle savedInstanceState){
//设置SwipeRefreshLayout
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
if (mLoadMode == MODE_PULL_DRAG) {
mSwipeRefreshLayout.setColorSchemeResources(R.color.button_normal_red);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (null != mItemLoader) {
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
addHead(mItemLoader.loadHead());
}
});
}
mSwipeRefreshLayout.setRefreshing(false);
}
});
} else {
mSwipeRefreshLayout.setEnabled(false);
}
//设置RecyclerView,Adapter
mAdapter = new BaseListAdapter();
mlayoutManager = new LinearLayoutManager(mActivity);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(mlayoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int visibleItemCount = mlayoutManager.getChildCount();
int totalItemCount = mlayoutManager.getItemCount();
int pastVisibleItems = mlayoutManager.findFirstVisibleItemPosition();
if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
if (null != mItemLoader && mLoadMode == MODE_PULL_DRAG) {
mScrollingIdle = false;
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
addTail(mItemLoader.loadTail(++mCurrentPage));
}
});
}
}
}
});
}
public void applyListviewHeightWithChild(){
int listViewHeight = 0;
int adaptCount = mAdapter.getItemCount();
for(int i=0;i<adaptCount;i++){
View temp = mAdapter.createViewHolder(null, 0).itemView;
temp.measure(0,0);
listViewHeight += temp.getMeasuredHeight();
Log.v(TumccaApplication.TAG, "BaseListFragment:applyListviewHeightWithChild:Height=" + listViewHeight);
}
ViewGroup.LayoutParams layoutParams = this.mRecyclerView.getLayoutParams();
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
//int expandSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);
//super.onMeasure(widthMeasureSpec, expandSpec);
layoutParams.height = listViewHeight;
mRecyclerView.setLayoutParams(layoutParams);
}
/**
* 获取所有数据
* @return
*/
public final List<ListItem> getItems(){
return mItems;
}
/**
* 暂时没有用
*/
public void update(){
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
/**
* 清除数据,数据清除完后,会重新调用loadHead,加载数据
*/
public void reload(){
if(null != mActivity){
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mItems.clear();
}
});
if(mItemLoader!=null){
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
addHead(mItemLoader.loadHead());
}
});
}
}
}
public void remove(long id){
for(ListItem item:mItems){
if(item.getId() == id){
mItems.remove(item);
break;
}
}
refresh();
}
public void refresh(){
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
public Activity getFragmentActivity(){
return mActivity;
}
private class BaseListAdapter extends RecyclerView.Adapter<VH> {
@Override
public VH onCreateViewHolder(ViewGroup viewGroup, int i) {
return (VH) mItems.get(0).getViewHolder(mActivity.getLayoutInflater());
}
@Override
public void onBindViewHolder(VH viewHolder, int i) {
viewHolder.mFragment = BaseListFragment.this;
mItems.get(i).bindViewHolder(viewHolder);
}
@Override
public int getItemCount() {
return mItems.size();
}
}
private void addHead(final List<ListItem> list) {
if (null != list) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mItems.size() > 0) {
//过滤掉重复的数据
long topId = mItems.get(0).getId();
int index = mItems.size();
for (int i = 0; i < mItems.size(); i++) {
if (topId == mItems.get(i).getId()) {
index = i;
break;
}
}
if (mItems.subList(0, index).size() == 0) {
//Toast.makeText(mContext, getString(R.string.there_is_no_new_works), Toast.LENGTH_SHORT).show();
} else {
//Toast.makeText(mContext, getString(R.string.there_is_works, albumList.subList(0, index).size()), Toast.LENGTH_SHORT).show();
mItems.addAll(0, mItems.subList(0, index));
}
} else {
mItems.addAll(list);
}
if(mLoadMode == MODE_FIXED_HEIGHT){
applyListviewHeightWithChild();
}
mAdapter.notifyDataSetChanged();
}
});
}
}
private void addTail(final List<ListItem> list) {
if (null != list) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mItems.addAll(list);
if(mLoadMode == MODE_FIXED_HEIGHT){
applyListviewHeightWithChild();
}
mAdapter.notifyDataSetChanged();
}
});
}
}
}
|
package br.caelum.vraptor.controller;
import static br.com.caelum.vraptor.view.Results.json;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Time;
import java.util.List;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import com.sun.jmx.snmp.Timestamp;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.blank.IndexController;
import br.com.caelum.vraptor.dao.CategoriaDao;
import br.com.caelum.vraptor.dao.PlaylistDao;
import br.com.caelum.vraptor.dao.UsuarioWeb;
import br.com.caelum.vraptor.dao.VideoDao;
import br.com.caelum.vraptor.infra.Arquivo;
import br.com.caelum.vraptor.interceptor.multipart.UploadedFile;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.models.Categoria;
import br.com.caelum.vraptor.models.Playlist;
import br.com.caelum.vraptor.models.Usuario;
import br.com.caelum.vraptor.models.Video;
import br.com.caelum.vraptor.view.Results;
import br.com.caelum.vraptor.view.Status;
@Resource
public class PlaylistsController {
private final PlaylistDao dao;
private final Result result;
private final ServletContext context;
private final HttpServletRequest request;
private final HttpServletResponse response;
private final UsuarioWeb usuarioWeb;
public PlaylistsController(PlaylistDao dao, Result result, final ServletContext context, HttpServletRequest request, HttpServletResponse response, UsuarioWeb usuarioWeb) {
this.dao = dao;
this.result = result;
this.context = context;
this.request = request;
this.response = response;
this.usuarioWeb = usuarioWeb;
}
public void adiciona(Playlist playlist, UploadedFile foto, long categoria_id) {
Categoria categoria = new Categoria();
categoria.setId(categoria_id);
playlist.setCategoria(categoria);
Timestamp timestampObj = new Timestamp();
long timeStamp = timestampObj.getDateTime();
Arquivo arquivoCapa = new Arquivo(foto, "playlists", timeStamp);
arquivoCapa.salvaArquivo();
playlist.setImagemCapa(timeStamp + foto.getFileName());
Usuario usuario = new Usuario();
usuario.setId(this.usuarioWeb.getId());
playlist.setUsuario(usuario);
dao.salva(playlist);
result.include("notice", "Playlist criada com sucesso!");
//result.redirectTo(this).lista();
result.redirectTo(IndexController.class).index();
}
public void formulario(){
}
public Playlist edita(Long id){
return dao.carrega(id);
}
public void altera(Playlist playlist) {
dao.atualiza(playlist);
result.include("notice", "Playlist alterada com sucesso!");
result.redirectTo(this).lista();
}
public void remove(Long id) {
Playlist playlist = dao.carrega(id);
dao.remove(playlist);
result.include("notice", "Playlist removida com sucesso!");
result.redirectTo(this).lista();
}
public List<Playlist> lista() {
return dao.listaTudo();
}
//busca
public void busca(){}
public List<Playlist> buscaPlaylist(String nome) {
result.include("nome", nome);
return dao.busca(nome);
//result.redirectTo(PlaylistsController.class).busca();
}
@Path("/playlists/listajson/{playlistId}")
public void listajson(long playlistId){
Status resultStatus = result.use(Results.status());
resultStatus.header("Access-Control-Allow-Origin", "*");
VideoDao vd = new VideoDao();
List<Video> videos = vd.listaPorPlaylist(playlistId);
result.use(json()).from(videos, "videos").serialize();
}
}
|
package cd.com.a.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import cd.com.a.model.admin_noticeDto;
import cd.com.a.service.admin_noticeService;
import cd.com.a.util.FileUploadUtil;
@Controller
public class noticeController {
@Autowired
admin_noticeService noticeService;
@RequestMapping(value="adminNotice.do", method=RequestMethod.GET)
public String adminNotice(Model model) {
return "admin/notice/notice_main";
}
@GetMapping(value="adminNoticeWrite.do")
public String write_get() {
//
return "admin/notice/notice_insert2";
}
@PostMapping(value="adminNoticeWriteAf.do", consumes ={"multipart/form-data"})
@ResponseBody
//@ModelAttribute 자동으로 dto로 넣어준다
//@RequestParam(value="ajaxContents",required=false) String contents,
//@RequestParam(value="title", required=false) String title,
public String writeAf(
@ModelAttribute admin_noticeDto adminNoticeDto,
@RequestParam(value = "files", required=false)MultipartFile[] files,
MultipartHttpServletRequest req) {
System.out.println("toString = " + adminNoticeDto.toString());
//DB에 보관할 문자열을 만들 변수 선언
String server_filename = "";
String filename = "";
boolean isError = true;
//파일 업로드 경로 설정
String fupload = req.getSession().getServletContext().getRealPath("/");
fupload += "upload\\notice";
System.out.println("upload 경로 = " + fupload);
// filename 취득
System.out.println("files size = " + files.length);
for(int i = 0; i < files.length; i++) {
if(files[i].getOriginalFilename() != null && files[i].getOriginalFilename() != "") {
System.out.println("i = " + i + " fileName = " + files[i].getOriginalFilename());
filename += "" + files[i].getOriginalFilename() + "&";
String newFileName = FileUploadUtil.getNewFileName(files[i].getOriginalFilename());
server_filename += newFileName + "&";
//파일 생성
File file = new File(fupload + "/" + newFileName);
//파일 업로드
try {
FileUtils.writeByteArrayToFile(file, files[i].getBytes());
System.out.println("파일 업로드!");
} catch (IOException e) {
System.out.println("noticeController / writeAf.do method / FileUtils error");
isError = false;
e.printStackTrace();
return String.valueOf(isError);
}
}
}
/* 업로드 파일 확인용 코드
try {
File file2 = new File(fupload + "/" + "1586769707808.txt");
Scanner scan = new Scanner(file2);
while(scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
if(filename.length() > 0) {
//마지막 '&' 제거
filename = filename.substring(0, filename.length()-1);
server_filename = server_filename.substring(0, server_filename.length()-1);
}
System.out.println("origin FileName = " + filename);
System.out.println("server FileName = " + server_filename);
adminNoticeDto.setNotice_filename(filename);
adminNoticeDto.setNotice_server_filename(server_filename);
System.out.println("모든 업로드 종료 후 dto 확인 = " + adminNoticeDto.toString());
isError = noticeService.notice_insert(adminNoticeDto);
return String.valueOf(isError);
}
}
|
package com.tencent.mm.plugin.fts.b;
import com.tencent.mm.plugin.fts.a.a.a;
import com.tencent.mm.plugin.fts.c.c;
class c$d extends a {
private String gBf;
final /* synthetic */ c jux;
public c$d(c cVar, String str) {
this.jux = cVar;
this.gBf = str;
}
public final boolean execute() {
c cVar = this.jux.jup;
String str = this.gBf;
cVar.jvj.bindLong(1, -1);
cVar.jvj.bindString(2, str);
cVar.jvj.bindLong(3, -1);
cVar.jvj.execute();
return true;
}
public final String afC() {
return String.format("{conversation: %s}", new Object[]{this.gBf});
}
public final String getName() {
return "DeleteTalkerTask";
}
}
|
package com.ppdai.framework.raptor.spring.utils;
import com.ppdai.framework.raptor.annotation.RaptorInterface;
import com.ppdai.framework.raptor.annotation.RaptorMessage;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* @author yinzuolong
*/
@Slf4j
public class ProtoFileResourceUtils {
@Data
public static class ProtoFileInfo {
private String fileName;
private String packageName;
private String content;
public String getFullName() {
return StringUtils.isEmpty(packageName) ? fileName : packageName + "." + fileName;
}
}
private static Map<String, ProtoFileInfo> PROTO_FILE_CACHE = new ConcurrentReferenceHashMap<>();
public static ProtoFileInfo findInterfaceProtoFile(Class<?> raptorInterface, ClassLoader classLoader) {
if (raptorInterface != null) {
RaptorInterface annotation = AnnotationUtils.findAnnotation(raptorInterface, RaptorInterface.class);
if (annotation != null) {
return findProtoFile(raptorInterface.getPackage().getName(), annotation.protoFile(), classLoader);
}
}
return null;
}
public static ProtoFileInfo findMessageProtoFile(Class<?> messageClass, ClassLoader classLoader) {
RaptorMessage annotation = AnnotationUtils.findAnnotation(messageClass, RaptorMessage.class);
if (annotation != null) {
return findProtoFile(messageClass.getPackage().getName(), annotation.protoFile(), classLoader);
}
return null;
}
public static List<ProtoFileInfo> findProtoFilesByMessage(List<Class<?>> messageClasses, ClassLoader classLoader) {
Set<ProtoFileInfo> results = new LinkedHashSet<>();
Set<Class<?>> founds = new HashSet<>();
for (Class<?> messageClass : messageClasses) {
Set<ProtoFileInfo> messageProtoFiles = findProtoFilesByMessage(messageClass, founds, classLoader);
results.addAll(messageProtoFiles);
}
return new ArrayList<>(results);
}
private static Set<ProtoFileInfo> findProtoFilesByMessage(Class<?> messageClass, Set<Class<?>> founds, ClassLoader classLoader) {
Set<ProtoFileInfo> results = new HashSet<>();
ProtoFileInfo protoFileInfo = findMessageProtoFile(messageClass, classLoader);
if (protoFileInfo != null && !founds.contains(messageClass)) {
results.add(protoFileInfo);
founds.add(messageClass);
Field[] fields = messageClass.getDeclaredFields();
for (Field field : fields) {
Class<?> fieldType = field.getType();
RaptorMessage annotation = AnnotationUtils.findAnnotation(fieldType, RaptorMessage.class);
ResolvableType resolvableType = ResolvableType.forField(field);
if (annotation != null) {
Set<ProtoFileInfo> filedMessageProtoFiles = findProtoFilesByMessage(fieldType, founds, classLoader);
results.addAll(filedMessageProtoFiles);
} else if (List.class.isAssignableFrom(fieldType)) {
ResolvableType genericType = resolvableType.getGeneric(0);
results.addAll(findProtoFilesByMessage(genericType.getRawClass(), founds, classLoader));
} else if (Map.class.isAssignableFrom(fieldType)) {
ResolvableType keyType = resolvableType.getGeneric(0);
ResolvableType valueType = resolvableType.getGeneric(1);
results.addAll(findProtoFilesByMessage(keyType.getRawClass(), founds, classLoader));
results.addAll(findProtoFilesByMessage(valueType.getRawClass(), founds, classLoader));
}
}
}
return results;
}
public static ProtoFileInfo findProtoFile(String packageName, String fileName, ClassLoader classLoader) {
fileName = StringUtils.endsWithIgnoreCase(fileName, ".proto") ? fileName : fileName + ".proto";
String resource = packageName.replace(".", "/") + "/" + fileName;
if (PROTO_FILE_CACHE.get(resource) != null) {
return PROTO_FILE_CACHE.get(resource);
}
ProtoFileInfo protoFileInfo = new ProtoFileInfo();
protoFileInfo.setFileName(fileName);
protoFileInfo.setPackageName(packageName);
if (classLoader == null) {
classLoader = ProtoFileResourceUtils.class.getClassLoader();
}
try (InputStream in = classLoader.getResourceAsStream(resource)) {
String content = StreamUtils.copyToString(in, StandardCharsets.UTF_8);
protoFileInfo.setContent(content);
PROTO_FILE_CACHE.put(resource, protoFileInfo);
return protoFileInfo;
} catch (Exception e) {
log.error("Read proto file [{}] error.", resource, e);
}
return null;
}
}
|
package com.tencent.mm.plugin.subapp.ui.friend;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.tencent.mm.R;
import com.tencent.mm.plugin.subapp.ui.friend.FMessageConversationUI.a;
class FMessageConversationUI$5 extends BaseAdapter {
final /* synthetic */ FMessageConversationUI ose;
FMessageConversationUI$5(FMessageConversationUI fMessageConversationUI) {
this.ose = fMessageConversationUI;
}
public final View getView(int i, View view, ViewGroup viewGroup) {
a aVar;
if (view == null || view.getTag() == null) {
view = LayoutInflater.from(this.ose.mController.tml).inflate(R.i.fmessage_conversation_empty_list_item, null);
aVar = new a(this.ose, view);
view.setTag(aVar);
} else {
aVar = (a) view.getTag();
}
if (i == 0) {
aVar.gwj.setImageResource(R.k.find_more_friend_mobile_icon);
aVar.eGX.setText(R.l.find_friends_by_mobile);
}
return view;
}
public final long getItemId(int i) {
return (long) i;
}
public final Object getItem(int i) {
return Integer.valueOf(i);
}
public final int getCount() {
return 1;
}
}
|
package com.travelportal.vm;
import java.util.ArrayList;
import java.util.List;
import com.travelportal.domain.HotelMealPlan;
public class HotelSearch {
public Long supplierCode;
public String hotelNm;
public String supplierNm;
public String hotelAddr;
public String hoteldescription;
public String hotel_email;
public String imgPaths;
public String imgDescription;
public String checkIn;
public String checkOut;
public int nationality;
public String nationalityName;
public int countryCode;
public String countryName;
public int cityCode;
public String cityName;
public int startRating;
public Double stars;
public Double currencyExchangeRate;
public String hotelBuiltYear;
public String checkInTime;
public String checkInTimeType;
public String checkOutTime;
public String checkOutTimeType;
public String roomVoltage;
public int cancellation_date_diff;
public String bookingId;
public int currencyId;
public String currencyName;
public String currencyShort;
public String agentCurrency;
public Double minRate;
/*public Set<HotelamenitiesVM> amenities;*/
public List<Integer> services1;
public List<ServicesVM> services;
public HotelBookingDetailsVM hotelBookingDetails;
public long datediff;
public String breakfackRate;
public String perferhotel;
public BatchMarkupInfoVM batchMarkup;
public List<SerachHotelRoomType> hotelbyRoom = new ArrayList<>();
public List<SerachedHotelbyDate> hotelbyDate;
public List<HotelMealPlan> mealPlan;
public SpecificMarkupInfoVM markup;
public Double mealCompulsory;
public Double availableLimit;
public String paymentType;
public String agentName;
//public String flag;
public Long getSupplierCode() {
return supplierCode;
}
public void setSupplierCode(Long supplierCode) {
this.supplierCode = supplierCode;
}
public String getHotelNm() {
return hotelNm;
}
public void setHotelNm(String hotelNm) {
this.hotelNm = hotelNm;
}
public String getSupplierNm() {
return supplierNm;
}
public void setSupplierNm(String supplierNm) {
this.supplierNm = supplierNm;
}
public String getHotelAddr() {
return hotelAddr;
}
public void setHotelAddr(String hotelAddr) {
this.hotelAddr = hotelAddr;
}
public int getCountryCode() {
return countryCode;
}
public void setCountryCode(int countryCode) {
this.countryCode = countryCode;
}
public int getCityCode() {
return cityCode;
}
public void setCityCode(int cityCode) {
this.cityCode = cityCode;
}
public int getStartRating() {
return startRating;
}
public void setStartRating(int startRating) {
this.startRating = startRating;
}
public List<SerachedHotelbyDate> getHotelbyDate() {
return hotelbyDate;
}
public void setHotelbyDate(List<SerachedHotelbyDate> hotelbyDate) {
this.hotelbyDate = hotelbyDate;
}
public List<SerachHotelRoomType> getHotelbyRoom() {
return hotelbyRoom;
}
public void setHotelbyRoom(List<SerachHotelRoomType> hotelbyRoom) {
this.hotelbyRoom = hotelbyRoom;
}
public String getImgPaths() {
return imgPaths;
}
public void setImgPaths(String imgPaths) {
this.imgPaths = imgPaths;
}
public String getImgDescription() {
return imgDescription;
}
public void setImgDescription(String imgDescription) {
this.imgDescription = imgDescription;
}
public String getCheckIn() {
return checkIn;
}
public void setCheckIn(String checkIn) {
this.checkIn = checkIn;
}
public String getCheckOut() {
return checkOut;
}
public void setCheckOut(String checkOut) {
this.checkOut = checkOut;
}
public int getNationality() {
return nationality;
}
public void setNationality(int nationality) {
this.nationality = nationality;
}
/*public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}*/
public List<Integer> getServices1() {
return services1;
}
public void setServices1(List<Integer> services1) {
this.services1 = services1;
}
public List<ServicesVM> getServices() {
return services;
}
public void setServices(List<ServicesVM> services) {
this.services = services;
}
public String getHoteldescription() {
return hoteldescription;
}
public void setHoteldescription(String hoteldescription) {
this.hoteldescription = hoteldescription;
}
/*public Set<HotelamenitiesVM> getAmenities() {
return amenities;
}
public void setAmenities(Set<HotelamenitiesVM> amenities) {
this.amenities = amenities;
}*/
public HotelBookingDetailsVM getHotelBookingDetails() {
return hotelBookingDetails;
}
public void setHotelBookingDetails(HotelBookingDetailsVM hotelBookingDetails) {
this.hotelBookingDetails = hotelBookingDetails;
}
public long getDatediff() {
return datediff;
}
public void setDatediff(long datediff) {
this.datediff = datediff;
}
public Double getStars() {
return stars;
}
public void setStars(Double stars) {
this.stars = stars;
}
public String getPerferhotel() {
return perferhotel;
}
public void setPerferhotel(String perferhotel) {
this.perferhotel = perferhotel;
}
public SpecificMarkupInfoVM getMarkup() {
return markup;
}
public void setMarkup(SpecificMarkupInfoVM markup) {
this.markup = markup;
}
public BatchMarkupInfoVM getBatchMarkup() {
return batchMarkup;
}
public void setBatchMarkup(BatchMarkupInfoVM batchMarkup) {
this.batchMarkup = batchMarkup;
}
public List<HotelMealPlan> getMealPlan() {
return mealPlan;
}
public void setMealPlan(List<HotelMealPlan> mealPlan) {
this.mealPlan = mealPlan;
}
public String getNationalityName() {
return nationalityName;
}
public void setNationalityName(String nationalityName) {
this.nationalityName = nationalityName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getBreakfackRate() {
return breakfackRate;
}
public void setBreakfackRate(String breakfackRate) {
this.breakfackRate = breakfackRate;
}
public String getHotelBuiltYear() {
return hotelBuiltYear;
}
public void setHotelBuiltYear(String hotelBuiltYear) {
this.hotelBuiltYear = hotelBuiltYear;
}
public String getCheckInTime() {
return checkInTime;
}
public void setCheckInTime(String checkInTime) {
this.checkInTime = checkInTime;
}
public String getCheckOutTime() {
return checkOutTime;
}
public void setCheckOutTime(String checkOutTime) {
this.checkOutTime = checkOutTime;
}
public String getRoomVoltage() {
return roomVoltage;
}
public void setRoomVoltage(String roomVoltage) {
this.roomVoltage = roomVoltage;
}
public int getCancellation_date_diff() {
return cancellation_date_diff;
}
public void setCancellation_date_diff(int cancellation_date_diff) {
this.cancellation_date_diff = cancellation_date_diff;
}
public Double getCurrencyExchangeRate() {
return currencyExchangeRate;
}
public void setCurrencyExchangeRate(Double currencyExchangeRate) {
this.currencyExchangeRate = currencyExchangeRate;
}
public String getAgentCurrency() {
return agentCurrency;
}
public void setAgentCurrency(String agentCurrency) {
this.agentCurrency = agentCurrency;
}
public Double getMealCompulsory() {
return mealCompulsory;
}
public void setMealCompulsory(Double mealCompulsory) {
this.mealCompulsory = mealCompulsory;
}
public String getHotel_email() {
return hotel_email;
}
public void setHotel_email(String hotel_email) {
this.hotel_email = hotel_email;
}
public Double getAvailableLimit() {
return availableLimit;
}
public void setAvailableLimit(Double availableLimit) {
this.availableLimit = availableLimit;
}
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getAgentName() {
return agentName;
}
public void setAgentName(String agentName) {
this.agentName = agentName;
}
public String getCheckInTimeType() {
return checkInTimeType;
}
public void setCheckInTimeType(String checkInTimeType) {
this.checkInTimeType = checkInTimeType;
}
public String getCheckOutTimeType() {
return checkOutTimeType;
}
public void setCheckOutTimeType(String checkOutTimeType) {
this.checkOutTimeType = checkOutTimeType;
}
}
|
package com.yeahbunny.stranger.server.services.impl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.ZonedDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.yeahbunny.stranger.server.exception.LoadPhotoException;
import com.yeahbunny.stranger.server.exception.PhotoStoreException;
import com.yeahbunny.stranger.server.services.PhotoService;
@Service
public class PhotoServiceImpl implements PhotoService{
private static final Logger LOG = LoggerFactory.getLogger(PhotoServiceImpl.class);
@Value("${app.photo.root_directory_path}")
private String rootDirectoryPath;
@Value("${app.photo.directory_separator}")
private String directorySeparator;
@Value("${app.photo.image_format}")
private String imageFormat;
@Value("${app.photo.file_data_separator}")
private String fileDataSeparator;
@Value("${app.backend_host}")
private String backendHost;
@Value("${app.photo.endpoint_path}")
private String photoEndpointPath;
@Override
public String saveFile(MultipartFile file, Long userId) {
String fileName = createPhotoName(userId);
String serverPath = storeFile(file, fileName);
String externalPhotoUrl = createExternalUrl(fileName);
LOG.debug("File {} stored {} url {}", fileName, serverPath, externalPhotoUrl);
return externalPhotoUrl;
}
private String createPhotoName(Long userId) {
ZonedDateTime storeFileDateTime = ZonedDateTime.now();
StringBuilder sb = new StringBuilder();
sb.append(userId);
sb.append(fileDataSeparator);
sb.append(storeFileDateTime.toInstant().toEpochMilli());
sb.append(fileDataSeparator);
sb.append("sep");
sb.append(imageFormat);
return sb.toString();
}
private String storeFile(MultipartFile file, String fileName) {
File directory = new File(rootDirectoryPath);
handleDirectoryOpenError(directory);
String serverPath = createServerFilePath(fileName);
LOG.info("Storing file: {}", serverPath);
try(FileOutputStream stream = new FileOutputStream(serverPath)) {
stream.write(file.getBytes());
}catch (SecurityException e){
e.printStackTrace();
throw new PhotoStoreException("STORE_SECURITY_EXCEPTION");
}catch (FileNotFoundException e){
e.printStackTrace();
throw new PhotoStoreException("FILE_NOT_FOUND_EXCEPTION");
}catch (IOException e){
e.printStackTrace();
throw new PhotoStoreException("IO_EXCEPTION");
}
return serverPath;
}
private String createExternalUrl(String fileName) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("http://");
stringBuilder.append(backendHost);
stringBuilder.append(photoEndpointPath);
stringBuilder.append(fileName);
return stringBuilder.toString();
}
private String createServerFilePath(String fileName) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(rootDirectoryPath);
stringBuilder.append(directorySeparator);
stringBuilder.append(fileName);
return stringBuilder.toString();
}
private void handleDirectoryOpenError(File directory) {
if (!directory.exists()){
try{
boolean result = directory.mkdirs();
if(!result){
LOG.error("directory.mkdirs() == false");
throw new PhotoStoreException("DIRECTORIES_CREATE_EXCEPTION");
}
LOG.debug("directories {}", rootDirectoryPath);
}catch (SecurityException e){
e.printStackTrace();
throw new PhotoStoreException("SECURITY_EXCEPTION");
}
}
}
@Override
public byte[] load(String fileName) {
String serverPath = createServerFilePath(fileName);
Path path = Paths.get(serverPath);
try {
return Files.readAllBytes(path);
} catch (IOException e) {
e.printStackTrace();
throw new LoadPhotoException(fileName + "does not exist");
}
}
}
|
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/**
*
* @author SIDDIQ SAMI
*/
public class Signin extends HttpServlet
{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String uname = request.getParameter("user");
String pwd = request.getParameter("pass");
if(checkUser(uname, pwd))
{
RequestDispatcher rs = request.getRequestDispatcher("Start");
rs.forward(request, response);
}
else
{
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
out.println("<html><head></head><body onload=\"alert('Username or Password incorrect')\"></body></html>");
}
}
public static boolean checkUser(String uname,String pwd)
{
boolean st=false;
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Intrepido1","root","aysha");
PreparedStatement ps =con.prepareStatement("select User_name,Password from Register where User_name=? and Password=?");
if(uname.isEmpty() || pwd.isEmpty())
{
}
else
{
ps.setString(1, uname);
ps.setString(2, pwd);
ResultSet rs =ps.executeQuery();
st = rs.next();
return st;
}
}catch(Exception e)
{
e.printStackTrace();
}
return st;
}
} |
package com.bbb.composite.product.details.model;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Docs
{
@JsonProperty("SCENE7_URL")
private String scene7Url;
@JsonProperty("DISPLAY_NAME")
private String display_name;
@JsonProperty("INTL_RESTRICTED")
private String intl_restricted;
@JsonProperty("INCART_FLAG")
private String incart_flag;
@JsonProperty("ATTRIBUTES_JSON")
private String[] attributes_json;
@JsonProperty("PRODUCT_ID")
private String product_id;
@JsonProperty("MX_PRICING_LABEL_CODE")
private String mx_pricing_label_code;
@JsonProperty("SITE_ID")
private String[] site_id;
@JsonProperty("COLLECTION_FLAG")
private String collection_flag;
//private String[] Inventory;
//private String RATINGS;
@JsonProperty("SEO_URL")
private String seo_url;
// private String CHILD_PRODUCT;
//private String EMAIL_OUT_OF_STOCK;
@JsonProperty("SHOP_GUIDE_ID")
private String shop_guide_id;
// private String[] PROD_ATTRIBUTES;
@JsonProperty("PRICE_RANGE_STRING")
private String price_range_string;
//private String[] CATEGORY_HIERARCHY;
@JsonProperty("DESCRIPTION")
private String description;
//private String BRAND_DESCRIP;
// private String SITE_NUM;
// private String[] RECORD_IDENTIFIER;
@JsonProperty("SWATCH_FLAG")
private String swatch_flag;
@JsonProperty("HIGH_PRICE")
private String high_price;
@JsonProperty("PRICE_RANGE_DESCRIP")
private String price_range_descrip;
@JsonProperty("LONG_DESCRIPTION")
private String long_description;
@JsonProperty("MX_INCART_FLAG")
private String mx_incart_flag;
@JsonProperty("REVIEWS")
private String reviews;
@JsonProperty("ALT_IMAGES")
private String[] alt_images;
@JsonProperty("LOW_PRICE")
private String low_price;
public String getScene7Url() {
return scene7Url;
}
public void setScene7Url(String scene7Url) {
this.scene7Url = scene7Url;
}
public String getDisplay_name() {
return display_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getIntl_restricted() {
return intl_restricted;
}
public void setIntl_restricted(String intl_restricted) {
this.intl_restricted = intl_restricted;
}
public String getIncart_flag() {
return incart_flag;
}
public void setIncart_flag(String incart_flag) {
this.incart_flag = incart_flag;
}
public String[] getAttributes_json() {
return attributes_json;
}
public void setAttributes_json(String[] attributes_json) {
this.attributes_json = attributes_json;
}
public String getProduct_id() {
return product_id;
}
public void setProduct_id(String product_id) {
this.product_id = product_id;
}
public String getMx_pricing_label_code() {
return mx_pricing_label_code;
}
public void setMx_pricing_label_code(String mx_pricing_label_code) {
this.mx_pricing_label_code = mx_pricing_label_code;
}
public String[] getSite_id() {
return site_id;
}
public void setSite_id(String[] site_id) {
this.site_id = site_id;
}
public String getCollection_flag() {
return collection_flag;
}
public void setCollection_flag(String collection_flag) {
this.collection_flag = collection_flag;
}
public String getSeo_url() {
return seo_url;
}
public void setSeo_url(String seo_url) {
this.seo_url = seo_url;
}
public String getShop_guide_id() {
return shop_guide_id;
}
public void setShop_guide_id(String shop_guide_id) {
this.shop_guide_id = shop_guide_id;
}
public String getPrice_range_string() {
return price_range_string;
}
public void setPrice_range_string(String price_range_string) {
this.price_range_string = price_range_string;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSwatch_flag() {
return swatch_flag;
}
public void setSwatch_flag(String swatch_flag) {
this.swatch_flag = swatch_flag;
}
public String getHigh_price() {
return high_price;
}
public void setHigh_price(String high_price) {
this.high_price = high_price;
}
public String getPrice_range_descrip() {
return price_range_descrip;
}
public void setPrice_range_descrip(String price_range_descrip) {
this.price_range_descrip = price_range_descrip;
}
public String getLong_description() {
return long_description;
}
public void setLong_description(String long_description) {
this.long_description = long_description;
}
public String getMx_incart_flag() {
return mx_incart_flag;
}
public void setMx_incart_flag(String mx_incart_flag) {
this.mx_incart_flag = mx_incart_flag;
}
public String getReviews() {
return reviews;
}
public void setReviews(String reviews) {
this.reviews = reviews;
}
public String[] getAlt_images() {
return alt_images;
}
public void setAlt_images(String[] alt_images) {
this.alt_images = alt_images;
}
public String getLow_price() {
return low_price;
}
public void setLow_price(String low_price) {
this.low_price = low_price;
}
@Override
public String toString() {
return "Docs [scene7Url=" + scene7Url + ", display_name=" + display_name + ", intl_restricted="
+ intl_restricted + ", incart_flag=" + incart_flag + ", attributes_json="
+ Arrays.toString(attributes_json) + ", product_id=" + product_id + ", mx_pricing_label_code="
+ mx_pricing_label_code + ", site_id=" + Arrays.toString(site_id) + ", collection_flag="
+ collection_flag + ", seo_url=" + seo_url + ", shop_guide_id=" + shop_guide_id
+ ", price_range_string=" + price_range_string + ", description=" + description + ", swatch_flag="
+ swatch_flag + ", high_price=" + high_price + ", price_range_descrip=" + price_range_descrip
+ ", long_description=" + long_description + ", mx_incart_flag=" + mx_incart_flag + ", reviews="
+ reviews + ", alt_images=" + Arrays.toString(alt_images) + ", low_price=" + low_price + "]";
}
} |
package com.base.crm.common.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.base.common.util.DateUtils;
import com.base.common.util.PageTools;
import com.base.crm.ad.service.ConsumeAcctGroupService;
import com.base.crm.orders.entity.CustOrder;
import com.base.crm.orders.service.CustOrderService;
import com.base.crm.report.entity.ConsumeAcctGroupReport;
import com.base.crm.report.entity.SummaryReport;
import com.base.crm.users.entity.UserInfo;
@Controller
@SessionAttributes("user")
public class IndexController {
private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
//
// @Autowired
// private CustInfoService custInfoService;
@Autowired
private CustOrderService orderService;
// @Autowired
// private WebsiteStatusCheckLogService websiteStatusCheckLogService;
@Autowired
private ConsumeAcctGroupService consumeAcctGroupService;
@RequestMapping(value = "/index")
public ModelAndView index(@ModelAttribute("user") UserInfo user) {
logger.info("index request");
Long userId = user.isAdmin() ? null : user.getuId();
List<SummaryReport> kpiList = null;
List<SummaryReport> kpiMonthList = null;
ModelAndView mv = new ModelAndView("page/index");
mv.addObject("date", new Date());
orderReport(mv, userId); // 单日/月表查询处理
CustOrder queryOrderParams = new CustOrder();
queryOrderParams.setPageTools(new PageTools(1, 15));
kpiMonthList = orderService.selectServicerKPIForMonthPageBy(queryOrderParams);
queryOrderParams.setUserId(userId==null?null:userId);
if (userId==null) {
ConsumeAcctGroupReport queryObject = new ConsumeAcctGroupReport();
queryObject.setStatus("1");
queryObject.setPageTools(new PageTools(7l));
List<ConsumeAcctGroupReport> resultList = consumeAcctGroupService.selectConsumeAcctGroupReportPage(queryObject);
mv.addObject("consumeAcctGroupReportList", resultList);
kpiList = orderService.selectServicerKPIForDalilyPageBy(queryOrderParams);
}else{
kpiList = orderService.selectServicerKPIForDalilyPageBy(queryOrderParams);
}
mv.addObject("kpiList", kpiList);
mv.addObject("kpiMonthList", kpiMonthList);
logger.info("index response===" + mv);
return mv;
}
private ModelAndView orderReport(ModelAndView mv, Long userId) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("userId", userId);
// 查询当日订单报表
String date = DateUtils.dateToTightStr(new Date());
SummaryReport currentReport = selectReportBy(userId, date,1);
mv.addObject("currentReport", currentReport);
// 查询昨日订单报表
date = DateUtils.dateToTightStr(DateUtils.getYesterdayDate());
SummaryReport yesterdayReport = selectReportBy(userId, date,1);
mv.addObject("yesterdayReport", yesterdayReport);
// 查询当月订单报表
String month = DateUtils.dateToTightStr(new Date()).substring(0, 6);
SummaryReport currentMonthReport = selectReportBy(userId, month,2);
mv.addObject("currentMonthReport", currentMonthReport);
// 查询上月订单报表
SummaryReport lastMonthReport = selectReportBy(userId, DateUtils.getLastMonth(),2);
mv.addObject("lastMonthReport", lastMonthReport);
return mv;
}
private SummaryReport selectReportBy(Long userId, String date,int reportFlag) {
List<SummaryReport> kpiList = null;
CustOrder queryOrderParams = new CustOrder();
queryOrderParams.setUserId(userId);
queryOrderParams.setStartDate(date);
queryOrderParams.setEndDate(date);
if(userId==null&&reportFlag==2){
kpiList = orderService.selectSalesPerformanceSummaryReport(queryOrderParams);
}else if(userId!=null&&reportFlag==2){
kpiList = orderService.selectServicerKPIForMonthPageBy(queryOrderParams);
}else if(userId!=null&&reportFlag==1){
kpiList = orderService.selectServicerKPIForDalilyPageBy(queryOrderParams);
}else if(userId==null&&reportFlag==1){
kpiList = orderService.selectServicerKPIForDalilyPageBy(queryOrderParams);
SummaryReport sr = new SummaryReport();
if(kpiList.size()>0){
for(SummaryReport temp : kpiList){
sr.sum(temp);
}
}
kpiList.clear();
kpiList.add(sr);
}
return kpiList.size()>0?kpiList.get(0):new SummaryReport();
}
public static void main(String[] args) {
System.err.println(DateUtils.getLastMonth());
}
@RequestMapping(value = "/home")
public ModelAndView home() {
logger.info("home request");
ModelAndView mv = new ModelAndView("page/Home");
mv.addObject("test", "hello world !!!home");
mv.addObject("date", new Date());
// mv.setViewName("forward:/login.html");
return mv;
}
}
|
package com.tencent.mm.ui.tools;
class FilterImageView$b {
String tUY;
String uxh;
String uxi;
FilterImageView$b(String str, String str2, String str3) {
this.tUY = str;
this.uxh = str2;
this.uxi = str3;
}
}
|
package com.lesson3.timecomplexity;
public class TapeEquilibrium {
public static void main(String [] args){
int [] A = {3,1,2,4,3};
System.out.println( new TapeEquilibrium().solution(A) );
}
public int solution(int[] A){
int totSum = 0;
int minDif = 9999;
int sumA = 0;
int sumB = 0;
for(int i:A){
totSum += i;
}
for(int i=0;i<A.length;i++){
if(i>0){
sumB = totSum - sumA;
int dif = Math.abs(sumA-sumB);
if(dif<minDif){
minDif = dif;
}
}
sumA += A[i];
}
return minDif;
}
}
|
package com.tencent.mm.plugin.brandservice.ui;
import com.tencent.mm.protocal.c.ju;
import com.tencent.mm.protocal.c.jz;
import java.util.List;
protected class c$a {
public long bHu;
public int count;
public int dYU;
public List<String> hoB;
public List<jz> hoC;
public boolean hoD;
public boolean hoE;
public List<ju> hoF;
protected c$a() {
}
}
|
package com.tfjybj.integral.model.scoreResult;
import com.tfjybj.integral.model.scoreResult.DetailBugModel;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
//import javax.xml.soap.Detail;
import java.util.List;
import java.util.Set;
@NoArgsConstructor
@Data
@Accessors(chain = true)
@ToString(callSuper = true)
public class DetailDataModel {
/**
* bug各状态详细数据
*/
private List<DetailBugModel> detailBugSet;
/**
* Task各状态详细数据
*/
private List<DetailTaskModel> detailTaskSet;
}
|
package com.tencent.mm.plugin.appbrand.jsapi.wifi;
import com.tencent.mm.plugin.appbrand.e;
import com.tencent.mm.plugin.appbrand.e.b;
import com.tencent.mm.plugin.appbrand.jsapi.wifi.wifisdk.d;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.sdk.platformtools.x;
class a$3 extends b {
final /* synthetic */ l fCl;
final /* synthetic */ a gdp;
a$3(a aVar, l lVar) {
this.gdp = aVar;
this.fCl = lVar;
}
public final void onDestroy() {
x.d("MicroMsg.JsApiConenctWifi", "remove listener");
d.a(null);
e.b(this.fCl.mAppId, this);
}
}
|
package net.javaguides.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import net.javaguides.springboot.service.InstanceService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import net.javaguides.springboot.model.Employee;
import net.javaguides.springboot.model.Instance;
import net.javaguides.springboot.service.EmployeeService;
@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@Autowired
private InstanceService instanceService;
// display list of employees
@GetMapping("/home")
public String viewHomePage(Model model) {
List<Employee> listEmployees = employeeService.getAllEmployees();
model.addAttribute("listEmployees", listEmployees);
return "index";
}
@GetMapping("/instance")
public String viewInstance(Model model) {
List<Instance> listinstance = instanceService.getAllInstances();
model.addAttribute("listEmployees", listinstance);
return "indexi";
}
@GetMapping("/showNewEmployeeForm")
public String showNewEmployeeForm(Model model) {
// create model attribute to bind form data
Employee employee = new Employee();
model.addAttribute("employee", employee);
return "new_employee";
}
@PostMapping("/saveEmployee")
public String saveEmployee(@ModelAttribute("employee") Employee employee) {
// save employee to database
employeeService.saveEmployee(employee);
return "redirect:/home";
}
@GetMapping("/showFormForUpdate/{id}")
public String showFormForUpdate(@PathVariable ( value = "id") long id, Model model) {
// get employee from the service
Employee employee = employeeService.getEmployeeById(id);
// set employee as a model attribute to pre-populate the form
model.addAttribute("employee", employee);
return "update_employee";
}
@GetMapping("/showResent/{stack}")
public String showResent(@PathVariable ( value = "stack") String stack, Model model) {
List<Employee> listEmployees = employeeService.recent(stack);
model.addAttribute("listEmployees", listEmployees);
model.addAttribute("link","http://localhost:8080/instance");
return "firstthree";
}
@GetMapping("/deleteEmployee/{id}")
public String deleteEmployee(@PathVariable (value = "id") long id) {
// call delete employee method
this.employeeService.deleteEmployeeById(id);
return "redirect:/home";
}
@GetMapping("/firstthree")
public String firstthree(Model model) {
List<Employee> listEmployees = employeeService.gettenEmployees();
model.addAttribute("listEmployees", listEmployees);
model.addAttribute("link","http://localhost:8080/home");
return "firstthree";
}
@GetMapping("/")
public String login()
{
return "login";
}
}
|
package mk.petrovski.weathergurumvp.data.remote.model.error_models;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
public class DataResponseModel {
private ErrorModel data;
public ErrorModel getData() {
return data;
}
public void setData(ErrorModel data) {
this.data = data;
}
}
|
package com.foobarspam.figuras;
public class Square extends GeometricShape implements Drawable {
//Propiedades
private double side = 0.;
//Constructores
public Square() {
super();
}
public Square(double side) {
super();
this.side = side;
}
public Square(String name, double side) {
super(name);
this.side = side;
}
//Setters y getters
public void setSide(double side) {
this.side = side;
}
public double getSide() {
return this.side;
}
//Lógica
@Override
public double area() {
double area = this.side*this.side;
return area;
}
@Override
public void draw() {
System.out.println(getName()+", which is a square, has been drawn.");
}
@Override
public void applyTheme() {
System.out.println("A super cool theme was applied to "+getName()+"which is a Square.");
}
} |
/*
* 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.web.tests.initialization;
import java.util.ArrayList;
import java.util.Collection;
import jakarta.enterprise.context.RequestScoped;
import jakarta.enterprise.context.SessionScoped;
import jakarta.servlet.ServletRequestEvent;
import org.junit.Assert;
import org.apache.webbeans.test.AbstractUnitTest;
import org.apache.webbeans.web.lifecycle.test.MockServletContext;
import org.apache.webbeans.web.tests.MockHttpSession;
import org.apache.webbeans.web.tests.MockServletRequest;
import org.junit.Test;
public class InitializedSessionScopedTest extends AbstractUnitTest
{
@Test
public void testse() throws Exception
{
Collection<Class<?>> beanClasses = new ArrayList<Class<?>>();
beanClasses.add(MySession.class);
beanClasses.add(MySessionHandler.class);
startContainer(beanClasses, null);
final MockServletContext mockServletContext = new MockServletContext();
final MockServletRequest mockServletRequest = new MockServletRequest();
final ServletRequestEvent servletRequestEvent = new ServletRequestEvent(mockServletContext, mockServletRequest);
MockHttpSession mockSession = new MockHttpSession();
getWebBeansContext().getContextsService().startContext(RequestScoped.class, servletRequestEvent);
MySessionHandler mySessionHandler = getInstance(MySessionHandler.class);
Assert.assertFalse(mySessionHandler.isInitialized());
getWebBeansContext().getContextsService().startContext(SessionScoped.class, mockSession);
getWebBeansContext().getContextsService().endContext(SessionScoped.class, mockSession);
Assert.assertTrue(mySessionHandler.isInitialized());
getWebBeansContext().getContextsService().endContext(RequestScoped.class, servletRequestEvent);
shutDownContainer();
}
}
|
package amu.electrical.deptt.utils;
import amu.electrical.deptt.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.support.v7.app.NotificationCompat;
public class NotificationUtils {
public static int ID = 420, NORMAL = ID, POSITIVE = 70, NEGATIVE = 71, MEDIA = 72, ANNOUNCEMENT = 73;
private int currId = ID;
private Context ctx;
public NotificationUtils() {
}
public NotificationUtils(Context ctx) {
this.ctx = ctx;
}
public void setId(int id) {
currId = id;
}
public void showNotification(String title, String message, Intent i) {
PendingIntent resultPendingIntent = PendingIntent.getActivity(ctx, ID, i, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Style style = new NotificationCompat.InboxStyle();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx);
Notification notification = mBuilder
.setColor(ctx.getResources().getColor(R.color.green_main))
.setSmallIcon(R.drawable.ic_noti_small)
.setTicker(title)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setAutoCancel(true)
.setStyle(style)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(currId, notification);
}
}
|
package algorithm.programmers.hash;
import java.util.HashMap;
public class programmers_courses30_lessons42578 {
static int solution(String[][] clothes) {
HashMap<String, Integer> map = new HashMap<>();
// 해시에 키,값 형태로 옷 종류별 개수 저장
for (int i = 0; i < clothes.length; i++) {
String currentKey = clothes[i][1];
if (map.containsKey(currentKey)) {
map.replace(currentKey, map.get(currentKey) + 1);
} else {
map.put(currentKey, 1);
}
}
int answer = 1;
for(int val : map.values()) {
answer *= (val+1);
}
return answer-1;
// Iterator<String> mapIter = map.keySet().iterator();
//
// int speciesCnt = map.size();
//// System.out.println("speciesCnt:" + speciesCnt);
// int result = 0;
//
// // n개 중 2..max 선택
// for (int i = 2; i <= speciesCnt; i++) {
// int temp = nCr(speciesCnt, i);
// // 한 종류에 여러개가 있다면 그 만큼 경우의 수가 늘어나므로 곱해준다
// while (mapIter.hasNext()) {
// temp *= map.get(mapIter.next());
// System.out.println(temp);
// }
// mapIter = map.keySet().iterator();
// result += temp;
// System.out.println("temp = "+temp);
// System.out.println("result = "+result);
// }
//
// // 각각 하나씩만 입었을 경우 더함
// result += clothes.length;
}
// 조합 공식 사용 nCr = n! / r!(n-r)!
static int nCr(int n, int r) {
if (n - r == 0)
return 1;
return factorial(n, n) / (factorial(r, r) * factorial(n - r, n - r));
}
static int factorial(int n, int result) {
if (n - 1 <= 0)
return result;
return factorial(n - 1, result * (n - 1));
}
public static void main(String[] args) {
// String[][] clothes = { { "1", "a" }, { "4", "b" },{ "5", "c" }, {"2","a"},{"3","a"},{"6","c"}};
// String[][] clothes = { { "1", "a" }, { "2", "b" },{ "3", "a" }};
String[][] clothes = { { "1", "a" }, { "2", "b" },{ "3", "c" }};
System.out.println(solution(clothes));
}
}
|
package ca.aequilibrium.weather.models;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.android.gms.maps.model.LatLng;
@Entity
public class Location implements Parcelable {
@PrimaryKey(autoGenerate = true)
private int uid;
@ColumnInfo(name = "latLng")
private LatLng latLng;
@ColumnInfo(name = "name")
private String name;
@ColumnInfo(name = "country")
private String country;
public Location() {}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public LatLng getLatLng() {
return latLng;
}
public void setLatLng(LatLng latLng) {
this.latLng = latLng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
protected Location(Parcel in) {
uid = in.readInt();
latLng = (LatLng) in.readValue(LatLng.class.getClassLoader());
name = in.readString();
country = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(uid);
dest.writeValue(latLng);
dest.writeString(name);
dest.writeString(country);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<Location> CREATOR = new Parcelable.Creator<Location>() {
@Override
public Location createFromParcel(Parcel in) {
return new Location(in);
}
@Override
public Location[] newArray(int size) {
return new Location[size];
}
};
}
|
public class A {
public int numberA = 10;
public void walking(){
System.out.println("walking...");
}
public void dancing() {
System.out.println("dancing...");
}
}
|
package com.blackdragon2447.AAM.util;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import com.blackdragon2447.AAM.Reference;
import com.blackdragon2447.AAM.gui.AAMGui;
public class ThemeButtonBuilder {
public static JMenuItem BuildThemeButton(Themes Theme) {
JMenuItem item = new JMenuItem(Theme.toString());
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Themes theme[] = Themes.values();
for (int i = 0; i < theme.length; i++) {
if(theme[i].equals(Theme)){
AAMGui.setVisual(Themes.getLookAndFeel(i));
Reference.theme = i;
}
}
}
});
return item;
}
}
|
package aquarium.jellies;
public class Jelly { }
|
/*
* 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 view;
import static com.sun.java.accessibility.util.AWTEventMonitor.addWindowListener;
import controller.CargoController;
import controller.EmpresaController;
import controller.PessoaController;
import controller.SetorController;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import model.Cargo;
import model.Empresa;
import model.Setor;
/**
*
* @author carlos
*/
public class TelaCadastrar extends JInternalFrame{
private JPanel painel;
private JLabel jlNome;
private JLabel jlTelefone;
private JLabel jlEmpresa;
private JLabel jlSetor;
private JLabel jLEmail;
private JLabel jLCargo;
private JLabel jlMensagem;
private JTextField jTNome;
private JTextField jTTelefone;
private JTextField jTEmail;
private JComboBox jCEmpresa;
private JComboBox jCCargo;
private JComboBox jCSetor;
private JButton jbSalvar;
private JButton jbCancelar;
private final JTable tabela;
public TelaCadastrar( JTable table ){
initComponentes();
tabela = table;
}
private void initComponentes(){
//w, h
this.setSize(850, 335);
this.setLayout( null );
this.setTitle( "Cadastrar Pessoa" );
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
setClosable(true);
setIconifiable(true);
// setMaximizable(true);
// setResizable(true);
painel = new JPanel( null );
painel.setSize( 835, 295 );
painel.setLocation(3, 3);
painel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
add( painel );
//x y w h
jlNome = new JLabel( "Nome" );
jlNome.setBounds(10, 15, 40, 10);
painel.add( jlNome );
jTNome = new JTextField();
jTNome.setBounds(100, 10, 400, 25);
painel.add( jTNome );
jlTelefone = new JLabel( "Telefone" );
jlTelefone.setBounds(10, 50, 100, 10);
painel.add( jlTelefone );
jTTelefone = new JTextField();
jTTelefone.setBounds(100, 45, 200, 25);
painel.add( jTTelefone );
jlEmpresa = new JLabel( "Empresa" );
jlEmpresa.setBounds(10, 85, 100, 10);
painel.add( jlEmpresa );
jCEmpresa = new JComboBox();
jCEmpresa.setBounds(100, 80, 200, 25);
painel.add( jCEmpresa );
jlSetor = new JLabel( "Setor" );
jlSetor.setBounds(10, 120, 100, 10);
painel.add( jlSetor );
jCSetor = new JComboBox();
jCSetor.setBounds(100, 115, 200, 25);
painel.add( jCSetor );
jLEmail = new JLabel( "E-mail" );
jLEmail.setBounds(10, 160, 100, 10);
painel.add( jLEmail );
jTEmail = new JTextField();
jTEmail.setBounds(100, 150, 200, 25);
painel.add( jTEmail );
jLCargo = new JLabel( "Cargo" );
jLCargo.setBounds(10, 190, 100, 10);
painel.add( jLCargo );
jCCargo = new JComboBox();
jCCargo.setBounds(100, 185, 200, 25);
painel.add( jCCargo );
preencherCombos();
jlMensagem = new JLabel( "" );
jlMensagem.setBounds(40, 215, 300, 15);
jlMensagem.setForeground(Color.red);
painel.add( jlMensagem );
jbSalvar = new JButton("Salvar");
jbSalvar.setBounds(50, 240, 150, 25);
painel.add( jbSalvar );
jbSalvar.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
jBSalvarActionPerformed(ae);
}
} );
jbCancelar = new JButton("Voltar");
jbCancelar.setBounds(220, 240, 150, 25);
painel.add( jbCancelar );
jbCancelar.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
jbCancelarActionPerformed(ae);
}
} );
}
private void preencherCombos(){
preencherComboEmpresa();
preencherComboSetor();
preencherComboCargo();
}
private void preencherComboEmpresa(){
EmpresaController ec = new EmpresaController();
ec.getLista( jCEmpresa );
}
private void preencherComboSetor(){
SetorController ec = new SetorController();
ec.getLista( jCSetor );
}
private void preencherComboCargo(){
CargoController ec = new CargoController();
ec.getLista( jCCargo );
}
private void jbCancelarActionPerformed( ActionEvent ae ){
dispose();
}
private void jBSalvarActionPerformed( ActionEvent ae ){
if( validarCampos() )
salvar();
}
private boolean validarCampos(){
boolean teste = true;
if( jTNome.getText().equals("") || jTTelefone.getText().equals("") || jTEmail.getText().equals("") ||
jCEmpresa.getSelectedIndex() == 0 || jCSetor.getSelectedIndex() == 0 || jCCargo.getSelectedIndex() == 0 ){
teste = false;
if( jTNome.getText().equals("") ){
jlMensagem.setText( "Preencha o nome" );
}
else if( jTTelefone.getText().equals("") ){
jlMensagem.setText( "Preencha o telefone" );
}
else if( jTEmail.getText().equals("") ){
jlMensagem.setText( "Preencha o e-mail" );
}
else if( jCEmpresa.getSelectedIndex() == 0 ){
jlMensagem.setText( "Escolha a empresa" );
}
else if( jCSetor.getSelectedIndex() == 0){
jlMensagem.setText( "Preencha o Setor" );
}
else if( jCCargo.getSelectedIndex() == 0 ){
jlMensagem.setText( "Preencha o cargo" );
}
}
return teste;
}
private void salvar(){
String nome = jTNome.getText();
String telefone = jTTelefone.getText();
Empresa objEmpresa = (Empresa) jCEmpresa.getSelectedItem();
String empresa = String.valueOf( objEmpresa.getCd_empresa() );
Setor objSetor = (Setor) jCSetor.getSelectedItem();
String setor = String.valueOf( objSetor.getCd_setor() );
String email = jTEmail.getText();
Cargo objCargo = (Cargo) jCCargo.getSelectedItem();
String cargo = String.valueOf( objCargo.getCd_cargo() );
PessoaController pc = new PessoaController();
String[] values = new String[6];
values[0] = nome;
values[1] = telefone;
values[2] = empresa;
values[3] = setor;
values[4] = email;
values[5] = cargo;
pc.add(values, tabela, this);
}
}
|
package com.takshine.wxcrm.service;
import java.util.List;
import java.util.Map;
import com.takshine.wxcrm.base.services.EntityService;
import com.takshine.wxcrm.base.util.WxHttpConUtil;
import com.takshine.wxcrm.domain.UserRela;
import com.takshine.wxcrm.message.error.CrmError;
import com.takshine.wxcrm.message.sugar.FrstChartsReq;
import com.takshine.wxcrm.message.sugar.FrstChartsResp;
import com.takshine.wxcrm.message.sugar.UserAdd;
import com.takshine.wxcrm.message.sugar.UserReq;
import com.takshine.wxcrm.message.sugar.UsersResp;
import com.takshine.wxcrm.message.userget.UserGet;
/**
* 从sugar系统获取 LOV和 用户 的服务
* @author liulin
*
*/
public interface LovUser2SugarService extends EntityService {
/**
* 查询 获取 lov 数据列表
* @return
*/
public Map<String, Map<String, String>> getLovList(String crmId);
/**
* 从sugar系统中 查询 用户的数据列表
* @return
*/
public UsersResp getUserList(UserReq req) throws Exception;
/**
* 从后台CRM系统中 查询 首字母数据列表
* @return
*/
public FrstChartsResp getFirstCharList(FrstChartsReq req);
/**
* 获取关注用户列表
* @return
*/
public UserGet getAttenUserList(String publicId, String userId, String relaId);
/**
* 查询活动首字母
* @param req
* @return
*/
public FrstChartsResp getCampaignsFirstCharList(String openId);
/**
* 缓存数据
* @param data
*/
public void cacheLovData(String orgId, Map<String, Map<String, String>> data);
/**
* 修改用户的状态
* @param userAdd
* @return
*/
public CrmError updateUser(UserReq req);
/**
* 验证老密码
* @param ua
* @return
*/
public boolean validateUserPassword(UserAdd ua);
/**
* 修改密码
* @param ua
* @return
*/
public boolean updateUserPassword(UserAdd ua);
/**
* 修改用户信息
* @param ua
* @return
*/
public boolean updateUserInfo(UserAdd ua);
/**
* 获取好友列表
* @param userId
* @return
*/
public List<UserRela> getFriendList(String userId);
/**
* 从sugar系统中 查询 用户的数据列表
* @return
*/
public UsersResp getUserList(UserReq req,WxHttpConUtil util) throws Exception;
}
|
package com.ojas.rpo.security.dao.assign;
import java.util.List;
import com.ojas.rpo.security.dao.Dao;
import com.ojas.rpo.security.entity.Assign;
import com.ojas.rpo.security.entity.BdmReq;
import com.ojas.rpo.security.entity.Client;
import com.ojas.rpo.security.entity.Response;
import com.ojas.rpo.security.entity.User;
public interface AssignDao extends Dao<Assign, Long> {
public List<Assign> findById(Long assignid);
List<BdmReq> getReqByRecIdandClientId(Long userId, Long clientId, String status);
Response getReqByRecIdandUserId(Long userId, String status, Integer pageNo, Integer pageSize, String sortOrder, String sortField, String searchText, String searchField);
List<Client> getClientsByRecById(Long userId, String status);
List<Assign> getAssigenByBdmId(Long userId, String role);
int deleteByid(Long assigenid);
Response getAssinedRequirementsByBdmId(Long userId, String role, Integer pageNo, Integer pageSize, String sortingOrder, String sortingField, String searchText, String searchField);
Response searchAssignedRequirementsByBdmId(String role, Long id, String searchInput, String searchField, Integer pageNo, Integer pageSize);
public Integer deleteAssignmentByRecriuterAndRequirement(Long requirementId, User users);
// List<Assign> findReqiremetsByRecId();
}
|
package vantoan.blog_security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import vantoan.blog_security.service.IAppUserService;
@EnableWebSecurity
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private IAppUserService appUserService;
@Autowired
private LoginSucessHandle loginSucessHandle;
@Autowired
private AccesDinedHandler accesDinedHandler;
// xac thuc bo nho
// @Bean
// public UserDetailsService userDetailsService(){
// User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
// InMemoryUserDetailsManager memoryUserDetailsManager = new InMemoryUserDetailsManager();
// memoryUserDetailsManager.createUser(userBuilder.username("hung").password("123456").roles("USER").build());
// memoryUserDetailsManager.createUser(userBuilder.username("vohung").password("123456").roles("ADMIN").build());
// return memoryUserDetailsManager;
// }
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService((UserDetailsService) appUserService).passwordEncoder(NoOpPasswordEncoder.getInstance());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/blogs").permitAll()
.and().authorizeRequests().antMatchers("/blogs/edit/{id}").hasRole("ADMIN")
.and().authorizeRequests().antMatchers(HttpMethod.GET,"/blogs/**").hasAnyRole("USER","ADMIN")
.and().authorizeRequests().antMatchers(HttpMethod.POST,"/blogs/**").hasRole("ADMIN")
.and().authorizeRequests().antMatchers("/blogs/detail/{id}").permitAll()
.and()
.formLogin().loginPage("/login").failureForwardUrl("/failLogin").successHandler(loginSucessHandle)
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.and().exceptionHandling().accessDeniedHandler(accesDinedHandler);
http.csrf().disable();
}
}
|
package de.jottyfan.db;
import javax.faces.context.FacesContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Record1;
import org.jooq.Record2;
import org.jooq.SelectConditionStep;
import org.jooq.TableLike;
import org.jooq.impl.DSL;
import de.jottyfan.jsf.model.login.Encrypter;
import de.jottyfan.jsf.model.login.ProfileBean;
/**
*
* @author jotty
*
*/
public class LoginGateway extends JottyBlogGateway {
private final static Logger LOGGER = LogManager.getLogger(LoginGateway.class);
public static final TableLike<Record> V_LOGIN = DSL.table("v_login");
public static final Field<String> USERNAME = DSL.field("username", String.class);
public static final Field<String> PASSWORD = DSL.field("password", String.class);
public static final TableLike<Record> V_PROFILERIGHT = DSL.table("v_profileright");
public static final Field<Integer> FK_PROFILE = DSL.field("fk_profile", Integer.class);
public static final Field<String> RIGHT_NAME = DSL.field("right_name", String.class);
public LoginGateway(FacesContext facesContext) {
super(facesContext);
}
/**
* check if username password combination can be found in v_login
*
* @param username
* to be checked
* @param password
* to be checked
* @return true if found, false otherwise
*/
public boolean checkValidUsernamePassword(String username, String password) {
SelectConditionStep<Record1<String>> sql = jooq().select(PASSWORD).from(V_LOGIN).where(USERNAME.eq(username));
LOGGER.debug("{}, ? = {}", sql, username);
Record1<String> result = sql.fetchOne();
if (result == null) {
return false;
} else {
return Encrypter.check(password, result.get(PASSWORD));
}
}
/**
* load profile of user referenced by username
*
* @param username
* to reference to
* @return loaded profile
*/
public ProfileBean loadProfile(String username) {
SelectConditionStep<Record2<Integer, String>> sql = jooq().select(FK_PROFILE, RIGHT_NAME).from(V_PROFILERIGHT).where(USERNAME.eq(username));
LOGGER.debug("{}", sql.toString());
ProfileBean bean = new ProfileBean(username);
for (Record r : sql.fetch()) {
bean.setUsnr(r.get(FK_PROFILE));
bean.getRights().add(r.get(RIGHT_NAME));
}
return bean;
}
}
|
package com.tencent.mm.ui.contact;
import com.tencent.mm.ui.contact.SnsAddressUI.1;
class SnsAddressUI$1$1 implements Runnable {
final /* synthetic */ 1 ulT;
SnsAddressUI$1$1(1 1) {
this.ulT = 1;
}
public final void run() {
if (!this.ulT.ulS.getIntent().getBooleanExtra("stay_in_wechat", true)) {
this.ulT.ulS.moveTaskToBack(true);
}
}
}
|
package com.gcsw.teamone;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.messaging.FirebaseMessaging;
public class FirstAuthActivity extends AppCompatActivity {
private Intent intent;
private static String myID;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sf = getSharedPreferences("Users",MODE_PRIVATE);
if( sf.getString("Email","").length() == 0) {
// call Login Activity
intent = new Intent(FirstAuthActivity.this, LoginActivity.class);
} else {
// Call Next Activity
myID = sf.getString("Email", "").replace(".", "_");
intent = new Intent(FirstAuthActivity.this, MainActivity.class);
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
if (!task.isSuccessful()) {
Log.w("LoginActivity", "Fetching FCM registration token failed", task.getException());
return;
}
// Get new FCM registration token
String token = task.getResult();
DatabaseReference usersToken_ref =
FirebaseDatabase.getInstance().getReference("users").child(myID).child("token");
usersToken_ref.setValue(token);
}
});
}
intent.putExtra("fragment","0");
startActivity(intent);
this.finish();
}
public static String getMyID() { return myID; }
}
|
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
public class XMLHandler extends DefaultHandler {
private static SimpleDateFormat birthDayFormat = new SimpleDateFormat("yyyy.MM.dd");
private SimpleDateFormat visitDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
private Voter voter;
private WorkTime workTime;
private HashMap<Voter, Byte> voterCounts;
private HashMap<Short, WorkTime> voteStationWorkTimes;
private static byte val = 1;
public XMLHandler() {
this.voterCounts = new HashMap<>();
this.voteStationWorkTimes = new HashMap<>();
}
public HashMap<Voter, Byte> getVoterCounts() {
return voterCounts;
}
public HashMap<Short, WorkTime> getVoteStationWorkTimes() {
return voteStationWorkTimes;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
try {
if (qName.equals("voter")) {
voter = new Voter(attributes.getValue("name"),
attributes.getValue("birthDay"));
} else if (qName.equals("visit") && voter != null) {
voterCounts.merge(voter, val, (oldVal, newVal) -> (byte) (oldVal + newVal));
String stStation = attributes.getValue("station");
String stTime = attributes.getValue("time");
fillingVoteStationWorkTimes(stStation, stTime);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void fillingVoteStationWorkTimes(String stStation, String stTime) {
Short station = Short.parseShort(stStation);
Date time = null;
try {
time = visitDateFormat.parse(stTime);
} catch (ParseException e) {
e.printStackTrace();
}
workTime = voteStationWorkTimes.get(station);
if (workTime == null) {
workTime = new WorkTime();
voteStationWorkTimes.put(station, workTime);
}
workTime.addVisitTime(time.getTime());
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("voter")) {
voter = null;
}
if (qName.equals("visit")) {
workTime = null;
}
}
public void printVoteStationWorkTimes() {
System.out.println("Voting station work times: ");
for (Short votingStation : voteStationWorkTimes.keySet()) {
WorkTime workTime = voteStationWorkTimes.get(votingStation);
System.out.println("\t" + votingStation + " - " + workTime);
}
}
public void printVoterCounts() {
System.out.println("Duplicated voters: ");
for (Voter voter : voterCounts.keySet()) {
short count = voterCounts.get(voter);
if (count > 1) {
System.out.println(voter.toString() + "-" + count);
}
}
}
} |
package cn.it.homework6.adapter;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import cn.it.homework6.R;
public class DiaryListAdapter extends BaseAdapter {
private Context context;//上下文
private List<Map<String, Object>> data;//要装配的数据
public DiaryListAdapter(Context context, List<Map<String, Object>> data) {
this.context=context;
this.data=data;
}
//设置要装配的数据
public void setData(List<Map<String, Object>> data){
this.data=data;
}
@Override
public int getCount() {
return data==null?0:data.size();
}
@Override
public Object getItem(int position) {
return data==null?null:data.get(position);
}
@Override
public long getItemId(int position) {
return data==null?0:Long.valueOf(data.get(position).get("_id").toString());
}
//取得列表项视图对象
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Map<String,Object> map=data.get(position);
if(convertView==null){ //通过可回收的View优化自定义适配器
convertView=LayoutInflater.from(context).inflate(R.layout.note_item, parent, false);
}
TextView titleTv=(TextView) convertView.findViewById(R.id.title_tv);
TextView contentTv=(TextView) convertView.findViewById(R.id.content_tv);
titleTv.setText(map.get("title").toString());
contentTv.setText(map.get("content").toString());
return convertView;
}
}
|
package linklist;
import java.util.LinkedHashSet;
import java.util.Set;
public class DriverClasss {
public static void main(String[] args) {
LinkList l=new LinkList();
Node j=new Node(5);
l.insertAtHead(j);
Node k=new Node(6);
l.insertAtHead(k);
l.insertAtLast(new Node(7));
l.insertAtLast(new Node(7));
l.insertAtHead(new Node(1));
l.insertAtAny(55, 0);
l.insertAtAny(550, 1);
l.insertAtAny(1, 1);
System.out.println(l);
System.out.println(l.delFromLast());
System.out.println(l);
System.out.println(l.nodeFromLast(3));//node from lastt in single iteration
Node x1=l.head;
Node x=l.nodeFromLastUsingRecursion(x1, 3);//nodefrom last using recursion
System.out.println("i"+x);
LinkList l1=l;
System.out.println("before reversal"+l1);
//printing in reverse
l.printInReverse(l.head);
System.out.println("after reversal" +l1.reverseAlinkList(x1));//reversing a linklist
///middle of a link list
System.out.println(l1.returnMiddle().getX());//element in the middle of the linklist
//to find the intersection of the 2 link list
LinkList link1=new LinkList();
link1.insertAtHead(new Node(1));
link1.insertAtLast(new Node(2));
link1.insertAtLast(new Node(3));
LinkList link2=new LinkList();
link2.insertAtHead(new Node(1));
link2.insertAtLast(new Node(2));
link2.insertAtLast(new Node(3));
link2.insertAtLast(l.head);//now l2 pointing toward starting link
link1.insertAtLast(l.head);//now l1 pointing toward starting link
System.out.println(link1);
System.out.println(link2);
Set a=new LinkedHashSet<>();
Node start=link1.head;
while(start!=null) {
a.add(start.hashCode());
start=start.getNext();
}
System.out.println(a);
Node temp2=link2.head;
Node inter=null;
while(temp2!=null) {
if(!(a.add(temp2.hashCode()))) {
inter=temp2;
break;
}
temp2=temp2.getNext();
}
System.out.println(inter);////intersection of 2 nodes
}}
|
package com.pxene;
import com.google.common.collect.Lists;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadEarlyAmaxLogToFlume {
public static final Logger logger = LogManager.getLogger(MultiThreadEarlyAmaxLogToFlume.class);
private static ArrayBlockingQueue<File> queue = new ArrayBlockingQueue<>(64);
public static void main(String[] args) {
if (args.length < 1) {
logger.error("please give the folder path");
System.exit(0);
}
int length = args.length;
String folderPath = args[length -1];
List<File> fileList = Lists.newArrayList();
List<File> files = GlobalUtil.getFileFromFolder(folderPath, fileList);
int processNum = (Runtime.getRuntime().availableProcessors()) * 2;
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(processNum);
EarlyAmaxFileProducer producer = new EarlyAmaxFileProducer(files, queue);
EarlyAmaxFileConsumer consumer = new EarlyAmaxFileConsumer(args[length-3], Integer.valueOf(args[length-2]), queue);
fixedThreadPool.execute(producer);
for (int i = 0; i < processNum; i++) {
fixedThreadPool.execute(consumer);
}
}
}
|
package com.mobfox.rtree.model;
import com.mobfox.rtree.entity.Sample;
import java.util.Collections;
import java.util.function.Function;
/**
* A terminal node of an {@link com.mobfox.rtree.model.RTree RTree}.
* Responsible for making the actual predictions.
*/
public class RTreeLeaf implements RTree {
private final Function<Sample, Double> leafModel;
/**
* @param leafModel the fitted prediction function for this terminal leaf node
*/
public RTreeLeaf(Function<Sample, Double> leafModel) {
this.leafModel = leafModel;
}
public double predict(final Sample sample) {
return leafModel.apply(sample);
}
@Override
public Stats stats() {
return new Stats(1, 0, Collections.emptyMap());
}
}
|
package asscry;
import java.io.File;
import java.io.FileOutputStream;
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class BFKeyGenerate {
//private static final String FILENAME = "//storage//emulated//0//Crypto//";
static File direc = new File("");
private static String fileName = direc.getAbsolutePath();
public static void saveKey(final int KEY_SIZE) {
FileOutputStream fot = null;
try {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
keyGen.init(KEY_SIZE, sr);
SecretKey secretKey = keyGen.generateKey();
byte[] secretKeyByte = secretKey.getEncoded();
//FileUtil.createDirectory("KeyAES", FILENAME);
FileOutputStream fos = new FileOutputStream(fileName + "\\key_BlowFish.txt");
fos.write(secretKeyByte);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package ru.otus.spring.barsegyan.service.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.stereotype.Service;
import ru.otus.spring.barsegyan.domain.AppUser;
import ru.otus.spring.barsegyan.dto.rest.mappers.UserDtoMapper;
import ru.otus.spring.barsegyan.dto.rest.response.UserDto;
import ru.otus.spring.barsegyan.type.UserPrincipal;
import ru.otus.spring.barsegyan.util.UTCTimeUtils;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class SessionService {
private static final long MINUTES_SINCE_LAST_ACTIVITY_TO_BE_CONSIDERED_ONLINE = 1;
private final FindByIndexNameSessionRepository<? extends Session> findByIndexNameSessionRepository;
public SessionService(FindByIndexNameSessionRepository<? extends Session> findByIndexNameSessionRepository) {
this.findByIndexNameSessionRepository = findByIndexNameSessionRepository;
}
public UserPrincipal getCurrentUser() {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return (UserPrincipal) principal;
}
public void invalidateSession(String sessionId) {
findByIndexNameSessionRepository.deleteById(sessionId);
}
public boolean isUserOnline(String username) {
LocalDateTime now = UTCTimeUtils.now();
return findByIndexNameSessionRepository
.findByPrincipalName(username)
.values()
.stream()
.anyMatch(session -> {
LocalDateTime lastAccessedTime = UTCTimeUtils.toDate(session.getLastAccessedTime());
long minutesSinceLastActivity = Duration.between(lastAccessedTime, now).abs().toMinutes();
return minutesSinceLastActivity <= MINUTES_SINCE_LAST_ACTIVITY_TO_BE_CONSIDERED_ONLINE;
});
}
public List<UserDto> mapOnlineStatus(Collection<AppUser> users) {
return users.stream()
.map(this::mapOnlineStatus)
.collect(Collectors.toList());
}
public UserDto mapOnlineStatus(AppUser user) {
return Optional.ofNullable(user)
.map(value -> UserDtoMapper.map(user, isUserOnline(user.getUsername())))
.orElse(null);
}
public List<? extends Session> getUserSessions(String username) {
return new ArrayList<>(findByIndexNameSessionRepository.findByPrincipalName(username).values());
}
public Session createSession(Authentication authentication) {
Session newSession = findByIndexNameSessionRepository.createSession();
newSession.setMaxInactiveInterval(Duration.ofHours(720));
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(authentication);
newSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);
((SessionRepository) findByIndexNameSessionRepository).save(newSession);
return newSession;
}
public UserPrincipal getAuthenticationPrincipal(String token) {
Session session = findByIndexNameSessionRepository.findById(token);
SecurityContext securityContext = session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
Object principal = securityContext.getAuthentication().getPrincipal();
return (UserPrincipal) principal;
}
}
|
package de.madjosz.adventofcode.y2016;
import static java.lang.Math.abs;
import java.util.List;
import java.util.function.IntConsumer;
public class Day02 {
private final List<String> input;
public Day02(List<String> input) {
this.input = input;
}
public int a1() {
int[] pos = new int[] { 1, 1 };
int code = 0;
for (String line : input) {
line.chars().forEach(move1(pos));
code = code * 10 + 3 * pos[1] + pos[0] + 1;
}
return code;
}
private IntConsumer move1(int[] pos) {
return i -> {
switch (i) {
case 'D': if (pos[1] < 2) ++pos[1]; break;
case 'U': if (pos[1] > 0) --pos[1]; break;
case 'R': if (pos[0] < 2) ++pos[0]; break;
case 'L': if (pos[0] > 0) --pos[0]; break;
}
};
}
private static final char[] KEYPAD = new char[] { '1', '3', '7', 'B', 'D' };
public String a2() {
int[] pos = new int[] { -2, 0 };
StringBuilder code = new StringBuilder();
for (String line : input) {
line.chars().forEach(move2(pos));
code.appendCodePoint(KEYPAD[pos[1] + 2] + pos[0]);
}
return code.toString();
}
private IntConsumer move2(int[] pos) {
return i -> {
switch (i) {
case 'D': if (pos[1] + abs(pos[0]) < 2) ++pos[1]; break;
case 'U': if (pos[1] - abs(pos[0]) > -2) --pos[1]; break;
case 'R': if (pos[0] + abs(pos[1]) < 2) ++pos[0]; break;
case 'L': if (pos[0] - abs(pos[1]) > -2) --pos[0]; break;
}
};
}
}
|
package pl.ark.chr.buginator.persistence.security;
import pl.ark.chr.buginator.domain.core.Application;
/**
* Used for security reason. Each class implementing this interface should be filtered to return only
* this data that match given Application
*/
public interface FilterData {
Application getApplication();
}
|
package co.nos.noswallet.ui.addWallet;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import javax.inject.Inject;
import co.nos.noswallet.R;
import co.nos.noswallet.persistance.currency.CryptoCurrency;
import co.nos.noswallet.ui.common.ActivityWithComponent;
import co.nos.noswallet.ui.common.BaseDialogFragment;
import co.nos.noswallet.ui.common.WindowControl;
import co.nos.noswallet.util.Mutator;
public class AddAccountDialogFragment extends BaseDialogFragment implements AddAccountView {
public static String TAG = AddAccountDialogFragment.class.getSimpleName();
public static String CRYPTOCURRENCY = "CRYPTOCURRENCY";
private TextView errorLabel, currencyName;
private ImageView currencyIcon;
private TextInputLayout sub_account_name_layout;
private TextInputEditText sub_account_name;
private Handler handler;
private CryptoCurrency cryptoCurrency;
@Inject
AddAccountPresenter presenter;
public static AddAccountDialogFragment newInstance(CryptoCurrency currency) {
Bundle args = new Bundle();
AddAccountDialogFragment fragment = new AddAccountDialogFragment();
args.putSerializable(CRYPTOCURRENCY, currency);
fragment.setArguments(args);
return fragment;
}
public static void showFrom(FragmentActivity activity,
CryptoCurrency currency,
Runnable endAction) {
if (activity instanceof WindowControl) {
AddAccountDialogFragment dialog = AddAccountDialogFragment.newInstance(currency);
dialog.show(((WindowControl) activity).getFragmentUtility().getFragmentManager(),
AddAccountDialogFragment.TAG);
((WindowControl) activity).getFragmentUtility().getFragmentManager().executePendingTransactions();
dialog.getDialog().setOnDismissListener(dialog1 -> {
if (endAction != null) {
endAction.run();
}
});
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler(Looper.getMainLooper());
if (getArguments() != null) {
cryptoCurrency = (CryptoCurrency) getArguments().getSerializable(CRYPTOCURRENCY);
}
if (cryptoCurrency == null) {
cryptoCurrency = CryptoCurrency.defaultCurrency();
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
if (getActivity() instanceof ActivityWithComponent) {
((ActivityWithComponent) getActivity()).getActivityComponent().inject(this);
}
view = inflater.inflate(R.layout.fragment_add_account, container, false);
setStatusBar();
sub_account_name = view.findViewById(R.id.sub_account_name);
sub_account_name_layout = view.findViewById(R.id.sub_account_name_layout);
currencyIcon = view.findViewById(R.id.nollar_image);
currencyName = view.findViewById(R.id.nollar);
errorLabel = view.findViewById(R.id.representative_label_error);
TextView saveButton = view.findViewById(R.id.visible_currencies_save);
currencyName.setText(cryptoCurrency.name());
setupCurrencyDrawable(cryptoCurrency);
setupToolbar(getString(R.string.add_sub_account));
presenter.attachView(this);
saveButton.setOnClickListener(v -> {
String name = String.valueOf(sub_account_name.getText());
presenter.attemptAddNewSubAccount(cryptoCurrency, name);
});
presenter.requestSubAccountsLeft(cryptoCurrency);
return view;
}
public void setupCurrencyDrawable(CryptoCurrency currency) {
switch (currency) {
case NOLLAR:
setupDrawable(R.drawable.ic_arrow_blue, scaleIcon(1.2f));
break;
case NOS:
int drawable = isDarkTheme() ? R.drawable.ic_arrow_white : R.drawable.ic_arrow_black;
setupDrawable(drawable, scaleIcon(1.2f));
break;
case NANO:
setupDrawable(R.drawable.nano_launcher_foreground_black, scaleIcon(0.8f));
break;
case BANANO:
setupDrawable(R.drawable.banano_launcher_foreground_black, scaleIcon(1.5f));
break;
}
}
private Mutator<ImageView> scaleIcon(float scaleFactor) {
return view -> {
view.setScaleY(scaleFactor);
view.setScaleX(scaleFactor);
};
}
protected void setupDrawable(int drawable,
Mutator<ImageView> mutator) {
currencyIcon.setImageResource(drawable);
mutator.mutate(currencyIcon);
}
@Override
public void dismiss() {
super.dismiss();
handler.removeCallbacksAndMessages(null);
}
@Override
public void showAccountNameAlreadyExists(String name) {
sub_account_name_layout.setErrorEnabled(true);
sub_account_name_layout.setError("Hey! Sub-account named \"" + name + "\" already exists");
}
@Override
public void showExceededAccountsLimit(int subaccountsSize, CryptoCurrency currency) {
errorLabel.setTextColor(ContextCompat.getColor(getActivity(), R.color.red));
errorLabel.setText("Hey! You has exceeded sub-accounts limit which is " + subaccountsSize + " for " + currency.name());
}
@Override
public void clearNameError() {
sub_account_name_layout.setErrorEnabled(false);
}
@Override
public void showNameEmpty() {
sub_account_name_layout.setErrorEnabled(true);
sub_account_name_layout.setError(getString(R.string.field_cannot_be_blank));
}
@Override
public void showAccountsLeftInfo(int left, CryptoCurrency currency) {
errorLabel.setTextColor(isDarkTheme() ? Color.WHITE : Color.BLACK);
errorLabel.setText("You have " + left + " accounts left for " + currency.name());
}
@Override
public void showAccountAdded() {
errorLabel.setTextColor(ContextCompat.getColor(getActivity(), R.color.green));
errorLabel.setText("Sub-account added!");
handler.postDelayed(this::dismiss, 500);
}
}
|
/*
* 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 Controller;
import Database.Database;
import Model.Aplikasi;
import Model.Jasa;
import View.ViewListJasa;
import java.awt.HeadlessException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
public final class ControllerViewListJasa implements ActionListener{
ViewListJasa VJ = new ViewListJasa();
Aplikasi app;
public ControllerViewListJasa(Aplikasi app){
this.app = app;
VJ.setVisible(true);
VJ.addActionListener(this);
showJasa();
}
public void showJasa(){
Database db = new Database();
ArrayList<Jasa> ListJasa = db.getListJasa();
DefaultTableModel model = (DefaultTableModel)VJ.getTableDataJasa().getModel();
Object[] row = new Object[3];
for (int i = 0; i < ListJasa.size(); i++){
row[0] = ListJasa.get(i).getIdJasa();
row[1] = ListJasa.get(i).getNamaJasa();
row[2] = ListJasa.get(i).getTarif();
model.addRow(row);
}
}
public void executeSQLQuery(String query, String pesan){
Database db = new Database();
Connection con = db.getConnection();
Statement st;
try{
st = con.createStatement();
if (st.executeUpdate(query) == 1){
DefaultTableModel model = (DefaultTableModel)VJ.getTableDataJasa().getModel();
model.setRowCount(0);
showJasa();
JOptionPane.showMessageDialog(null, "Database berhasil diakses dan "+pesan);
} else {
JOptionPane.showMessageDialog(null, "Database gagal diakses dan "+pesan);
}
} catch (HeadlessException | SQLException ex){
JOptionPane.showMessageDialog(null, "Maaf, koneksi database anda gagal dan "+pesan);
}
}
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == VJ.getButtonBack()){
ControllerMenuPetugas controllerMenuPetugas = new ControllerMenuPetugas(app);
this.VJ.setVisible(false);
}
}
}
|
/*
* 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 controller;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import modle.AuthUser;
import modle.UserCat;
/**
* FXML Controller class
*
* @author RM.LasanthaRanga@gmail.com
*/
public class SelectLoginTypeController implements Initializable {
@FXML
private JFXComboBox<String> com_type;
@FXML
private JFXButton btn_log;
List<UserCat> userCats;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
ObservableList List = FXCollections.observableArrayList();
userCats = AuthUser.getUserCats();
for (UserCat userCat : userCats) {
List.add(userCat.getOthoname());
}
com_type.setItems(List);
btn_log.setOnAction((event) -> {
getSelected();
});
}
public void getSelected() {
String selectedItem = com_type.getSelectionModel().getSelectedItem();
for (UserCat userCat : userCats) {
if (userCat.getOthoname().equals(selectedItem)) {
try {
AuthUser.setIdOc(userCat.getOthoid());
btn_log.getParent().getScene().getWindow().hide();
AnchorPane paymant = javafx.fxml.FXMLLoader.load(getClass().getResource("/view/authoritist.fxml"));
btn_log.getParent().getScene();
Scene scene = new Scene(paymant);
Stage stage = new Stage();
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
stage.show();
} catch (IOException ex) {
ex.printStackTrace();
Logger.getLogger(PayController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
|
package com.zealot.mytest.security.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.zealot.mytest.po.User;
import com.zealot.mytest.po.UserRole;
import com.zealot.mytest.security.entity.SysUserEntity;
import com.zealot.mytest.service.UserRoleService;
import com.zealot.mytest.service.UserService;
@Service("userDetailsService")
public class CustomUserService implements UserDetailsService {
@Resource(name="userService")
private UserService userService;
@Resource(name="userRoleService")
private UserRoleService userRoleService;
@Override
public UserDetails loadUserByUsername(String name)
throws UsernameNotFoundException {
User user = userService.findUserByLoginName(name);
if( user == null ){
throw new UsernameNotFoundException(String.format("User with username=%s was not found", name));
}
SysUserEntity sysUser = new SysUserEntity();
sysUser.setId((long)user.getUid());
sysUser.setPassword(user.getPwd());
sysUser.setUsername(user.getUname());
List<UserRole> userRoleList = userRoleService.findByUser(user.getUid());
sysUser.setRoles(userRoleList);
return sysUser;
}
}
|
package banyuan.day09.package02;
/**
* @author 陈浩
* @date Created on 2019/11/3
* 3.键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩)
* ,按照总分从高到低输出到控制台
*/
public class Student implements Comparable {
private String name;
private int ChineseScore;
private int mathScore;
private int EnglishScore;
public Student() {
}
public Student(String name, int chineseScore, int mathScore, int englishScore) {
this.name = name;
ChineseScore = chineseScore;
this.mathScore = mathScore;
EnglishScore = englishScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChineseScore() {
return ChineseScore;
}
public void setChineseScore(int chineseScore) {
ChineseScore = chineseScore;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
public int getEnglishScore() {
return EnglishScore;
}
public void setEnglishScore(int englishScore) {
EnglishScore = englishScore;
}
public int getSumScore() {
return EnglishScore + mathScore + ChineseScore;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", ChineseScore=" + ChineseScore +
", mathScore=" + mathScore +
", EnglishScore=" + EnglishScore +
'}';
}
@Override
public int compareTo(Object o) {
Student s = (Student) o;
int result = -(this.getSumScore() - s.getSumScore());
return result;
}
}
|
public class GenaricDemo1 {
public static void main(String[] args) {
Demo <String> d1 = new Demo<String>();
d1.coll("sadf");
d1.print(1234);
d1.show("asqwdvvcw");
}
}
class Demo<T>{
public void show( T t ){
System.out.println(t);
}
public <A> void coll(A s){
System.out.println(s);
}
public static <Q> void print(Q q){
System.out.println(q);
}
}
/*class Student extends Person{
public Student(String arg0, int arg1) {
super(arg0, arg1);
}
}*/
/*class Person{
private String name;
private int age ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
}*/
|
package com.nearur.daa;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class QuickSort extends AppCompatActivity {
Button merge;
TextView result;
CheckedTextView checkedTextView;
EditText editText;
int[] array;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quick_sort);
editText=(EditText)findViewById(R.id.editTextquicklist);
merge=(Button)findViewById(R.id.buttonquick);
result=(TextView)findViewById(R.id.textViewquickresult);
checkedTextView=(CheckedTextView)findViewById(R.id.checkedTextViewalgoquick);
merge.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(editText.getText().toString().length()>0){
String[] strings=editText.getText().toString().trim().split(",");
array=new int[strings.length];
for(int i=0;i<array.length;i++){
array[i]=Integer.parseInt(strings[i].trim());
}
sort(0,array.length-1);
StringBuffer buffer=new StringBuffer();
for(int x:array){
buffer.append(x+",");
}
result.setVisibility(View.VISIBLE);
result.setText("Sorted List \n"+buffer.toString().substring(0,buffer.length()-1));
}else{
Toast.makeText(QuickSort.this,"Please Enter Valid List",Toast.LENGTH_LONG).show();
}
}
});
merge.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
checkedTextView.setVisibility(View.VISIBLE);
checkedTextView.setText("void sort(int start,int end) {\n" +
" if(start<end) {\n" +
"\n" +
" int q=partition(start, end);\n" +
"\n" +
" partition(start, q);\n" +
"\n" +
" partition(q+1, end);\n" +
"\n" +
" }return;\n" +
" }\n" +
"\n" +
" int partition( int p, int r)\n" +
" {\n" +
" int i, pivot, temp;\n" +
" pivot = array[r];\n" +
" i = p;\n" +
" for(int j=p;j<r;j++) {\n" +
" if(array[j]<pivot) {\n" +
" temp=array[i];\n" +
" array[i]=array[j];\n" +
" array[j]=temp;\n" +
" i++;\n" +
" }\n" +
" }\n" +
" temp=array[i];\n" +
" array[i]=array[r];\n" +
" array[r]=temp;\n" +
" return i;\n" +
" }\n");
return false;
}
});
}
void sort(int start,int end) {
if(start<end) {
int q=partition(start, end);
sort(start, q-1);
sort(q+1, end);
}return;
}
int partition( int p, int r)
{
int i, pivot, temp;
pivot = array[r];
i = p;
for(int j=p;j<r;j++) {
if(array[j]<pivot) {
temp=array[i];
array[i]=array[j];
array[j]=temp;
i++;
}
}
temp=array[i];
array[i]=array[r];
array[r]=temp;
return i;
}
}
|
package com.example.sonic.whatdoyoudo.utils;
import android.util.Log;
import com.opencsv.CSVWriter;
import java.io.FileWriter;
/**
* Created by sonic on 03/04/2017.
*/
public class Dataset {
private CSVWriter writer;
private String[] header;
public String createDataset(String[] entries, boolean newDataset) {
if (newDataset) {
header = new String[]{
"MeanX", "MeanY", "MeanZ",
"StdDevX", "StdDevY", "StdDevZ",
"MaxX", "MaxY", "MaxZ",
"MinX", "MinY", "MinZ",
"Class"
};
if(writeToFile(header, false)){
if (writeToFile(entries, true)) {
return "New dataset created";
}else {
return "Fail created dataset";
}
} else {
return "Fail created header";
}
} else {
if (writeToFile(entries, true)){
return "Dataset added";
} else {
return "File record dataset";
}
}
}
private boolean writeToFile(String[] data, boolean append) {
try {
writer = new CSVWriter(new FileWriter("/sdcard/dataset.csv", append), ',');
writer.writeNext(data);
writer.close();
return true;
} catch (Exception e) {
String c = e.toString();
// Log.i("err", e.toString());
return false;
}
}
}
|
package com.lingnet.vocs.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.lingnet.common.entity.BaseEntity;
@Entity
@Table(name = "follow")
public class Follow extends BaseEntity implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = -5019464227885006397L;
private String status;//阶段 费用
private String reportId;//关联报备
private Date bftime;//拜访时间
private String bfnr;//拜访内容
private String cyr;//参与人
private String khcyr;//客户参与人
private String bz;//备注
private String bffs;//拜访方式
private String userId;//创建人
private String partnerId;//经销商id
private String threadId;//上传资料
private String projectName;//项目名称
private String cusComName;//客户名称
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getBftime() {
return bftime;
}
public void setBftime(Date bftime) {
this.bftime = bftime;
}
public String getBfnr() {
return bfnr;
}
public void setBfnr(String bfnr) {
this.bfnr = bfnr;
}
public String getCyr() {
return cyr;
}
public void setCyr(String cyr) {
this.cyr = cyr;
}
public String getKhcyr() {
return khcyr;
}
public void setKhcyr(String khcyr) {
this.khcyr = khcyr;
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
public String getBffs() {
return bffs;
}
public void setBffs(String bffs) {
this.bffs = bffs;
}
public String getReportId() {
return reportId;
}
public void setReportId(String reportId) {
this.reportId = reportId;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getCusComName() {
return cusComName;
}
public void setCusComName(String cusComName) {
this.cusComName = cusComName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPartnerId() {
return partnerId;
}
public void setPartnerId(String partnerId) {
this.partnerId = partnerId;
}
public String getThreadId() {
return threadId;
}
public void setThreadId(String threadId) {
this.threadId = threadId;
}
}
|
package pacman.board;
import pacman.util.Position;
import java.util.Arrays;
import java.util.Objects;
import java.util.StringJoiner;
/**
* Represents the Pac Man game board.
* The board can be any size,
* it is set out as a grid with each space containing only one BoardItem.
* Game boards are by default surrounded
* by a BoardItem.WALL with every other space being BoardItem.NONE.
* Example: a board with width 1 and height 1 would look like this:
*
* X
*
* A board with width 4 and height 4 would look like this:
* XXXX
* X00X
* X00X
* XXXX
*
* The coordinate positions for the board is the
* top left position is (0, 0) and the bottom right position is
* (getWidth-1, getHeight-1).
*/
public class PacmanBoard {
/**
* Width of the game board
*/
private int width;
/**
* Height of the game board
*/
private int height;
/**
* The board grid
*/
private BoardItem[][] board;
private Position pacmanSpawn;
private Position ghostSpawn;
/**
* Constructor taking the width and height creating a board that is filled with
* BoardItem.NONE except a 1 block wide border wall around the entire board ( BoardItem.WALL ).
* @param width - the horizontal size of the board which is greater than zero.
* @param height - the vertical size of the board which is greater than zero.
* @throws IllegalArgumentException - when height || width is less than or equal to 0.
*/
public PacmanBoard(int width, int height) throws IllegalArgumentException {
if ((width <= 0) || (height <= 0)) {
throw new IllegalArgumentException();
}
this.width = width;
this.height = height;
this.board = new BoardItem[width][height];
for (int i = 0; i < width ; i++) {
for (int j = 0; j < height; j++) {
if ((i == 0 || i == width - 1) || (j == 0 || j == height - 1)) {
this.board[i][j] = BoardItem.WALL;
} else {
this.board[i][j] = BoardItem.NONE;
}
}
}
}
/**
* Constructor taking an existing PacmanBoard and making a deep copy.
* A deep copy should have the same getWidth, getHeight and board as the given board.
* When a change is made to the other board this should not change this copy.
* @param other - copy of an existing PacmanBoard.
* @throws NullPointerException - if copy is null.
*/
public PacmanBoard(PacmanBoard other) throws NullPointerException {
if (other == null) {
throw new NullPointerException();
}
this.width = other.width;
this.height = other.height;
this.board = new BoardItem[width][height];
for (int i = 0; i < width; i++) {
this.board[i] = other.board[i].clone();
}
}
/**
* Gets the width of the board
* @return width of the game board
*/
public int getWidth() {
return width;
}
/**
* Gets the height of the board
* @return height of the board
*/
public int getHeight() {
return height;
}
/**
* Sets a tile on the board to an item.
* If the item to be set is a BoardItem.PACMAN_SPAWN and the board already
* contains a BoardItem.PACMAN_SPAWN then the old BoardItem.PACMAN_SPAWN
* should be made a BoardItem.NONE. If the item to be set is a
* BoardItem.GHOST_SPAWN and the board already contains a BoardItem.GHOST_SPAWN
* then the old BoardItem.GHOST_SPAWN should be made a BoardItem.NONE.
* @param position - the portion to place the item.
* @param item - the board item that is to be placed at the position.
* @throws IndexOutOfBoundsException - when the position trying to be set is not within the board.
* @throws NullPointerException - when the position or item is null.
*/
public void setEntry(Position position, BoardItem item)
throws IndexOutOfBoundsException, NullPointerException {
if (position == null || item == null) {
throw new NullPointerException();
}
if (item == BoardItem.PACMAN_SPAWN) {
if (getPacmanSpawn() != null) {
board[getPacmanSpawn().getX()][getPacmanSpawn().getY()] = BoardItem.NONE;
}
board[position.getX()][position.getY()] = BoardItem.PACMAN_SPAWN;
this.pacmanSpawn = new Position(position.getX(), position.getY());
} else if (item == BoardItem.GHOST_SPAWN) {
if (getGhostSpawn() != null) {
board[getGhostSpawn().getX()][getGhostSpawn().getY()] = BoardItem.NONE;
}
board[position.getX()][position.getY()] = BoardItem.GHOST_SPAWN;
this.ghostSpawn = new Position(position.getX(), position.getY());
} else {
board[position.getX()][position.getY()] = item;
}
}
/**
* Returns what item the board has on a given position.
* @param position - wanting to be checked
* @return BoardItem at the location given.
* @throws IndexOutOfBoundsException - when the position is not within the board.
* @throws NullPointerException - if position is null.
*/
public BoardItem getEntry(Position position)
throws IndexOutOfBoundsException, NullPointerException {
if (position == null) {
throw new NullPointerException();
}
return board[position.getX()][position.getY()];
}
/**
* Tries to eat a dot off the board and returns the item that it ate/tried to eat.
* If a BoardItem.DOT is eaten then it is replaced with a BoardItem.NONE.
* If a BoardItem.BIG_DOT is eaten then it is replaced with a BoardItem.BIG_DOT_SPAWN.
* If the item is any other BoardItem then do nothing and return the item.
* @param position - to eat.
* @return the item that was originally the position before trying to eat.
* @throws IndexOutOfBoundsException - if position is null.
* @throws NullPointerException - when the position trying to be eaten is not within the board.
*/
public BoardItem eatDot(Position position) throws IndexOutOfBoundsException, NullPointerException {
BoardItem item = this.board[position.getX()][position.getY()];
if (item == BoardItem.DOT) {
setEntry(position, BoardItem.NONE);
return BoardItem.DOT;
} else if (item == BoardItem.BIG_DOT) {
setEntry(position, BoardItem.BIG_DOT_SPAWN);
return BoardItem.BIG_DOT;
} else {
return item;
}
}
/**
* Get the spawn position for pacman.
* @return the postion of pacmans spawn or null if none found.
*/
public Position getPacmanSpawn() {
return pacmanSpawn;
}
/**
* Get the spawn position for the ghosts.
* @return the position of the ghost spawn or null if none found.
*/
public Position getGhostSpawn() {
return ghostSpawn;
}
/**
* Checks if the board contains any pickup items.
* @return true if the board does not contain any DOT's or BIG_DOT's.
*/
public boolean isEmpty() {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if ((this.board[i][j] == BoardItem.BIG_DOT)
|| (this.board[i][j] == BoardItem.DOT)) {
return false;
}
}
}
return true;
}
/**
* Resets the board to place a DOT in every position that
* has no item ( NONE BoardItem ) and respawns BIG_DOT's in
* the BIG_DOT_SPAWN locations. Leaves walls, pacman spawns and ghost spawns intact.
*/
public void reset() {
// place DOTs where NONEs are
// respawn BIG_DOTS in BIG_DOT_SPAWNS
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (this.board[i][j] == BoardItem.NONE) {
this.board[i][j] = BoardItem.DOT;
}
if (this.board[i][j] == BoardItem.BIG_DOT_SPAWN) {
this.board[i][j] = BoardItem.BIG_DOT;
}
}
}
}
/**
* Checks if another object instance is equal to this instance.
* Boards are equal if they have the same dimensions (width, height)
* and have equal items for all board positions.
* @param o - Object to be compared to
* @return - true if same, false otherwise.
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof PacmanBoard)) {
return false;
}
PacmanBoard pacmanBoard = (PacmanBoard) o;
return (this.getHeight() == pacmanBoard.getHeight())
&& (this.getWidth() == pacmanBoard.getWidth());
}
/**
* For two objects that are equal the hash should also be equal.
* For two objects that are not equal the hash does not have to be different.
* @return hash of PacmanBoard.
*/
@Override
public int hashCode() {
return Objects.hash(width, height);
}
/**
* Creates a multiline string ( using System.lineSeparator() as newline )
* that is a printout of each index of the board with the character key.
* Example of a board with height 3 width 4.
*
* XXXX
* X00X
* XXXX
*
* Note: the lines are not indented but may show in the JavaDoc as such.
* There are no spaces. The last line does not have a newline.
* @return board as a multiline string.
*/
@Override
public String toString() {
StringJoiner joiner = new StringJoiner(System.lineSeparator());
for (int y = 0; y < height; y++) {
StringBuilder rowBuilder = new StringBuilder();
for (int x = 0; x < width; x++) {
rowBuilder.append(getEntry(new Position(x, y)).getChar());
}
joiner.add(rowBuilder.toString());
}
return joiner.toString();
}
}
|
package com.javalogicalprograms;
import java.util.*;
public class RemoveDuplicateElementsInIntegerArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {25, 26, 11, 16, 25, 11, 35, 25, 16, 11};
int len = a.length;
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
if(a[i] == a[j])
{
a[j] = a[len-1];
len--;
j--;
}
}
}
for(int i=0;i<len;i++)
{
System.out.print(a[i]+", ");
}
System.out.println();
System.out.println("************* Next Method **************");
//Method 2
Set<Integer> s = new TreeSet<>();
for(int i:a)
{
s.add(i);
}
System.out.println();
System.out.print("Unique Elements are: "+s);
}
}
|
package Management.HumanResources.FinancialSystem.DataAccessObject;
import Management.HumanResources.BaseDepartment;
import Management.HumanResources.BaseEmployee;
import java.io.IOException;
/**
* 人员薪资的数据操作接口
* <b> 使用了DAO模式 </b>
*
* @author 尚丙奇
* @since 2021-10-16 14:00
*/
public abstract interface SalaryDao {
public Double getSumActualSalary(BaseDepartment department);
public void setSalary(BaseDepartment department, String name, Double salary);
public void saveSalary(BaseDepartment department) throws IOException;
public void updateSalary(BaseEmployee employee) throws IOException;
}
|
package io.github.namhyungu.algorithm.baekjoon.backtracking;
import java.util.Scanner;
public class Solution14888 {
private static int[] nums;
private static int[] operators;
private static int[] order;
private static int N;
private static int min;
private static int max;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
N = scanner.nextInt();
nums = new int[N];
operators = new int[4];
order = new int[N - 1];
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
for (int i = 0; i < N; i++) {
nums[i] = scanner.nextInt();
}
for (int i = 0; i < 4; i++) {
operators[i] = scanner.nextInt();
}
solution(0);
System.out.println(max);
System.out.println(min);
}
private static void solution(int idx) {
if (idx == N - 1) {
int calc = nums[0];
for (int i = 1; i < N; i++) {
int operator = order[i - 1];
if (operator == 0) {
calc += nums[i];
} else if (operator == 1) {
calc -= nums[i];
} else if (operator == 2) {
calc *= nums[i];
} else {
if (calc < 0) {
calc = -(Math.abs(calc) / nums[i]);
} else {
calc /= nums[i];
}
}
}
min = Math.min(min, calc);
max = Math.max(max, calc);
return;
}
for (int i = 0; i < 4; i++) {
if (operators[i] > 0) {
operators[i]--;
order[idx] = i;
solution(idx + 1);
operators[i]++;
}
}
}
}
|
package patterns.state;
public interface IState {
public void doAction();
}
|
package ro.redeul.google.go.formatter;
import com.ansorgit.plugins.bash.editor.formatting.noOpModel.NoOpBlock;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.formatting.FormattingModel;
import com.intellij.formatting.FormattingModelBuilder;
import com.intellij.formatting.FormattingModelProvider;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.ui.awt.RelativePoint;
import org.jetbrains.annotations.NotNull;
import ro.redeul.google.go.config.sdk.GoSdkData;
import ro.redeul.google.go.sdk.GoSdkTool;
import ro.redeul.google.go.sdk.GoSdkUtil;
import javax.swing.*;
import java.awt.*;
/**
* User: jhonny
* Date: 05/07/11
*/
public class GoFmt implements FormattingModelBuilder {
@NotNull
@Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
PsiFile containingFile = element.getContainingFile();
String currentCommandName = CommandProcessor.getInstance().getCurrentCommandName();
if (currentCommandName != null && currentCommandName.equals("Reformat Code")) {
formatDocument(containingFile);
}
ASTNode astNode = containingFile.getNode();
// return a block that does nothing
return FormattingModelProvider.createFormattingModelForPsiFile(containingFile, new NoOpBlock(astNode), settings);
}
private void formatDocument(final PsiFile psiFile) {
final Sdk sdk = GoSdkUtil.getGoogleGoSdkForFile(psiFile);
if (sdk == null) {
showBalloon(psiFile.getProject(), "Error formatting code", "There is no Go SDK attached to module/project.", MessageType.ERROR);
return;
}
final VirtualFile file = psiFile.getVirtualFile();
if (file == null) {
return;
}
// try to format using go's default formatter
final Document fileDocument = psiFile.getViewProvider().getDocument();
// commit file changes to disk
if (fileDocument != null) {
PsiDocumentManager.getInstance(psiFile.getProject()).performForCommittedDocument(fileDocument, new Runnable() {
@Override
public void run() {
try {
final FileDocumentManager documentManager = FileDocumentManager.getInstance();
GeneralCommandLine command = new GeneralCommandLine();
String goFmtPath = GoSdkUtil.getTool((GoSdkData) sdk.getSdkAdditionalData(), GoSdkTool.GoFmt);
command.setExePath(goFmtPath);
command.addParameter("-w");
command.addParameter(file.getPath());
Process process = command.createProcess();
process.waitFor();
file.refresh(false, true);
documentManager.reloadFromDisk(fileDocument);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
}
@Override
public TextRange getRangeAffectingIndent(PsiFile psiFile, int i, ASTNode astNode) {
return null;
}
private static void showBalloon(Project project, String title, String message, MessageType messageType) {
// ripped from com.intellij.openapi.vcs.changes.ui.ChangesViewBalloonProblemNotifier
final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project);
if (frame == null) return;
final JComponent component = frame.getRootPane();
if (component == null) return;
final Rectangle rect = component.getVisibleRect();
final Point p = new Point(rect.x + rect.width - 10, rect.y + 10);
final RelativePoint point = new RelativePoint(component, p);
JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(
String.format("<html><body><strong>%s</strong><br/><p>%s</p></body></html>", title, message),
messageType.getDefaultIcon(), messageType.getPopupBackground(), null)
.setShowCallout(false)
.setFadeoutTime(2000)
.setPreferredPosition(Balloon.Position.above)
.setCloseButtonEnabled(true)
.createBalloon().show(point, Balloon.Position.atLeft);
}
}
|
package io.confluent.se.poc.streams;
import io.confluent.kafka.streams.serdes.avro.*;
import org.apache.kafka.streams.*;
import org.apache.kafka.streams.kstream.*;
import org.apache.kafka.common.serialization.*;
import org.apache.kafka.streams.state.*;
import org.apache.avro.generic.*;
import org.apache.avro.*;
import org.json.*;
import io.confluent.kafka.serializers.*;
//import java.util.*;
import java.io.*;
import java.util.concurrent.CompletableFuture;
public class AvroUtil {
public static GenericRecord transform(GenericRecord value1, GenericRecord value2) {
try {
InputStream is = new FileInputStream(System.getProperty("schema-file"));
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
String line = buf.readLine();
StringBuilder sb = new StringBuilder();
while(line != null){
sb.append(line).append("\n");
line = buf.readLine();
}
String streamSchema = sb.toString();
Schema.Parser parser = new Schema.Parser();
Schema schema = parser.parse(streamSchema);
GenericRecord avroRecord = new GenericData.Record(schema);
avroRecord.put("order_id", value1.get("order_id"));
avroRecord.put("sku", value1.get("sku"));
avroRecord.put("price", (Integer)value1.get("price"));
avroRecord.put("quantity", (Integer)value1.get("quantity"));
avroRecord.put("first_name", value2.get("first_name"));
avroRecord.put("last_name", value2.get("last_name"));
return avroRecord;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
|
package org.motechproject.server.model.rct;
import org.motechproject.ws.rct.ControlGroup;
public class ControlGroupAssignment {
private Integer id ;
private Integer assignmentNumber ;
private ControlGroup controlGroup;
public boolean hasAssignmentNumber(Integer nextAssignment) {
return assignmentNumber.equals(nextAssignment) ;
}
public ControlGroup group() {
return controlGroup;
}
}
|
package com.example.caroline.countme;
import android.content.Context;
import android.util.Log;
import java.io.FileOutputStream;
public class CsvWriter {
// some variables
String filename = "DataFile.csv";
// constructor, needs a Project
public CsvWriter(Project project) {
String[] StringArray = project.getData(); // get the String[] from the Project
String csvStr = makeCsvString(StringArray);
}
// method to take the String[] of project data and make it a string
public String makeCsvString(String[] data) {
String csvString = "";
for (int i = 0; i < data.length; i++) {
if (i < data.length - 1) {
csvString = csvString + data[i] + ",";
} else { //i = data.length - 1
csvString = csvString + data[i];
}
}
Log.d("CSVWriter made this", csvString);
return csvString;
}
// method to write a line of text (String) to a file
public void writeLineToCsv(String csvString, String filename, Context context) {
FileOutputStream outputStream;
try {
outputStream = context.openFileOutput(filename, context.MODE_PRIVATE);
outputStream.write(csvString.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package cn.wycclub.service;
import cn.wycclub.dao.po.OrderInfo;
import cn.wycclub.dao.po.UserInfo;
import cn.wycclub.dto.Order;
import java.util.List;
public interface BusinessOrdersService {
//添加订单(基于购物车)
Integer insertOrder(List<Integer> cids, int uid) throws Exception;
//通过订单号查询订单
OrderInfo selectOrderByKey(Integer id) throws Exception;
//通过用户ID查询用户所有订单
List<Order> selectOrderByUID(Integer id) throws Exception;
//添加订单(基于现在购买)
Integer insertOrder(Integer pid, Integer quantity, Integer uid) throws Exception;
//付款
boolean pay(Integer oid, UserInfo user) throws Exception;
//修改订单状态
boolean updateOrderState(int oid, int state);
}
|
package com.tencent.mm.plugin.appbrand.appcache;
import com.tencent.mm.a.e;
import com.tencent.mm.modelcdntran.g;
import com.tencent.mm.plugin.appbrand.q.h;
import com.tencent.mm.sdk.platformtools.al.a;
import java.util.concurrent.CountDownLatch;
class ah$a$1 implements a {
final /* synthetic */ CountDownLatch dKv;
final /* synthetic */ String fhh;
final /* synthetic */ s.a fhi;
final /* synthetic */ com.tencent.mm.plugin.appbrand.appcache.base.a fhj;
final /* synthetic */ h fhk;
final /* synthetic */ ah.a fhl;
ah$a$1(ah.a aVar, String str, s.a aVar2, com.tencent.mm.plugin.appbrand.appcache.base.a aVar3, h hVar, CountDownLatch countDownLatch) {
this.fhl = aVar;
this.fhh = str;
this.fhi = aVar2;
this.fhj = aVar3;
this.fhk = hVar;
this.dKv = countDownLatch;
}
public final boolean vD() {
g.ND().lx(this.fhh);
this.fhi.abt();
e.deleteFile(this.fhj.getFilePath());
this.fhk.value = null;
this.dKv.countDown();
return false;
}
}
|
package br.org.funcate.glue.controller;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.HashMap;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import br.org.funcate.eagles.kernel.dispatcher.EventDispatcher;
import br.org.funcate.eagles.kernel.dispatcher.EventHandler;
import br.org.funcate.eagles.kernel.listener.EventListener;
import br.org.funcate.eagles.kernel.listener.ListenersHandler;
import br.org.funcate.eagles.kernel.listener.ListenersHandlerImpl;
import br.org.funcate.eagles.kernel.transmitter.DirectedEventTransmitter;
import br.org.funcate.eagles.kernel.transmitter.EventTransmitter;
import br.org.funcate.glue.event.CleanThematicEvent;
import br.org.funcate.glue.event.GetOsEvent;
import br.org.funcate.glue.event.GetSelectFeatureEvent;
import br.org.funcate.glue.event.GetThemeAttributesEvent;
import br.org.funcate.glue.event.GetViewsEvent;
import br.org.funcate.glue.event.TreeThemeChangeEvent;
import br.org.funcate.glue.event.SetLabelContextEvent;
import br.org.funcate.glue.event.SetThematicContextEvent;
import br.org.funcate.glue.main.AppSingleton;
import br.org.funcate.glue.model.ContextToGroupMap;
import br.org.funcate.glue.model.ContextToLabelConfig;
import br.org.funcate.glue.model.Layer;
import br.org.funcate.glue.model.LoadingStatusService;
import br.org.funcate.glue.model.UserType;
import br.org.funcate.glue.model.canvas.CanvasService;
import br.org.funcate.glue.model.canvas.CanvasState;
import br.org.funcate.glue.model.exception.GlueServerException;
import br.org.funcate.glue.model.request.TextRequest;
import br.org.funcate.glue.model.tree.CustomNode;
import br.org.funcate.glue.model.tree.TreeService;
import br.org.funcate.glue.os.model.GenericTableModel;
import br.org.funcate.glue.os.view.ProgramServiceOrderScreen;
import br.org.funcate.glue.os.view.ServiceOrderCreatorScreen;
import br.org.funcate.glue.os.view.ServiceOrderOnMapScreen;
import br.org.funcate.glue.view.GlueMessageDialog;
import br.org.funcate.glue.view.TreeView;
public class TreeController implements EventDispatcher, EventListener {
private TreeView treeView;
private CustomNode lastTheme;
private ListenersHandler listenersHandler;
private EventHandler eventHandler;
private EventTransmitter eventTransmitter;
private List<String> eventsToListen;
public static DefaultListModel<String> listModel;
public static GenericTableModel dataModel;
public static ArrayList<HashMap<String, String>> osCoods;
public static String ip;
public static String osX;
public static String osY;
public TreeController(TreeView treeView) {
this.treeView = treeView;
AppSingleton.getInstance().getMediator().setTreeController(this);
listenersHandler = new ListenersHandlerImpl();
eventHandler = new EventHandler();
eventTransmitter = new DirectedEventTransmitter(this);
eventsToListen = new ArrayList<String>();
eventsToListen.add(GetViewsEvent.class.getName());
eventsToListen.add(GetThemeAttributesEvent.class.getName());
eventsToListen.add(SetThematicContextEvent.class.getName());
eventsToListen.add(CleanThematicEvent.class.getName());
eventsToListen.add(SetLabelContextEvent.class.getName());
eventsToListen.add(TreeThemeChangeEvent.class.getName());
eventsToListen.add(GetSelectFeatureEvent.class.getName());
eventsToListen.add(GetOsEvent.class.getName());
listModel = new DefaultListModel<String>();
}
public List<String> getEventsToListen() {
return this.eventsToListen;
}
CustomNode createRoot() {
try {
return TreeService.createRoot();
} catch (GlueServerException e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
return null;
}
}
public CustomNode getCurrentView() {
return TreeService.getCurrentView();
}
public void setCurrentView(CustomNode view) {
TreeService.setCurrentView(view);
}
public void setDefaultTreeModel(DefaultTreeModel defaultTreeModel) {
TreeService.setDefaultTreeModel(defaultTreeModel);
}
public DefaultTreeModel getDefaultTreeModel() {
return TreeService.getDefaultTreeModel();
}
public void renameNode() {
TreeService.renameNode();
}
public void deleteNode() {
TreeService.removeNode();
}
public CustomNode getCurrentTheme() {
return TreeService.getCurrentTheme();
}
public void setCurrentTheme(CustomNode theme) {
TreeService.setCurrentTheme(theme);
boolean change = TreeService.checkThemeChange(theme.getName());
TreeThemeChangeEvent e = new TreeThemeChangeEvent(this);
e.setChange(change);
e.setOldTheme(getLastTheme());
dispatch(e);
}
public CustomNode getLastTheme() {
return lastTheme;
}
public void setLastTheme(CustomNode lastTheme) {
this.lastTheme = lastTheme;
}
public void createViewUpdator(Boolean reload, Boolean memory, Boolean remove) {
TreeService.createViewUpdator(reload, memory, remove);
}
public boolean checkAllNodes(CustomNode root, CustomNode compare) {
return TreeService.checkAllNodes(root, compare);
}
public void setUserType(UserType userType) {
TreeService.setUserType(userType);
}
public UserType getUserType() {
return TreeService.getUserType();
}
public void setSelectedNode(CustomNode selectedNode) {
TreeService.setSelectedNode(selectedNode);
}
public CustomNode getSelectedNode() {
return TreeService.getSelectedNode();
}
CustomNode createToolBar() {
return TreeService.createToolbar();
}
public void copyNode() {
TreeService.copyNode();
}
public void cutNode() {
TreeService.cutNode();
}
public void pasteNode() {
TreeService.pasteNode();
}
public CustomNode getNodeView(CustomNode parent) {
return TreeService.getNodeView(parent);
}
public void rearrange(int index, CustomNode root, CustomNode nodeSource) {
TreeService.rearrange(index, root, nodeSource);
}
public void moveNode(CustomNode targetView, CustomNode sourceView) {
TreeService.moveNode(targetView, sourceView);
}
public CustomNode getRoot() {
return TreeService.getRoot();
}
public void setVisible(boolean visible) {
treeView.setVisible(visible);
}
void applyView() {
TreeService.applyView();
}
public List<CustomNode> getSelectedThemes() {
return TreeService.getSelectedThemes();
}
public void setSelectionPath(TreePath treePath) {
treeView.getTree().setSelectionPath(treePath);
}
void repaint() {
treeView.repaint();
}
public CustomNode getLastSelectedPathComponent() {
return (CustomNode) treeView.getTree().getLastSelectedPathComponent();
}
public TreePath getSelectionPath() {
return treeView.getTree().getSelectionPath();
}
void expandPath(TreePath path) {
treeView.getTree().expandPath(path);
}
void scrollPathToVisible(TreePath path) {
treeView.getTree().scrollPathToVisible(path);
}
void disableTree() {
LoadingStatusService.addThreadCount();
treeView.setVisible(false);
}
void enableTree() {
treeView.setVisible(true);
LoadingStatusService.removeThreadCount();
}
void collapsePath(TreePath path) {
treeView.getTree().collapsePath(path);
}
void addNode(CustomNode node, CustomNode parent) {
TreeService.addNode(node, parent);
}
public List<Layer> getLayers() {
return TreeService.getLayers();
}
void removeNodeFromParent(CustomNode node) {
TreeService.removeNodeFromParent(node);
}
Boolean updateSelectedView(Boolean isReload, Boolean isViewMem) {
try {
return TreeService.updateSelectedView(isReload, isViewMem);
} catch (GlueServerException e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
return false;
}
}
void reload() {
TreeService.reload();
}
public void setNodeSource(CustomNode nodeSource) {
TreeService.setNodeSource(nodeSource);
}
@Override
public void handle(EventObject e) {
if (e instanceof GetViewsEvent) {
this.handle((GetViewsEvent) e);
} else if (e instanceof GetThemeAttributesEvent) {
this.handle((GetThemeAttributesEvent) e);
} else if (e instanceof SetThematicContextEvent) {
this.handle((SetThematicContextEvent) e);
} else if (e instanceof CleanThematicEvent) {
this.handle((CleanThematicEvent) e);
} else if (e instanceof SetLabelContextEvent) {
this.handle((SetLabelContextEvent) e);
} else if (e instanceof TreeThemeChangeEvent){
this.handle((TreeThemeChangeEvent) e);
} else if (e instanceof GetSelectFeatureEvent){
this.handle((GetSelectFeatureEvent)e);
}else if (e instanceof GetOsEvent){
this.handle((GetOsEvent)e);
}
}
private void handle(GetOsEvent e){
String[]columnNames = {"OsID", "Ocorrence", "Status"};
Object[][] data;
data = new Object[e.getOsIDs().size()][columnNames.length];
for (int i = 0; i < e.getOsIDs().size(); i++) {
data[i][0] = e.getOsIDs().get(i);
data[i][1] = e.getOcorrences().get(i);
data[i][2] = e.getStatus().get(i);
}
dataModel = new GenericTableModel(columnNames, data);
}
private void handle(GetSelectFeatureEvent e){
String id = e.getFeatureId();
AppSingleton singleton = AppSingleton.getInstance();
CanvasState state = singleton.getCanvasState();
ip = e.getOsIP();
osX = e.getOsX();
osY = e.getOsY();
// listModel.clear();
//boolean inList = true;
if(!id.equals("")){
// if (!listModel.isEmpty()) {
// for (int i = 0; i < listModel.size(); i++) {
// if (listModel.get(i).equals(id))
// inList = true;
// }
// }
if (state.getGvSourceType()=="ip") {
//listModel.addElement(id);
ServiceOrderCreatorScreen.getInstance().getTextIP().setText(id);
ServiceOrderCreatorScreen.getInstance().setVisible(true);
}else if(state.getGvSourceType()=="os"){
ProgramServiceOrderScreen.getInstance().getTextOS().setText(id);
ProgramServiceOrderScreen.getInstance().setVisible(true);
}
}else{
GlueMessageDialog.show("this ip has no Id", null, 2);
}
}
private void handle(SetLabelContextEvent e){
ContextToLabelConfig contextToLabelConfig = e.getContext();
TextRequest.setContextToLabelConfig(contextToLabelConfig);
new TextRequest().start();
}
private void handle(TreeThemeChangeEvent e) {
}
private void handle(CleanThematicEvent e) {
this.cleanGroupThemes();
try {
CanvasService.draw(true, false);
} catch (GlueServerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private void handle(GetViewsEvent e) {
e.setViews(TreeService.getViews());
}
private void handle(GetThemeAttributesEvent e) {
try {
e.setAttributes(TreeService.getAttributes(e.getViewName(),
e.getThemeName()));
} catch (GlueServerException e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
}
}
private void handle(SetThematicContextEvent e) {
AppSingleton singleton = AppSingleton.getInstance();
ContextToGroupMap contextToGroupMap = e.getParameters();
singleton.setGroupMapParameters(contextToGroupMap);
this.setThematicTheme(contextToGroupMap.getView(),
contextToGroupMap.getTheme());
try {
CanvasService.draw(true, false);
} catch (GlueServerException exception) {
exception.printStackTrace();
// TODO AGUARDANDO IMPLEMENTAÇÃO DO EXCEPTION HANDLER
}
}
@Override
public ListenersHandler getListenersHandler() {
return listenersHandler;
}
@Override
public EventHandler getEventHandler() {
return eventHandler;
}
@Override
public void dispatch(EventTransmitter tc, EventObject e) throws Exception {
tc.dispatch(e);
}
private void setThematicTheme(String viewName, String themeName) {
TreeService.setThematicTheme(viewName, themeName);
}
private void cleanGroupThemes() {
TreeService.cleanGroupThemes();
}
public void dispatch(EventObject e) {
try {
dispatch(this.eventTransmitter, e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
|
public class DezePerMazaRuntimeException extends RuntimeException{
public DezePerMazaRuntimeException(String message) {
super(message);
}
}
|
/*
* 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 br.com.fatecpg.oo;
/**
*
* @author Manoel Rodriguez
*/
public class Main {
public static void main(String[] args) {
Horario horaAtual = new Horario();
horaAtual.setHoras(14);
horaAtual.setMinutos(51);
horaAtual.setMinutos(43);
Horario horaIntervalo = new Horario();
horaIntervalo.setHoras(14);
horaIntervalo.setMinutos(50);
horaIntervalo.setMinutos(00);
//CLASSE DATA
Data hoje = new Data();
hoje.setDia(25);
hoje.setMes(03);
hoje.setAno(2019);
}
}
|
package chapter08;
public class Exercise08_03 {
public static void main(String[] args) {
char[][] answers = {
{'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
{'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'},
{'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'},
{'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'},
{'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
{'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
{'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'},
{'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}};
char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};
printGradesByPoints(answers, keys);
}
public static void printGradesByPoints(char[][] answers, char[] rightKeys) {
int[] sortOfGrades = new int[answers.length];
String[] sortOfStudents = new String[answers.length];
for (int i = 0; i < answers.length; i++) {
int grade=0;
for (int j = 0; j < answers[i].length; j++) {
grade=(answers[i][j]==rightKeys[j])?(grade+=1):(grade+=0);
}
sortOfGrades[i]=grade;
sortOfStudents[i]=i+"";
}
for (int i = 0; i < sortOfStudents.length-1; i++) {
int min=sortOfGrades[i];
int minIndex=i;
for (int j = i+1; j < sortOfStudents.length; j++) {
if(sortOfGrades[j]<min) {
sortOfGrades[minIndex]=sortOfGrades[j];
String temp=sortOfStudents[minIndex];
sortOfStudents[minIndex]=sortOfStudents[j];
sortOfGrades[j]=min;
sortOfStudents[j]=temp;
min=sortOfGrades[minIndex];
}
}
}
for (int i=0;i<sortOfStudents.length;i++) {
System.out.println(sortOfStudents[i]+". student's grade is: "+sortOfGrades[i]);
}
}
}
|
/**
* 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.dao.bean;
import java.io.Serializable;
public class ProfileTab implements Serializable {
private static final long serialVersionUID = 1L;
private String defaultTab;
private boolean desktopVisible;
private boolean searchVisible;
private boolean dashboardVisible;
private boolean administrationVisible;
private ProfileTabFolder prfFolder = new ProfileTabFolder();
private ProfileTabDocument prfDocument = new ProfileTabDocument();
private ProfileTabMail prfMail = new ProfileTabMail();
public String getDefaultTab() {
return defaultTab;
}
public void setDefaultTab(String defaultTab) {
this.defaultTab = defaultTab;
}
public boolean isDesktopVisible() {
return desktopVisible;
}
public void setDesktopVisible(boolean desktopVisible) {
this.desktopVisible = desktopVisible;
}
public boolean isSearchVisible() {
return searchVisible;
}
public void setSearchVisible(boolean searchVisible) {
this.searchVisible = searchVisible;
}
public boolean isDashboardVisible() {
return dashboardVisible;
}
public void setDashboardVisible(boolean dashboardVisible) {
this.dashboardVisible = dashboardVisible;
}
public boolean isAdministrationVisible() {
return administrationVisible;
}
public void setAdministrationVisible(boolean administrationVisible) {
this.administrationVisible = administrationVisible;
}
public ProfileTabFolder getPrfFolder() {
return prfFolder;
}
public void setPrfFolder(ProfileTabFolder prfFolder) {
this.prfFolder = prfFolder;
}
public ProfileTabDocument getPrfDocument() {
return prfDocument;
}
public void setPrfDocument(ProfileTabDocument prfDocument) {
this.prfDocument = prfDocument;
}
public ProfileTabMail getPrfMail() {
return prfMail;
}
public void setPrfMail(ProfileTabMail prfMail) {
this.prfMail = prfMail;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("desktopVisible="); sb.append(desktopVisible);
sb.append(", searchVisible="); sb.append(searchVisible);
sb.append(", dashboardVisible="); sb.append(dashboardVisible);
sb.append(", administrationVisible="); sb.append(administrationVisible);
sb.append(", prfDocument="); sb.append(prfDocument);
sb.append(", prfFolder="); sb.append(prfFolder);
sb.append(", prfMail="); sb.append(prfMail);
sb.append("}");
return sb.toString();
}
}
|
package com.qgbase.biz.user.controller;
import com.qgbase.biz.user.query.TQuery;
import com.qgbase.biz.user.query.TuserQuery;
import com.qgbase.common.domain.OperInfo;
import com.qgbase.config.annotation.Permission;
import com.qgbase.util.PageControl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
/**
* Created by lbb on 2018/4/27.
* 主要用于:查询列表数据或复杂查询处理
*/
@Controller
@RequestMapping(value = "/api/query")
public class TQueryController {
@Autowired
TQuery tQuery;
@Value("${excel.import.page-max-value}")
private int pageMax;
@Autowired
TuserQuery userQuery;
@PostMapping(value = "/getUserList")
@ResponseBody
@Permission(moduleCode = "YHDLGL",operationCode = "QUERY")
public PageControl getUserList(@RequestBody Map queryMap,OperInfo operInfo){
return tQuery.queryTUserList(queryMap);
}
}
|
package com.zy.crm.utils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringUtils {
private static ApplicationContext context;
static {
context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
public static Object getBean(String id){
return context.getBean(id);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.