text stringlengths 10 2.72M |
|---|
package babylanguage.babyapp.practicelanguagecommon;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import babylanguage.babyapp.appscommon.activities.ActivitiesHelper;
import babylanguage.babyapp.appscommon.interfaces.OnCompletedListener;
import babylanguage.babyapp.appscommon.languages.LanguageType;
import babylanguage.babyapp.appscommon.services.AddsService;
import babylanguage.babyapp.appscommon.services.AndroidHelper;
import babylanguage.babyapp.appscommon.services.StorageManager;
import data.Sentences;
import services.AppConstants;
import services.AppVersionsHelper;
import services.LanguageManager;
public class TalkHebrewBaseActivity extends AppCompatActivity {
Menu menu;
protected String bannerId;
LanguageManager.FromToLanguageInfo langs;
protected LanguageType fromLang = LanguageType.en;
protected LanguageType toLang = LanguageType.he;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivitiesHelper.setPortraitOrientation(this);
AppInitializer.initApp(this);
langs = LanguageManager.getInstance(this).getLanguage(this);
fromLang = langs.from;
toLang = langs.to;
//Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(this, WordsGameActivity.class));
}
protected void setAddBanner(int bannerId){
AndroidHelper.setAddBanner(bannerId, this, AppConstants.banner_unit_id);
}
protected void initAdd(){
AddsService.getInstance().initInterstitialAdd(this, AppConstants.ads_unit_id, new OnCompletedListener() {
@Override
public void onComplete(Object data) {
initAdd();
}
});
}
@Override
protected void onStart() {
super.onStart();
this.initLocales();
AppInitializer.syncDataOnRestart(this);
}
@Override
protected void onResume() {
super.onResume();
this.initLocales();
}
@Override
protected void onDestroy() {
deleteSharedFiles();
super.onDestroy();
}
private void deleteSharedFiles(){
// delete shared files
String sharedFiles = StorageManager.getData(this, AppConstants.storage_name, AppConstants.share_files_storage_key, "");
String[] filesList = new String[0];
if(sharedFiles!=null){
filesList = sharedFiles.split(",");
}
List<String> notDeletedFiles = new ArrayList<>();
for(int i = 0; i < filesList.length; i++){
File file = new File(filesList[i]);
if(file.exists() && !AndroidHelper.deleteFile(file)){
notDeletedFiles.add(filesList[i]);
}
Toast.makeText(this, "file deleted" + filesList[i], Toast.LENGTH_SHORT);
}
String notDeletedFilesStr = "";
for(int i = 0; i < notDeletedFiles.size(); i++){
notDeletedFilesStr += notDeletedFiles.get(i) + ",";
}
StorageManager.setData(this, AppConstants.storage_name, AppConstants.share_files_storage_key, notDeletedFilesStr.substring(0, Math.max(0, notDeletedFilesStr.length() - 1)));
}
public void initLocales(){
LanguageManager.getInstance(this);
langs = LanguageManager.getInstance(this).getLanguage(this);
fromLang = langs.from;
toLang = langs.to;
String lang_text = "";
if(menu != null){
LanguageManager.FromToLanguageInfo lang = LanguageManager.getInstance(this).getLanguage(this);
switch (lang.from){
case en:
lang_text = "EN";
break;
case he:
lang_text = "HE";
break;
case ru:
lang_text = "RU";
break;
}
switch (lang.to){
case en:
lang_text += "/EN";
break;
case he:
lang_text += "/HE";
break;
case ru:
lang_text += "/RU";
break;
}
menu.getItem(0).setTitle(lang_text);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == AppConstants.lang_changed_code){
this.initLocales();
Sentences.updateSentencesWithLanguage(this);
ActivitiesHelper.restartActivity(this);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.app_menu, menu);
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
bar.setDisplayShowHomeEnabled(true);
Drawable drawable= getResources().getDrawable(R.drawable.home);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
Drawable newdrawable = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 100, 100, true));
bar.setHomeAsUpIndicator(newdrawable);
this.initLocales();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// ActionBar ab = getActionBar();
// ab.setHomeButtonEnabled(true);
// ab.setDisplayHomeAsUpEnabled(true);
int id = item.getItemId();
if(id == R.id.action_lang) {
Intent intent = new Intent(this, FromToLanguageSelectionActivity.class);
intent.putExtra("banner_id", bannerId);
startActivityForResult(intent, AppConstants.lang_request_code);
}
else if(id == R.id.menu_item_share){
if(AndroidHelper.verifyStoragePermissions(this)){
openShare();
}
}
else if(id == android.R.id.home){
AndroidHelper.goToNextActivity(this, AppVersionsHelper.getHomeActivityClass());
}
return super.onOptionsItemSelected(item);
}
@Override
public void onRequestPermissionsResult(int requestCode,String permissions[],int[] grantResults) {
switch (requestCode) {
case AndroidHelper.REQUEST_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openShare();
} else {
Toast.makeText(this, "We need your permission to make a screenshot of the question", Toast.LENGTH_SHORT).show();
}
}
}
public void openShare(){
final File img = AndroidHelper.takeScreenshot(this, AppConstants.storage_folder_name);
if(img != null){
String sharedFiles = StorageManager.getData(this, AppConstants.storage_name, AppConstants.share_files_storage_key, "");
if(sharedFiles != null && sharedFiles.length() > 0){
sharedFiles += ",";
}
sharedFiles += AndroidHelper.getFilePath(img, AppConstants.storage_folder_name);
StorageManager.setData(this, AppConstants.storage_name, AppConstants.share_files_storage_key, sharedFiles);
AndroidHelper.openShareScreen(this, getShareSubject(), getShareContent(), "image/*", Uri.fromFile(img).getPath());
}
}
protected String getShareSubject(){
return getResources().getString(R.string.share_default_subject);
}
protected String getShareContent(){
return getResources().getString(R.string.share_default_content);
}
}
|
package de.bischinger.validation.business;
import de.bischinger.validation.model.MyPojo;
import de.bischinger.validation.model.assertions.SoftAssertions;
/**
* Created by Alexander Bischof on 28.05.15.
*/
@FunctionalInterface
public interface ValidationStrategy {
void validate(MyPojo actual, MyPojo expected, long... offset);
//Offset ignored here
ValidationStrategy ALWAYS_EQUAL = (a, e, o) -> {
SoftAssertions softAssertions = new SoftAssertions();
softAssertions.assertThat(a).hasSum1(e.getSum1());
softAssertions.assertThat(a).hasSum2(e.getSum2());
softAssertions.assertThat(a).hasSum3(e.getSum3());
softAssertions.assertThat(a).hasSum4(e.getSum4());
softAssertions.assertAll();
};
ValidationStrategy BY_OFFSETMAPPING = (a, e, o) -> {
SoftAssertions softAssertions = new SoftAssertions();
softAssertions.assertThat(a).hasCloseToSum1(e.getSum1(), o[0]);
softAssertions.assertThat(a).hasCloseToSum2(e.getSum2(), o[1]);
softAssertions.assertThat(a).hasCloseToSum3(e.getSum3(), o[2]);
softAssertions.assertThat(a).hasCloseToSum4(e.getSum4(), o[3]);
softAssertions.assertAll();
};
}
|
package FlippingAnImage;
import java.util.ArrayList;
import java.util.List;
/**
* 题目内容
*
* Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.
* To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
* To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].
* Example 1:
* Input: [[1,1,0],[1,0,1],[0,0,0]]
* Output: [[1,0,0],[0,1,0],[1,1,1]]
* Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
* Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
* Example 2:
* Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
* Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
* Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
* Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
* Notes:
* 1 <= A.length = A[0].length <= 20
* 0 <= A[i][j] <= 1
* Seen this question in a real interview before
*
* @author zhangmiao
*
* email:1006299425@qq.com
*
*/
public class Solution {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//测试
int[][] test1 = new int[][]{{1,1,0},{1,0,1},{0,0,0}};
System.out.println("test1 flipAndInvertImage:");
show(flipAndInvertImage(test1));
int[][] test2 = new int[][]{{1,1,0,0},{1,0,0,1},{0,1,1,1},{1,0,1,0}};
System.out.println("test2 flipAndInvertImage:");
show(flipAndInvertImage(test2));
}
public static int[][] flipAndInvertImage(int[][] A) {
if (A == null){
return null;
}
for (int i=0;i<A.length;i++){
for (int n =0 ,m = A[i].length-1;n <= m;n++,m--){
System.out.println("n:"+n+",m:"+m+",A[i][n]:"+A[i][n]+",A[i][m]:"+A[i][m]);
//反转
int t = A[i][n];
A[i][n] = A[i][m];
A[i][m] = t;
//取反
if (n != m) {
if (A[i][n] == 0){
A[i][n] = 1;
} else {
A[i][n] = 0;
}
}
if (A[i][m] == 0){
A[i][m] = 1;
} else {
A[i][m] = 0;
}
}
}
return A;
}
public static void show(int[][] A){
StringBuffer out = new StringBuffer();
for (int i=0;i<A.length;i++){
for (int n =0;n < A[i].length;n++){
out.append(A[i][n]+",");
}
out.append("\n");
}
System.out.print(out.toString());
}
}
|
package com.cisco.prototype.ledsignaldetection.Fragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import com.cisco.prototype.ledsignaldetection.BluetoothInterface;
import com.cisco.prototype.ledsignaldetection.R;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This fragment is for displaying detected images
*/
public class ImageFragment extends Fragment {
public String log;
private BluetoothInterface mListener;
public int state = 31;
public boolean kickstart;
public boolean success;
public boolean readOutput;
private boolean firstLoader;
private boolean firstSys;
public ArrayList<String> kst;
public ArrayList<String> syst;
public ArrayList<String> files;
public String sysImage = "";
public String kickImage = "";
public String kickstartImageName = "";
private String ksver = "";
private boolean findKs = false;
private String logForKs = "";
private ArrayAdapter<String> kickAdapter;
private ArrayAdapter<String> sysAdapter;
private ArrayAdapter<String> fileAdapter;
private boolean create;
private Pattern recordP = Pattern.compile("(?s).*bootflash:(.*)[lL]oader>[^>]*");
private Pattern weirdItem = Pattern.compile("^[^\\s]*$");
private Pattern itemExtract = Pattern.compile("^*.\\s{1}([^\\s]*)$");
private Pattern ks = Pattern.compile("^.*-kickstart.*\\.bin$");
private Pattern system = Pattern.compile("^.*\\.bin$");
private Pattern empty = Pattern.compile("");
private Pattern version = Pattern.compile("^[^\\.]*\\.(\\d+.*)\\.bin$");
private View view;
private TextView infoText;
private Button submit;
private TextView terminal;
private Spinner kickSpin;
private Spinner sysSpin;
private Spinner fileSpin;
private RelativeLayout imageOptions;
private ScrollView scroll;
private TextView additional;
public ImageFragment(){}
@Override
public void onCreate(Bundle savedInstanceState) {
create = true;
state = 0;
super.onCreate(savedInstanceState);
log = "";
success = false;
firstLoader = true;
firstSys = true;
kst = new ArrayList<String>();
syst = new ArrayList<String>();
files = new ArrayList<String>();
mListener.onImageFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_image, container, false);
infoText = (TextView) view.findViewById(R.id.image_text);
terminal = (TextView) view.findViewById(R.id.image_terminal);
submit = (Button) view.findViewById(R.id.submit_image);
imageOptions = (RelativeLayout) view.findViewById(R.id.image_options);
scroll = (ScrollView) view.findViewById(R.id.image_output);
additional = (TextView)view.findViewById(R.id.additional);
scroll.fullScroll(View.FOCUS_DOWN);
terminal.setMovementMethod(new ScrollingMovementMethod());
kickSpin = (Spinner) view.findViewById(R.id.kickImages);
kickAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, kst);
kickAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
kickSpin.setAdapter(kickAdapter);
sysSpin = (Spinner) view.findViewById(R.id.sysImages);
sysAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, syst);
sysAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sysSpin.setAdapter(sysAdapter);
fileSpin = (Spinner) view.findViewById(R.id.file_spinner);
fileAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, files);
fileAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fileSpin.setAdapter(fileAdapter);
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try{
mListener = (BluetoothInterface)activity;
} catch(ClassCastException e){}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void success(String message){
imageOptions.setVisibility(View.GONE);
infoText.setText(message);
submit.setText("OK");
}
public void setText(String message){infoText.setText(message);}
public void setReadOutput(boolean bool){
readOutput = bool;
}
public void read(String data){
if(findKs){
logForKs += data;
}else{
log += data;
}
terminal.setText(log);
Log.i("log", log);
if(readOutput) {
switch (state) {
case 0:
if (log.contains("loader>")) {
if (firstLoader) {
firstLoader = false;
log = log.replace("loader>", "");
} else {
readOutput = false;
onFileListObtained();
}
} else if(log.contains("(boot)#")){
kickstart = false;
if (firstSys) {
firstSys = false;
log = log.replace("(boot)#", "");
} else {
firstSys = true;
logForKs = "";
mListener.writeData("show version");
findKs = true;
state = 37;
}
} else if(log.toLowerCase().contains("more")){
mListener.writeData("");
}
break;
case 2:
Log.i("case", "Case 2 entered");
if (log.contains("loader>")) {
//fail
state = 7;
readOutput = false;
kickSpin.setEnabled(true);
submit.setEnabled(true);
mListener.imageStateMachine(state);
} else if (log.contains("(boot)#")) {
//success!
setKsVersion();
state = 9;
sysSpin.setEnabled(true);
submit.setEnabled(true);
kickstart = false;
readOutput = false;
mListener.imageStateMachine(state);
}else if(data.toLowerCase().contains("more")){
mListener.writeData("");
}
break;
case 4:
if(log.contains("Could not load") || log.contains("opensource.org")){
//fail
state = 8;
readOutput = false;
sysSpin.setEnabled(true);
submit.setEnabled(true);
mListener.imageStateMachine(state);
} else if(log.toLowerCase().contains("login") || log.toLowerCase().contains("user access")){
//success!
state = 6;
readOutput = false;
mListener.imageStateMachine(state);
}else if(log.toLowerCase().contains("more")){
mListener.writeData("");
}
break;
case 37:
Log.i("logks", logForKs);
if (firstSys && logForKs.contains("show version")) {
firstSys = false;
logForKs = logForKs.replace("(boot)#", "");
} else if(logForKs.toLowerCase().contains("more")) {
logForKs = logForKs.replace("more", "");
logForKs = logForKs.replace("More", "");
mListener.writeData("");
} else if (logForKs.contains("(boot)#") && logForKs.contains("show version")) {
readOutput = false;
findKs = false;
getKickstartVersion();
}
break;
default:break;
}
}
}
public void onFileListObtained(){
Log.i("image", "onFileListObtained entered");
//load kickstart stuff
Matcher recordM = recordP.matcher(log);
if(recordM.find()){
log = recordM.group(1);
Log.e("LEDApp", log);
}
ArrayList<String[]> imagePairs = new ArrayList<>();
log = log.replaceAll("\\[\\d+m--More-- \\[\\d+m", "");
log = log.replaceAll("\\[ .* \\[m", "");
log = log.replaceAll("\\[\\d+m?", "");
String[] directoryContents = log.split("\n");
Log.e("LEDApp", log);
for (String piece : directoryContents) {
String item = "";
if(weirdItem.matcher(piece.trim()).matches()){
item = piece;
}
else{
Matcher itemFinder = itemExtract.matcher(piece.trim());
item = itemFinder.find() ? itemFinder.group(1) : piece.trim();
Log.i("piece, item", piece + ", " + item);
}
if (ks.matcher(item.trim()).matches()) {
Log.e("LEDApp", "found kickstart: " + item);
kst.add(item.trim());
kickAdapter.notifyDataSetChanged();
} else if (system.matcher(item.trim()).matches()) {
if(ksver != ""){
String blah = "";
Matcher kickMatch = version.matcher(item);
if(kickMatch.find()){
blah = kickMatch.group(1);
}
if(blah.equals(ksver)) syst.add(item.trim());
} else syst.add(item.trim());
sysAdapter.notifyDataSetChanged();
Log.e("LEDApp", "found sys: " + item);
}
if(!empty.matcher(item.trim()).matches() && !(item.contains("(boot)") || item.contains("dir"))) files.add(item);
}
Log.i("array", "ks: " + kst.size());
Log.i("array", "sys: " + syst.size());
imageOptions.setEnabled(true);
if (kst.size() == 1 && syst.size() == 1) {
this.sysImage = syst.get(0).trim();
this.kickImage = kst.get(0).trim();
mListener.imageStateMachine(1);
} else if(kst.size() == 0 || syst.size() == 0){
Log.e("LEDMatch", "image pair size is 0");
kst.clear();
syst.clear();
for(int i = 0; i < files.size(); i ++){
kst.add(files.get(i));
syst.add(files.get(i));
}
kickAdapter.notifyDataSetChanged();
sysAdapter.notifyDataSetChanged();
mListener.imageStateMachine(0);
} else {
mListener.imageStateMachine(0);
}
}
public void getKickstartVersion(){
Log.i("ksversion", logForKs);
String[] lines = logForKs.split("\n");
for(int i = 0; i < lines.length; i++){
Log.i("lines", lines[i]);
if (lines[i].contains("kickstart image")) {
kickstartImageName = lines[i];
break;
}
}
if(kickstartImageName!= null ){
String item = "";
if(weirdItem.matcher(kickstartImageName.trim()).matches()){
item = kickstartImageName;
}
else{
Matcher itemFinder = itemExtract.matcher(kickstartImageName.trim());
item = itemFinder.find() ? itemFinder.group(1) : kickstartImageName.trim();
Log.i("piece, item", kickstartImageName + ", " + item);
}
Matcher itemFinder = itemExtract.matcher(item.trim());
while(itemFinder.find()){
itemFinder = itemExtract.matcher(item.trim());
item = itemFinder.group(1);
}
item = item.trim();
String[] stuff = item.split("/");
item = stuff[stuff.length - 1];
kickImage = item;
Matcher kickMatch = version.matcher(item);
if(kickMatch.find()){
ksver = kickMatch.group(1);
}
}
logForKs = "";
onFileListObtained();
}
public void setKsVersion(){
Matcher kickMatch = version.matcher(kickImage);
if(kickMatch.find()){
ksver = kickMatch.group(1);
}
ArrayList<String> temp = new ArrayList<String>();
for(int k = 0; k < syst.size(); k++){
temp.add(syst.get(k));
Log.i("ksver", "temp: " + temp.get(k));
}
syst.clear();
sysAdapter.notifyDataSetChanged();
for(int i = 0; i < syst.size(); i++){
Log.i("ksver", "syst cleared: " + syst.get(i));
}
for(int i = 0; i < temp.size(); i++){
String blah = "";
kickMatch = version.matcher(temp.get(i));
if(kickMatch.find()){
blah = kickMatch.group(1);
}
if(blah.equals(ksver)){
syst.add(temp.get(i));
Log.i("ksver", "syst equal: " + syst.get(syst.size() - 1));
}
}
sysAdapter.notifyDataSetChanged();
for(int i = 0; i < syst.size(); i++){
Log.i("ksver", "syst repopulated: " + syst.get(i));
}
}
public void setAdditional(String string){additional.setText(string);}
public void onResume(){
super.onResume();
if(!create){
mListener.setDataForImage();
} else create = false;
}
} |
package com.tencent.mm.plugin.sns.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import com.tencent.mm.plugin.sns.g.b;
import com.tencent.mm.plugin.sns.model.af;
import com.tencent.mm.plugin.sns.storage.n;
import com.tencent.mm.sdk.platformtools.x;
class SnsGalleryUI$3 implements OnMenuItemClickListener {
final /* synthetic */ SnsGalleryUI nWf;
final /* synthetic */ boolean nWg;
SnsGalleryUI$3(SnsGalleryUI snsGalleryUI, boolean z) {
this.nWf = snsGalleryUI;
this.nWg = z;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
String selectId = this.nWf.nTu.getSelectId();
String selectedMediaId = this.nWf.nTu.getSelectedMediaId();
b selectItem = this.nWf.nTu.getSelectItem();
x.d("MicroMsg.SnsGalleryUI", "click selectLocalId " + selectId);
x.d("MicroMsg.SnsGalleryUI", "click position " + selectedMediaId);
n Nl = af.byo().Nl(selectId);
try {
int i;
int position = this.nWf.nTu.getPosition();
int size = Nl.bAJ().sqc.ruA.size();
if (size <= 1 || position <= 1 || position > size) {
i = 0;
} else {
i = position - 1;
}
this.nWf.nTr.a(this.nWg, Nl, selectItem.caK, true, i);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.SnsGalleryUI", e, "", new Object[0]);
}
return true;
}
}
|
package com.qy.zgz.kamiduo.utils;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Created by LCB on 2018/2/8.
*/
public class HttpUtils {
/**
* Get请求,获得返回数据
*
* @param urlStr
* @return
* @throws Exception
*/
public static String doGet(String urlStr)
{
URL url = null;
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try
{
url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(30);
conn.setConnectTimeout(30);
conn.setRequestMethod("GET");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
if (conn.getResponseCode() == 200)
{
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[128];
while ((len = is.read(buf)) != -1)
{
baos.write(buf, 0, len);
}
baos.flush();
return baos.toString();
} else
{
throw new RuntimeException(" responseCode is not 200 ... ");
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
if (is != null)
is.close();
} catch (IOException e)
{
}
try
{
if (baos != null)
baos.close();
} catch (IOException e)
{
}
conn.disconnect();
}
return null ;
}
public static <T> void xPostJson(String url, HashMap<String,String> hashMap, Callback.CommonCallback<T> callback) {
RequestParams params = new RequestParams(url);
params.addHeader("Content-Type","application/x-www-form-urlencoded");
for (Map.Entry<String,String> entry:hashMap.entrySet())
{
params.addBodyParameter(entry.getKey(), entry.getValue());
}
params.setCharset("utf-8");
params.setConnectTimeout(10000);
x.http().post(params, callback);
}
}
|
package com.ice.springaop;
/**
* @author ice
* @date 18-11-6 上午10:03
*/
public @interface Timer {
}
|
package cn.canlnac.onlinecourse.presentation.internal.di.modules;
import cn.canlnac.onlinecourse.domain.executor.PostExecutionThread;
import cn.canlnac.onlinecourse.domain.executor.ThreadExecutor;
import cn.canlnac.onlinecourse.domain.interactor.GetDocumentsInCatalogUseCase;
import cn.canlnac.onlinecourse.domain.interactor.UseCase;
import cn.canlnac.onlinecourse.domain.repository.CatalogRepository;
import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity;
import dagger.Module;
import dagger.Provides;
/**
* 注入模块.
*/
@Module
public class GetDocumentsInCatalogModule {
private final int catalogId;
private final Integer start;
private final Integer count;
private final String sort;
public GetDocumentsInCatalogModule(
int catalogId,
Integer start,
Integer count,
String sort
) {
this.catalogId = catalogId;
this.start = start;
this.count = count;
this.sort = sort;
}
@Provides
@PerActivity
UseCase provideGetDocumentsInCatalogUseCase(CatalogRepository catalogRepository, ThreadExecutor threadExecutor,
PostExecutionThread postExecutionThread){
return new GetDocumentsInCatalogUseCase(catalogId, start,count,sort, catalogRepository, threadExecutor, postExecutionThread);
}
}
|
/*
* 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 GuiNetbean;
//a
import Storage.Account;
import Storage.AccountList;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
/**
*
* @author Admin
*/
public class guiRegister extends javax.swing.JFrame {
/**
* Creates new form guiLogin
*/
public guiRegister() {
initComponents();
initCustomer();
}
private boolean isValidPhone(String phoneNum) {
String regex = "(84[3|5|7|8|9]|0[3|5|7|8|9])+([0-9]{8})";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(phoneNum);
return m.matches();
}
public LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) {
return Instant.ofEpochMilli(dateToConvert.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
public static boolean isValidUsername(String name) {
String regex = "^[a-zA-Z0-9._-]{5,20}$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(name);
return m.matches();
}
public static boolean isValidPassword(char[] password) {
String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,30}$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(new String(password));
return m.matches();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jDesktopPane2 = new javax.swing.JDesktopPane();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
ousername = new javax.swing.JTextField();
ofullname = new javax.swing.JTextField();
ophone = new javax.swing.JTextField();
opassword1 = new javax.swing.JPasswordField();
opassword2 = new javax.swing.JPasswordField();
showpassword = new javax.swing.JRadioButton();
BtSignup = new javax.swing.JButton();
login = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
oday = new com.toedter.calendar.JDateChooser();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Register");
setLocation(new java.awt.Point(650, 250));
jDesktopPane2.setBackground(new java.awt.Color(255, 255, 0));
jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jLabel1.setFont(new java.awt.Font("Rockwell", 0, 55)); // NOI18N
jLabel1.setText("SIGN UP");
jLabel2.setText("Password");
jLabel3.setText("Ussername");
jLabel4.setText("Re-enter pass");
jLabel5.setText("Phone");
jLabel6.setText("Date of birth");
jLabel7.setText("Name");
opassword1.setEchoChar('\u2022');
opassword2.setEchoChar('\u2022');
showpassword.setText("Show password");
showpassword.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showpasswordActionPerformed(evt);
}
});
BtSignup.setFont(new java.awt.Font("UTM Alberta Heavy", 0, 24)); // NOI18N
BtSignup.setText("SIGN UP");
BtSignup.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtSignupActionPerformed(evt);
}
});
login.setText("Login");
login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginActionPerformed(evt);
}
});
jLabel8.setText("You have an account ?");
oday.setDateFormatString("dd/MM/YYYY");
jButton2.setText("Main menu");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(103, 103, 103)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(88, 88, 88)
.addComponent(BtSignup, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(oday, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(ofullname, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(ophone))))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(103, 103, 103)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(ousername, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(opassword1)
.addComponent(opassword2)))
.addComponent(showpassword, javax.swing.GroupLayout.Alignment.TRAILING)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(134, 134, 134)
.addComponent(jLabel1)))
.addGap(0, 91, Short.MAX_VALUE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(login)))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jLabel1)
.addGap(38, 38, 38)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ousername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(opassword1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(opassword2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(showpassword)
.addGap(5, 5, 5)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ofullname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ophone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(oday, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(BtSignup, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(login)
.addComponent(jLabel8)
.addComponent(jButton2))
.addContainerGap(22, Short.MAX_VALUE))
);
jDesktopPane2.setLayer(jPanel2, javax.swing.JLayeredPane.DEFAULT_LAYER);
javax.swing.GroupLayout jDesktopPane2Layout = new javax.swing.GroupLayout(jDesktopPane2);
jDesktopPane2.setLayout(jDesktopPane2Layout);
jDesktopPane2Layout.setHorizontalGroup(
jDesktopPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jDesktopPane2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jDesktopPane2Layout.setVerticalGroup(
jDesktopPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jDesktopPane2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jDesktopPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jDesktopPane2)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
guiMain d2 = new guiMain();
d2.setVisible(true);
dispose();
}//GEN-LAST:event_jButton2ActionPerformed
private void loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginActionPerformed
guiLogin d2 = new guiLogin();
d2.setVisible(true);
dispose();
}//GEN-LAST:event_loginActionPerformed
private void BtSignupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtSignupActionPerformed
String username = ousername.getText();
char[] password = opassword1.getPassword();
char[] password_2 = opassword2.getPassword();
String name = ofullname.getText();
String phoneNum = ophone.getText();
Date birtday = oday.getCalendar().getTime();
if (!(!username.isEmpty() && password.length != 0 && password_2.length != 0 && !name.isEmpty() && !phoneNum.isEmpty())) {
JOptionPane.showMessageDialog(jDesktopPane2, "Please enter information", "Warning", JOptionPane.WARNING_MESSAGE);
} else if (!isValidUsername(username)) {
JOptionPane.showMessageDialog(jDesktopPane2, "Username must be between 5 and 20 characters, can contain lowercase \nletters, uppercase numbers and some special characters (._=)", "Warning", JOptionPane.WARNING_MESSAGE);
} else if (!isValidPassword(password)) {
JOptionPane.showMessageDialog(jDesktopPane2, "Password must be between 8 and 30 characters, at least one uppercase, \none lowercase, one number and one special character (@$!%*?&)", "Warning", JOptionPane.WARNING_MESSAGE);
} else if (!(new String(password)).equals(new String(password_2))) {
JOptionPane.showMessageDialog(jDesktopPane2, "Passwords are not the same", "Warning", JOptionPane.WARNING_MESSAGE);
} else if (!isValidPhone(phoneNum)) {
JOptionPane.showMessageDialog(jDesktopPane2, "The phone number you entered is not of a Vietnamese carrier", "Warning", JOptionPane.WARNING_MESSAGE);
} else {
AccountList list = new AccountList();
if (!list.addAccount(new Account(username, new String(password), name,
convertToLocalDateViaMilisecond(birtday), phoneNum))) {
JOptionPane.showMessageDialog(jDesktopPane2, "Username already in use", "Warning", JOptionPane.WARNING_MESSAGE);
} else {
JOptionPane.showMessageDialog(BtSignup, "Successful registration", "Success",
JOptionPane.INFORMATION_MESSAGE);
guiMain frm1 = new guiMain();
frm1.setVisible(true);
dispose();
}
}
}//GEN-LAST:event_BtSignupActionPerformed
private void showpasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showpasswordActionPerformed
if (showpassword.isSelected()) {
opassword1.setEchoChar((char) 0);
opassword2.setEchoChar((char) 0);
} else {
opassword1.setEchoChar('\u2022');
opassword2.setEchoChar('\u2022');
}
}//GEN-LAST:event_showpasswordActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(guiRegister.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(guiRegister.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(guiRegister.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(guiRegister.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new guiRegister().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton BtSignup;
private javax.swing.JButton jButton2;
private javax.swing.JDesktopPane jDesktopPane2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel2;
private javax.swing.JButton login;
private com.toedter.calendar.JDateChooser oday;
private javax.swing.JTextField ofullname;
private javax.swing.JPasswordField opassword1;
private javax.swing.JPasswordField opassword2;
private javax.swing.JTextField ophone;
private javax.swing.JTextField ousername;
private javax.swing.JRadioButton showpassword;
// End of variables declaration//GEN-END:variables
private void initCustomer() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2001);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();
oday.setDate(date);
}
}
|
package com.vincent.key.domain;
public class FunctionCode {
private int keyCode;
private int functionCode;
private String desc;
public FunctionCode(int keyCode, int functionCode, String desc){
this.keyCode = keyCode;
this.functionCode = functionCode;
this.desc = desc;
}
public int getKeyCode() {
return keyCode;
}
public void setKeyCode(int keyCode) {
this.keyCode = keyCode;
}
public int getFunctionCode() {
return functionCode;
}
public void setFunctionCode(int functionCode) {
this.functionCode = functionCode;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
|
package hirondelle.web4j.database;
/**
Execute a database transaction.
<P>Should be applied only to operations involving more than one SQL statement.
*/
public interface Tx {
/**
Execute a database transaction, and return the number of edited records.
*/
int executeTx() throws DAOException;
}
|
package com.group.cache;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.group.util.MybatisUtils;
/**
* 测试缓存
* @author Administrator
*
*/
public class TestCache {
private SqlSession session;
@Before
public void before(){
session = MybatisUtils.getSession();
}
/**
* 测试一级缓存
*/
@Test
public void testLevelOne() {
//两次查询,之出现条查询语句
/*List<Map> books = session.selectList("com.group.dao.IBookDao.allMap");
List<Map> books1 = session.selectList("com.group.dao.IBookDao.allMap");*/
//一级换存级别为session内部,不能够跨session的,所以会出现两条查询语句
List<Map> books3 = session.selectList("com.group.dao.IBookDao.allMap");
SqlSession session2 = MybatisUtils.getSession();
List<Map> books4 = session2.selectList("com.group.dao.IBookDao.allMap");
}
/**
* 测试二级缓存,只有commit提交数据库,确定修改了数据库后二级换存才会真正进行缓存
*/
@Test
public void testLevelTwo() {
List<Map> books3 = session.selectList("com.group.dao.IBookDao.allMap");
session.commit();//为了让集合进入二级缓存
SqlSession session2 = MybatisUtils.getSession();
List<Map> books4 = session2.selectList("com.group.dao.IBookDao.allMap");
}
@After
public void after() {
MybatisUtils.closeSession(session);
}
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayPartitionI {
public static int arrayPairSum1(int[] nums) { //wrong understanding
int res = 0;
int check =0;
int minAdd = 0;
Arrays.sort(nums);
List<Integer> maxArray = new ArrayList<>();
for (int i = 0;i< nums.length;i++){
for (int j = i+1;j<nums.length;j++){
if (nums[i] < nums[j]){
minAdd = minAdd + nums[i];
check++;
}
else {
minAdd = minAdd + nums[j];
check++;
}
if (check%(nums.length/2) == 0){
maxArray.add(minAdd);
check = 0;
minAdd = 0;
}
}
}
res = Collections.max(maxArray);
return res;
}
public static int arrayPairSum(int[] nums) {
int res = 0;
Arrays.sort(nums);
for (int i =0; i<nums.length; i+=2){
res = res+nums[i];
}
return res;
}
public static void main(String[] args) {
int[] nums = {6,2,6,5,1,2};
System.out.println(arrayPairSum(nums));
}
}
|
/*
* 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.test.specalization;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import jakarta.enterprise.context.spi.CreationalContext;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.util.AnnotationLiteral;
import org.junit.Assert;
import org.apache.webbeans.test.AbstractUnitTest;
import org.junit.Test;
public class AlternativeSpecializesProducerTest extends AbstractUnitTest
{
private static final String PACKAGE_NAME = AlternativeSpecializesProducerTest.class.getPackage().getName();
@Test
@SuppressWarnings("unchecked")
public void testAlternativeSpecializeBean()
{
Collection<String> beanXmls = new ArrayList<String>();
beanXmls.add(getXmlPath(PACKAGE_NAME, "AlternativeSpecializesProducer"));
Collection<Class<?>> beanClasses = new ArrayList<Class<?>>();
beanClasses.add(Pen.class);
beanClasses.add(DefaultPenProducer.class);
beanClasses.add(AdvancedPenProducer.class);
beanClasses.add(PremiumPenProducer.class);
startContainer(beanClasses, beanXmls);
Annotation[] anns = new Annotation[1];
anns[0] = new AnnotationLiteral<QualifierSpecialized>()
{
};
Set<Bean<?>> beans = getBeanManager().getBeans(IPen.class, anns);
Assert.assertTrue(beans.size() == 1);
Bean<IPen> bean = (Bean<IPen>)beans.iterator().next();
CreationalContext<IPen> cc = getBeanManager().createCreationalContext(bean);
IPen pen = (IPen) getBeanManager().getReference(bean, IPen.class, cc);
Assert.assertTrue(pen.getID().contains("premium"));
shutDownContainer();
}
}
|
import java.io.*;
class ExceptionDemo1 {
public static void main(String args[]){
FileInputStream fis = new FileInputStream("test.txt");
int b;
while ((b = fis.read()) != -1) {
System.out.print(b);
}
fis.close();
}
} |
/*
* 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 TorrentMetadata;
import java.io.IOException;
/**
*
* @author Robert
*/
import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TorrentFileTest
{
public static void main(String [] args) throws IOException
{
TorrentFile loadSampleTorrent = null;
//TODO make it universal, get the path of the project or smth
//Test loading .torrent
String torrent = "C:\\Users\\Robert\\Downloads\\sample.torrent";
//String torrent = "C:\\Users\\Robert\\Downloads\\[torrenty.pl] Deus Ex_ Revision _2015_ [ENG] [ALI213] [RAR].torrent";
File torrentFile = new File(torrent);
try
{
loadSampleTorrent = TorrentFile.load(torrentFile);
}
catch (IOException | NoSuchAlgorithmException ex)
{
Logger.getLogger("TorrentFile Test").log(Level.SEVERE, null, ex);
}
//TODO make it universal, get the path of the project or smth
//Test saving .torrent
FileOutputStream fop = null;
File file;
try
{
file = new File("C:\\Users\\Robert\\Downloads\\sampleSaved.torrent");
fop = new FileOutputStream(file);
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
loadSampleTorrent.save(fop);
fop.flush();
fop.close();
System.out.println("Done");
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (fop != null)
{
fop.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
//Test creating .torrent
File fileSample;
File createTorrentFile;
File fileTMP;
TorrentFile testCreate = null;
FileOutputStream fopTestCreate = null;
FileOutputStream fopSampleSaved = null;
try
{
createTorrentFile = new File("C:\\Users\\Robert\\Downloads\\test.txt");
URI testAnnounce = new URI("udp://tracker.openbittorrent.com");
testCreate = TorrentFile.create(createTorrentFile,testAnnounce , "robert");
fileTMP = new File("C:\\Users\\Robert\\Downloads\\sampleCreate.torrent");
fopTestCreate = new FileOutputStream(fileTMP);
//saving the loadd file to check if everything is correct
fileSample = new File("C:\\Users\\Robert\\Downloads\\sampleSaved.torrent");
fopSampleSaved= new FileOutputStream(fileSample);
// if file doesnt exists, then create it
if (!fileTMP.exists())
{
fileTMP.createNewFile();
}
// if file doesnt exists, then create it
if (!fileSample.exists())
{
fileSample.createNewFile();
}
testCreate.save(fopTestCreate);
System.out.println("Saving sample.torrent to " + fileSample.getName() +" succesfull");
loadSampleTorrent.save(fopSampleSaved); //saving loaded .torrent
fopTestCreate.flush();
fopTestCreate.close();
fopSampleSaved.flush();
fopSampleSaved.close();
System.out.println("Creating .torrent from test.txt to "+ fileTMP.getName() +" succesfull");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
|
package com.ryit.utils;
public class Constants {
public static final String ADMIN_USER = "adminUser";
public static final String USER = "web_user";
public static final String MOBILE_NO = "mobile"; // 手机号码
public static final String MOBILE_VERIFY_CODE = "mobile_verify"; // 手机验证码
public static final String MOBILE_VERIFY_CODE_SEND_TIME = "mobile_verify_send_tme"; // 手机验证码发送时间
public static final int MAX_TIME = 180; // session最长保留验证码时间(3分钟)
public static final String SMS_MOBILE_AREA_CODE_CN_ELSE = "1";
public static final String REGISTER_MOBILE_NO = "register_mobile"; //注册手机号码
public static final String REGISTER_MOBILE_VERIFY_CODE = "register_mobile_verify"; //注册手机验证码
public static final String REGISTER_MOBILE_VERIFY_CODE_SEND_TIME = "register_mobile_verify_send_tme"; //注册手机验证码超期时间
public static final String PWD_USER_ID="pwd_userId";
public static final String PROTAL_SMS = "Protal_yzm";
//购买商主账户角色(总公司)
public static final int BUYER_MAJOR_ROLE = 1;
//购买商子账户角色(连锁店)
public static final int BUYER_MINOR_ROLE = 2;
//购买商主账户角色名(总公司)
public static final String BUYER_MAJOR_ROLE_NAME = "ADMIN";
//购买商子账户角色名
public static final String BUYER_MINOR_ROLE_NAME = "SUB_ACCOUNT";
public static final String CHINA_CODE = "A000086000";
public static final String CHINA_NAME = "中国";
//订单状态-已审核
public static final int ORDER_STATUS_AUDITED = 2;
public static final int ORDER_STATUS_CREATE = 1;
public static final int ORDER_STATUS_INVALID = 0;
public static final int ORDER_STATUS_REJECT = 3;
//联系人类型,1购买商连锁店,2供应商
public static final int CONTACTS_TYPE_BUYER = 1;
public static final int CONTACTS_TYPE_SELLER = 2;
public static final int COLD_PRODUCT = 3;
//生成供应商code前缀(CSSP-SP-)
public static final String SUPPLIER_CODE = "SP";
//生成商品code前缀
public static final String CARGOS_CODE = "CSSP-CARGO-";
public static final String LOG4J_CATEGROY = "CSSP";
public static final String RESULT_PAGE = "web/result";
//订单类型(入库)
public static final String ORDER_TYPE_IN = "1";
//订单类型(出库)
public static final String ORDER_TYPE_OUT = "2";
//订单类型(冷运)
public static final String ORDER_TYPE_COLD = "3";
//订单类型(重货)
public static final String ORDER_TYPE_HEAVY = "4";
//订单类型编码(销退入库)
public static final String ORDER_TYPE_CODE_RI = "RI";
//订单类型编码(采购入库)
public static final String ORDER_TYPE_CODE_PI = "PI";
//订单类型编码(报溢入库)
public static final String ORDER_TYPE_CODE_OI = "OI";
//订单类型编码(销退出库)
public static final String ORDER_TYPE_CODE_RO = "RO";
//订单类型编码(采购出库)
public static final String ORDER_TYPE_CODE_PO = "PO";
//订单类型编码(报损出库)
public static final String ORDER_TYPE_CODE_BO = "BO";
}
|
package com.yijiupi.login.service.impl;
import com.yijiupi.login.dao.UserDao;
import com.yijiupi.login.entity.User;
import com.yijiupi.login.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Author:吴宸煊
* @Date: Created in 13:43 2018/1/17
* @Description:实现用户service
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
/**
* @Description:用户注册
* @param: userPO
* @return:
*/
@Override
public void save(User user) {
userDao.insert(user);
}
/**
* @Description:
* @param: name
* @param password
* @return:UserPO
*/
@Override
public User getUser(String name, String password) {
return userDao.getUser(name,password);
}
@Override
public User getName(String name) {
return userDao.getName(name);
}
}
|
/*
* 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 eu.stoehler.botapi.users;
import java.io.Serializable;
/**
* Protects one nickname.
* @author joern
*/
public class SimpleUser implements Target, Serializable{
private static final long serialVersionUID = 1L;
/**
* currently selected pseudonym
*/
public String pseudonym;
public SimpleUser(String p) {
pseudonym = p;
}
@Override
public void allowDeleteNickname(Nickname nick) throws NicknameProtectionException {
if(pseudonym != null) {
if(nick.value.equals(pseudonym)) {
throw new NicknameProtectionException(nick, "Setze einen anderen Haupt-Nickname.");
}
}
}
public void setPseudonym(Nickname nick) {
this.pseudonym = nick.value;
}
@Override
public String targetIdentifier() {
return pseudonym;
}
}
|
package com.springboot.module.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import javax.persistence.*;
@Getter
@Setter
@NoArgsConstructor
@ToString
@AllArgsConstructor
@Table(name = "sys_user")
public class User {
@Id
private Integer id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 昵称
*/
private String nickname;
/**
* 角色ID
*/
@Column(name = "role_id")
private Integer roleId;
/**
* 创建时间
*/
@Column(name = "create_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 修改时间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column(name = "update_time")
private Date updateTime;
/**
* 是否有效 1有效 2无效
*/
@Column(name = "delete_status")
private String deleteStatus;
} |
package test.str;
/**
* Copyright (c) by www.leya920.com
* All right reserved.
* Create Date: 2017-05-24 11:06
* Create Author: maguoqiang
* File Name: Child.java
* Last version: 1.0
* Function: //TODO
* Last Update Date: 2017-05-24 11:06
* Last Update Log:
* Comment: //TODO
**/
public class Child extends Parent{
@Override
public int getInt(Parent parent) {
return parent.retInt();
}
@Override
public int retInt() {
return 2;
}
public static void main(String[] args) {
Parent p=new Child();
System.out.println(p.getInt(p));
System.out.println(p.retInt());
}
}
|
package modelo;
public class Neornithe extends Ave{
private Neognato neognato;
private Paleognato paleognato;
protected final char RANGO_METABOLICO_ALTO = 'A';
protected final char RANGO_METABOLICO_MEDIO = 'M';
protected final char RANGO_METABOLICO_BAJO = 'B';
protected double longitudCola;
protected double densidadOsea;
protected char rangoMetabolico;
public Neornithe ( String col, double alt, double pes, double longC, double densO, char ranM){
super( col, alt, pes );
longitudCola = longC;
densidadOsea = densO;
rangoMetabolico = ranM;
}
public Neognato darNeognato(){
return neognato;
}
public Paleognato darPaleognato(){
return paleognato;
}
public double darLongitudCola(){
return longitudCola;
}
public double darDensidadOsea(){
return densidadOsea;
}
public char darRangoMetabolico(){
return rangoMetabolico;
}
public void modificarLongitudCola(double longC){
longitudCola = longC;
}
public void modificarDensidadOsea(double densO){
densidadOsea = densO;
}
/**@Override
*/
public double calcularPromedioPesoAve(){
double peso = 0;
peso = neognato.calcularPromedioPesoAve();
peso += paleognato.calcularPromedioPesoAve();
return peso;
}
/**@Override
*/
public double calcularSumaAltura(){
double suma = 0;
suma = neognato.calcularSumaAltura();
suma += paleognato.calcularSumaAltura();
return suma;
}
/**@Override
*/
public int calcularTotalBajo(){
int bajo = 0;
bajo = neognato.calcularTotalBajo();
bajo += paleognato.calcularTotalBajo();
return bajo;
}
/**@Override
*/
public int calcularTotalMedio(){
int medio = 0;
medio = neognato.calcularTotalMedio();
medio += paleognato.calcularTotalMedio();
return medio;
}
/**@Override
*/
public int calcularTotalAlto(){
int alto = 0;
alto = neognato.calcularTotalAlto();
alto += paleognato.calcularTotalAlto();
return alto;
}
} |
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface MeterInterface extends Remote {
public void Register() throws RemoteException ;
public void unRegister()throws RemoteException ;
public String sendReadings()throws RemoteException ;
public String sendAlerts()throws RemoteException ;
public String sendRequest()throws RemoteException ;
public String sendHistory()throws RemoteException ;
public boolean sendAnswer()throws RemoteException ;
}
|
package com.bowlong.net.http;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bowlong.bio2.B2InputStream;
import com.bowlong.io.ByteInStream;
import com.bowlong.lang.NumFmtEx;
import com.bowlong.lang.StrEx;
import com.bowlong.text.EncodingEx;
import com.bowlong.util.DateEx;
import com.bowlong.util.ExceptionEx;
import com.bowlong.util.MapEx;
/**
*
* @author Canyon
* @version createtime:2015年8月17日下午7:50:55
*/
@SuppressWarnings({ "rawtypes" })
public class HttpBaseEx {
static public String UseAgent1 = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)";
static public String UseAgent2 = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
static public String UseAgent3 = "Mozilla/4.0";
/** 连接超时时间,缺省为10秒钟 */
static public final int defaultConnectionTimeout = 10000;
/** 回应超时时间, 缺省为30秒钟 */
static public final int defaultSoTimeout = 30000;
/*** GET参数编码 */
static public final String buildQuery(Map<String, String> data,
String charset) {
if (MapEx.isEmpty(data))
return "";
String ret = "";
String k, v;
boolean isSupported = !StrEx.isEmptyTrim(charset);
if (isSupported) {
isSupported = EncodingEx.isSupported(charset);
if (!isSupported) {
charset = EncodingEx.UTF_8;
isSupported = true;
}
}
StringBuffer buff = new StringBuffer();
for (Entry<String, String> entry : data.entrySet()) {
k = entry.getKey();
v = entry.getValue();
try {
if (isSupported) {
k = URLEncoder.encode(k, charset);
v = URLEncoder.encode(v, charset);
}
buff.append(k).append("=").append(v);
} catch (UnsupportedEncodingException e) {
}
buff.append("&");
}
ret = buff.toString();
if (StrEx.isEmptyTrim(ret))
return ret;
return ret.substring(0, ret.length() - 1);
}
static public final String buildStrByJSON4Obj(Object data) {
try {
return JSON.toJSONString(data);
} catch (Exception e) {
}
return "";
}
static public final String buildStrByJSON4Map(Map data) {
try {
if (MapEx.isEmpty(data))
return "";
JSONObject json = new JSONObject();
Map<String, String> mapKV = MapEx.toMapKV(data);
for (Entry<String, String> entry : mapKV.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
json.put(key, val);
}
return json.toJSONString();
} catch (Exception e) {
}
return "";
}
/*** GET参数转换为map对象 */
static public final Map<String, String> buildMapByQuery(String query) {
Map<String, String> ret = new HashMap<String, String>();
if (!StrEx.isEmptyTrim(query)) {
boolean isFirst = query.indexOf("?") == 0;
if (isFirst)
query = query.substring(1);
String[] params = query.split("&");
for (String item : params) {
if (StrEx.isEmptyTrim(item))
continue;
int index = item.indexOf("=");
if (index < 0)
continue;
String k = item.substring(0, index);
String v = item.substring(index + 1);
if (ret.containsKey(k)) {
v = ret.get(k) + "," + v;
}
ret.put(k, v);
}
}
return ret;
}
static public final String inps2Str(InputStream ins, String charset) {
if (ins == null)
return "";
try {
boolean isSupported = !StrEx.isEmptyTrim(charset);
if (isSupported) {
isSupported = EncodingEx.isSupported(charset);
if (!isSupported) {
charset = EncodingEx.UTF_8;
isSupported = true;
}
}
StringBuffer buff = new StringBuffer();
BufferedReader br = null;
if (isSupported) {
br = new BufferedReader(new InputStreamReader(ins, charset));
} else {
br = new BufferedReader(new InputStreamReader(ins));
}
String readLine = null;
while ((readLine = br.readLine()) != null) {
buff.append(readLine);
}
ins.close();
br.close();
return buff.toString();
} catch (Exception e) {
return ExceptionEx.e2s(e);
}
}
static public final Object inps2Obj(InputStream ins) {
if (ins == null)
return null;
try {
return B2InputStream.readObject(ins);
} catch (Exception e) {
}
return null;
}
static public final Map inps2Map(InputStream ins) {
if (ins == null)
return new HashMap();
try {
return B2InputStream.readMap(ins);
} catch (Exception e) {
}
return new HashMap();
}
static public final byte[] inps2Bytes(InputStream ins) {
if (ins == null)
return new byte[0];
try {
return B2InputStream.readStream(ins);
} catch (Exception e) {
}
return new byte[0];
}
static public final Object inps2Obj4Stream(InputStream ins)
throws Exception {
byte[] bts = inps2Bytes(ins);
try (ByteInStream byteStream = ByteInStream.create(bts)) {
return B2InputStream.readObject(byteStream);
}
}
static public final Map inps2Map4Stream(InputStream ins) throws Exception {
byte[] bts = inps2Bytes(ins);
try (ByteInStream byteStream = ByteInStream.create(bts)) {
return B2InputStream.readMap(byteStream);
}
}
static public final String inps2Str4Stream(InputStream ins, String charset) {
if (ins == null)
return "";
try {
boolean isSupported = !StrEx.isEmptyTrim(charset);
if (isSupported) {
isSupported = EncodingEx.isSupported(charset);
if (!isSupported) {
charset = EncodingEx.UTF_8;
isSupported = true;
}
}
byte[] bts = B2InputStream.readStream(ins);
if (isSupported) {
return new String(bts, charset);
} else {
return new String(bts);
}
} catch (Exception e) {
return ExceptionEx.e2s(e);
}
}
/*** 取得参数的字节流 **/
static public final byte[] getBytes4Str(String params, String charset) {
byte[] btParams = new byte[0];
if (!StrEx.isEmptyTrim(params)) {
boolean isSupported = !StrEx.isEmptyTrim(charset);
if (isSupported) {
isSupported = EncodingEx.isSupported(charset);
if (!isSupported) {
charset = EncodingEx.UTF_8;
isSupported = true;
}
}
try {
if (isSupported) {
btParams = params.getBytes(charset);
} else {
btParams = params.getBytes();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return btParams;
}
static public String getSpeed(String pingUrl, String charUTF) {
Charset cset = null;
if (!StrEx.isEmpty(charUTF)) {
cset = Charset.forName(charUTF);
}
return getSpeed(pingUrl, cset);
}
static public String getSpeed(String pingUrl, Charset cset) {
try {
String line = null;
Process pro = Runtime.getRuntime().exec(
"ping " + pingUrl + " -l 1000 -n 4");
InputStream inStream = pro.getInputStream();
BufferedReader buf = null;
if (cset == null) {
buf = new BufferedReader(new InputStreamReader(inStream));
} else {
buf = new BufferedReader(new InputStreamReader(inStream, cset));
}
int len = 0;
String vEn = "Average";
String vCn = "平均";
while ((line = buf.readLine()) != null) {
int position = line.indexOf(vEn);
if (position == -1) {
position = line.indexOf(vCn);
len = vCn.length();
} else {
len = vEn.length();
}
if (position != -1) {
System.out.println(line);
String value = line.substring(position + len,
line.lastIndexOf("ms"));
value = value.replaceAll("=", "");
value = value.trim();
double speed = (1000d / Integer.parseInt(value)) / 1024
* DateEx.TIME_SECOND;
double lineMB = (1024 * 1.25);
String v = "";
if (speed > lineMB) {
speed /= 1024;
v = NumFmtEx.formatDouble(speed) + "MB/s";
} else {
v = NumFmtEx.formatDouble(speed) + "KB/s";
}
System.out.println("下载速度:" + v);
return v;
}
}
} catch (Exception e) {
}
return "0KB/s";
}
}
|
package com.tencent.mm.plugin.card.b;
import com.tencent.mm.plugin.card.model.g;
public interface k$a {
void a(g gVar);
void auM();
}
|
package com.libapputils;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
public class Utils {
private static String TAG = "data";
private static int screenWidth = 0;
public static boolean hasInternet() {
return true;
}
public static String getText(TextView textView) {
return textView.getText().toString().trim();
}
public static void showToast(Context context, String message) {
// Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
TextView textView = (TextView) toast.getView().findViewById(android.R.id.message);
if (textView != null) textView.setGravity(Gravity.CENTER);
toast.show();
}
public static void showToastValidation(Context context, int message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public static void showValidationToast(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
public static void log(String text) {
Log.d(TAG, text);
}
public static void loge(String text) {
Log.e(TAG, text);
}
public static void logd(String tag, String s) {
}
public static android.support.v7.app.AlertDialog createAlertDialog(Activity activity, String message, String positiveText,
String negativeText, DialogInterface.OnClickListener mDialogClick) {
android.support.v7.app.AlertDialog.Builder builder =
new android.support.v7.app.AlertDialog.Builder(activity).setPositiveButton(positiveText, mDialogClick)
.setNegativeButton(negativeText, mDialogClick)
.setMessage(message);
return builder.create();
}
public static boolean hasInternet(Context context, String no_internet_message) {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (!(networkInfo != null && networkInfo.isConnectedOrConnecting())) {
showToast(context, no_internet_message);
return false;
}
return true;
}
public static boolean hasInternetConnection(Context context) {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
public static void hideKeyboard(Activity ctx) {
if (ctx.getCurrentFocus() != null) {
InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(ctx.getCurrentFocus().getWindowToken(), 0);
}
}
public static void showKeyboard(Activity activity, EditText view) {
Context context = activity;
try {
if (context != null) {
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
} catch (Exception e) {
Log.e("Exception on show", e.toString());
}
}
public static void requestEdittextFocus(Activity activity, EditText view) {
view.requestFocus();
showKeyboard(activity, view);
}
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(text.getBytes("iso-8859-1"), 0, text.length());
byte[] sha1hash = md.digest();
return convertToHex(sha1hash);
}
private static String convertToHex(byte[] data) {
StringBuilder buf = new StringBuilder();
for (byte b : data) {
int halfbyte = (b >>> 4) & 0x0F;
int two_halfs = 0;
do {
buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
halfbyte = b & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
public static void setLanguage(Activity activity, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = new Configuration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// Do something for lollipop and above versions
config.locale = locale;
activity.createConfigurationContext(config);
} else {
// do something for phones running an SDK before lollipop
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
config.setLocale(locale);
}
activity.getBaseContext().getResources().updateConfiguration(config,
activity.getBaseContext().getResources().getDisplayMetrics());
}
}
public static void setMirroredEnable(boolean enabled, ImageView... view) {
for (ImageView v : view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
v.getDrawable().setAutoMirrored(enabled);
}
}
}
public static void logD(String key, String value) {
Log.e(key, value);
}
public static void expand(final View v) {
v.measure(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
final int targetHeight = v.getMeasuredHeight();
// Older versions of android (pre API 21) cancel animations for views with a height of 0.
v.getLayoutParams().height = 1;
// v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? ViewGroup.LayoutParams.WRAP_CONTENT
: (int) (targetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
public static void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
// v.setVisibility(View.INVISIBLE);
} else {
v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
v.requestLayout();
}
}
@Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int) (initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
public static void visible(View... views) {
for (View view : views) {
view.setVisibility(View.VISIBLE);
}
}
public static void gone(View... views) {
for (View view : views) {
view.setVisibility(View.GONE);
}
}
public static void invisible(View... views) {
for (View view : views) {
view.setVisibility(View.INVISIBLE);
}
}
}
|
package com.walkerwang.algorithm.swordoffer;
class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
public class TreeNodeNext {
public static void main(String[] args) {
TreeLinkNode node1 = new TreeLinkNode(1);
TreeLinkNode node2 = new TreeLinkNode(2);
TreeLinkNode node3 = new TreeLinkNode(3);
TreeLinkNode node4 = new TreeLinkNode(4);
TreeLinkNode node5 = new TreeLinkNode(5);
node1.left = node2;
node1.right = node3;
node1.next = null;
node2.left = node4;
node2.right = node5;
node2.next = node1;
node3.left = node3.right = node3.next = null;
node4.left = node4.right = null;
node4.next = node2;
node5.left = node5.right = null;
node5.next = node2;
TreeLinkNode node = GetNext(node2);
System.out.println(node.val);
}
/**
* ����ʱ�䣺37ms
ռ���ڴ棺709k
*/
public static TreeLinkNode GetNext(TreeLinkNode pNode) {
if(pNode == null){
return null;
}
//������������ߵĽڵ�
if (pNode.right != null) {
pNode = pNode.right;
while(pNode.left != null){
pNode = pNode.left;
}
return pNode;
}
//�����������ұߵĽڵ�
while(pNode.next != null){
if (pNode.next.left == pNode) {
return pNode.next;
}
pNode = pNode.next;
}
return null;
}
}
|
package jp.android.obento;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.text.format.Time;
public class TimerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = {0, 1000, 500, 2000}; // OFF/ON/OFF/ON...
vibrator.vibrate(pattern, -1);
// AlarmManagerのインスタンスを取得
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OtokomaeObentoGetActivity.class);
i.putExtra(ObentoGetActivity.ON_TIMER, true);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent sender = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
// アラームを設定
Time t = new Time();
t.setToNow();
long now_time = t.toMillis(false);
long wake_time = now_time + 3500; // 0 + 1000 + 500 + 2000
am.set(AlarmManager.RTC_WAKEUP, wake_time, sender);
}
}
|
package com.github.manage;
import com.vic.common.base.form.BaseForm;
/**
* @ProjectName: vic-mall
* @Package: com.github.manage
* @Description: java类作用描述
* @Author: Vayne.Luo
* @date 2019/02/21
*/
public class TestController {
public static void main(String[] args) {
BaseForm baseForm = new BaseForm();
}
}
|
package com.deltastuido.payment.interfaces;
import java.util.Map;
import com.google.common.base.Preconditions;
public class ChannelPaymentParams {
public static ChannelPaymentParams forForm(String method, String action,
Map<String, String> inputs) {
Preconditions.checkArgument(method.toUpperCase().equals("POST")
|| method.toUpperCase().equals("GET"));
Preconditions.checkNotNull(action);
Preconditions.checkNotNull(inputs);
ChannelPaymentParams params = new ChannelPaymentParams();
params.setFormAction(action);
params.setFormInputs(inputs);
params.setFormMethod(method);
return params;
}
public static ChannelPaymentParams forQRCodeURI(String qrCodeUri) {
ChannelPaymentParams params = new ChannelPaymentParams();
params.setQrCodeURI(qrCodeUri);
return params;
}
private String formMethod;
private String formAction;
private Map<String, String> formInputs;
private String qrCodeURI;
public Map<String, String> getFormInputs() {
return formInputs;
}
public String getFormAction() {
return formAction;
}
public String getFormMethod() {
return formMethod;
}
public String getQRCodeURI() {
return null;
}
protected void setFormMethod(String formMethod) {
this.formMethod = formMethod;
}
protected void setFormAction(String formAction) {
this.formAction = formAction;
}
protected void setFormInputs(Map<String, String> formInputs) {
this.formInputs = formInputs;
}
public String getQrCodeURI() {
return qrCodeURI;
}
protected void setQrCodeURI(String qrCodeURI) {
this.qrCodeURI = qrCodeURI;
}
}
|
package simpleframework.core;
import com.xxw.HelloServlet;
import com.xxw.controller.MainPageController;
import org.junit.jupiter.api.*;
import java.lang.annotation.Target;
/**
* @author xiongxianwei
* 2020/6/7 0007
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class BeanContainerTest {
private static BeanContainer beanContainer;
@BeforeAll
static void init(){
beanContainer=BeanContainer.getBeanContainer();
System.out.println(beanContainer);
beanContainer=BeanContainer.getBeanContainer();
System.out.println(beanContainer);
}
@Order(1)
@DisplayName("loadBeanTest:加载目标包路径的所有Class对象和其实例")
@Test
public void loadBeanTest(){
Assertions.assertEquals(false,beanContainer.isLoaded());
beanContainer.loadBeans("com.xxw");
Assertions.assertEquals(4,beanContainer.beanMapSize());
Assertions.assertEquals(true,beanContainer.isLoaded());
}
@Order(2)
@DisplayName("getBeansTest:根据Class对象获取其实例")
@Test
public void getBeansTest(){
MainPageController mainPageController = (MainPageController) beanContainer.getBean(MainPageController.class);
Assertions.assertEquals(true,mainPageController instanceof MainPageController);
HelloServlet helloServlet= (HelloServlet) beanContainer.getBean(HelloServlet.class);
Assertions.assertEquals(false,helloServlet instanceof HelloServlet);
}
}
|
package org.scilab.forge.jlatexmath.graphics;
import org.robovm.apple.coregraphics.CGContext;
import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.uikit.UIImage;
import org.scilab.forge.jlatexmath.platform.graphics.Graphics2DInterface;
import org.scilab.forge.jlatexmath.platform.graphics.Image;
public class ImageI implements Image{
private UIImage mUIImage;
private CGContext mCGContext;
public ImageI(){
mUIImage = new UIImage();
// mCGContext = cgContext;
}
@Override
public int getWidth() {
// TODO Auto-generated method stub
return (int) mUIImage.getSize().getWidth();
}
@Override
public int getHeight() {
// TODO Auto-generated method stub
return (int) mUIImage.getSize().getHeight();
}
public Graphics2DInterface createGraphics2D(CGContext context, CGRect frame) {
// TODO Auto-generated method stub
mCGContext = context;
return new Graphics2DI(mCGContext, frame, mUIImage);
}
public UIImage getUIImage(){
return mUIImage;
}
@Override
public Graphics2DInterface createGraphics2D() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.example.android.hpquiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class Quiz extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
}
int score = 0;
public void summary (View view){
RadioButton ans1_2 = findViewById(R.id.ans1_2);
RadioButton ans2_2 = findViewById(R.id.ans2_2);
RadioButton ans3_2 = findViewById(R.id.ans3_2);
RadioButton ans4_1 = findViewById(R.id.ans4_1);
RadioButton ans5_4 = findViewById(R.id.ans5_4);
RadioButton ans6_3 = findViewById(R.id.ans6_3);
EditText ans7 = findViewById(R.id.ans7);
CheckBox ans8_1 = findViewById(R.id.ans8_1);
CheckBox ans8_2 = findViewById(R.id.ans8_2);
CheckBox ans8_3 = findViewById(R.id.ans8_3);
CheckBox ans8_4 = findViewById(R.id.ans8_4);
if (ans1_2.isChecked())
score += 1;
if (ans2_2.isChecked())
score += 1;
if (ans3_2.isChecked())
score += 1;
if (ans4_1.isChecked())
score += 1;
if (ans5_4.isChecked())
score += 1;
if (ans6_3.isChecked())
score += 1;
else
score = score;
String text7 = ans7.getText().toString().toLowerCase().replaceAll(" ","");
if (text7.equals("red") || text7.equals("scarlet") || text7.equals("crimson") || text7.equals("gules"))
score +=1;
if (!ans8_1.isChecked() && ans8_2.isChecked() && !ans8_3.isChecked() && ans8_4.isChecked())
score +=1;
String summaryText = "You scored "+score+" points!";
TextView scoreText = findViewById(R.id.score_text);
scoreText.setText(summaryText);
Toast.makeText(this , summaryText, Toast.LENGTH_SHORT).show();
//restart score
score = 0;
}
}
|
package shared;
import java.lang.*;
/** Class structure used for maitaining threshold information in
* Entropy to make score arrays.
*/
public class ThresholdInfo {
/** The index of this threshold.
*/
public int index;
/** The score value for this particular threshold.
*/
public double score;
/** The weight of this particular threshold.
*/
public double weight;
/** Constructor.
*/
public ThresholdInfo(){
index = Globals.UNDEFINED_INT;
score = Globals.UNDEFINED_REAL;
weight = Globals.UNDEFINED_REAL;
}
} |
package com.zhouyi.business.core.model;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* @author 杜承旭
* @ClassNmae: UploadPacketResponse
* @Description: TODO
* @date 2019/8/17 9:25
* @Version 1.0
**/
@Data
@ToString
public class UploadPacketResponse implements Serializable {
//数据包信息
private String pkId;
private String uploadLogId;
private String nodeSign;
private String fileServer;
private String fileLocation;
private String fileSuffix;
private BigDecimal fileSize;
private String fileMd5;
private String resolveStatus;
private String resolveResultInfo;
private Date resolveDatetime;
//节点信息
private String nodeCode;
private String nodeName;
private String nodeRequest;
private String nodeImg;
private String deleteFlag;
//采集过程信息
private Short collectStatus;
private Date collectDate;
private Short ord;
private String collectNodeId;
private Short isSkip;
private String skipReason;
private String skipUserId;
private Date skipDatetimetime;
//人员基本信息
private String ryjcxxcjbh;
private String jzrybh;
private String cjxxyydm;
private String xm;
private String xmhypy;
private String gmsfhm;
private String cyzjdm;
private String zjhm;
private String xbdm;
private Date csrq;
private String cym;
private String wwxm;
private String bmch;
private String gjdm;
private String mzdm;
private String jgssxdm;
private String csdssxdm;
private String csdxz;
private String hjdssxdm;
private String hjdxz;
private String type;
private String zzmmdm;
private String hyzkdm;
private String xldm;
private String grsfdm;
private String rylbdm;
private String xzdqhdm;
private String xzdxz;
private String ajlbdm;
private String cjrxm;
private String cjdwdm;
private String cjdwmc;
private Date cjsj;
private String tssfdm;
private String zjxydm;
private String collectCategoryId;
private String status;
private String schedule;
private String taskId;
private String equipmentCode;
private String deletag;
private String annex;
private String createUserId;
private Date createDatetime;
private String updateUserId;
private Date updateDatetime;
}
|
package com.elkattanman.farmFxml.repositories;
import com.elkattanman.farmFxml.domain.Treatment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface TreatmentRepository extends JpaRepository<Treatment, Integer>, JpaSpecificationExecutor<Treatment> {
} |
package com.tencent.mm.plugin.backup.a;
public class f$a {
public long endTime;
public String gRG;
public int gRH;
public long startTime;
public f$a(int i, String str, long j, long j2) {
this.gRH = i;
this.gRG = str;
this.startTime = j;
this.endTime = j2;
}
}
|
package com.mashibing.strategy;
import com.mashibing.Tank;
/**
* @program: tank
* @author: hduprince
* @create: 2020-04-07 15:49
**/
public interface FireStrategy {
void fire(Tank tank);
}
|
package com.example.news;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.ListView;
import com.example.news.Gson.News;
import com.example.news.Gson.NewsList;
import com.example.news.Util.HttpUtil;
import com.example.news.Util.UserDao;
import com.example.news.Util.Utility;
import java.util.List;
//创建子线程获取json数据
public class ThreadandRunnable {
private final static String httpUrl = "http://api.tianapi.com/";
private final static String APIKEY = "/?key=51577d0fae9b107351d70e8ed3a8c54b";
private List<News> news;
private String jsonResult="";
private Context mContext;
private ListView listView;
private Handler handler;
private String sort;
private UserDao userDao;
private boolean Interr = true;
public ThreadandRunnable(Context mContext, ListView listView, Handler handler, UserDao userDao, String str) {
super();
this.mContext = mContext;
this.listView = listView;
this.handler = handler;
this.sort = str;
this.userDao = userDao;
}
public List<News> ThreadandRunnable() {
new Thread(new Runnable() {
@Override
public void run() {
while (Interr) {
jsonResult = HttpUtil.request(httpUrl + sort + APIKEY, "num=10");
handler.post(runnable);
Log.d("MYTAG", jsonResult);
Interr = false; //获取json数据后终止线程
}
}
}).start();
return news;
}
Runnable runnable = new Runnable() {
@Override
public void run() {
//解析获取的json数据
NewsList newsList = Utility.parseJsonWithGson(jsonResult);
//将获取的数据添加到数据库总
userDao.addNews(newsList.getNewslist(), sort);
//从数据库中检索
news = userDao.selectNews(sort);
QueryAdapter queryAdapter = new QueryAdapter(mContext, news);
listView.setAdapter(queryAdapter);//设置listView的Adapter
}
};
public List<News> getList() {
return userDao.selectNews(sort);
}
}
|
package EBuilder;
public class Shoes{
private final Style style;
private final boolean laces;
private final boolean zipper;
private final int eyelets;
private final String color;
public Shoes(Style style, boolean laces, boolean zipper, int eyelets, String color) {
this.style = style;
this.laces = laces;
this.zipper = zipper;
this.eyelets = eyelets;
this.color = color;
}
@Override
public String toString() {
return "Shoes{" +
"style=" + style +
", laces=" + laces +
", zipper=" + zipper +
", eyelets=" + eyelets +
", color='" + color + '\'' +
'}';
}
}
|
package com.tencent.mm.plugin.appbrand.appcache;
import com.tencent.mm.plugin.appbrand.appcache.s.a;
import com.tencent.mm.plugin.appbrand.appcache.s.b;
import com.tencent.mm.sdk.platformtools.bi;
import java.util.concurrent.ConcurrentHashMap;
public final class l implements b {
private static final ConcurrentHashMap<String, Boolean> ffL = new ConcurrentHashMap();
/* renamed from: com.tencent.mm.plugin.appbrand.appcache.l$1 */
static /* synthetic */ class AnonymousClass1 {
static final /* synthetic */ int[] ffM = new int[a.values().length];
static {
try {
ffM[a.ffW.ordinal()] = 1;
} catch (NoSuchFieldError e) {
}
try {
ffM[a.ffX.ordinal()] = 2;
} catch (NoSuchFieldError e2) {
}
try {
ffM[a.ffY.ordinal()] = 3;
} catch (NoSuchFieldError e3) {
}
try {
ffM[a.ffZ.ordinal()] = 4;
} catch (NoSuchFieldError e4) {
}
try {
ffM[a.fga.ordinal()] = 5;
} catch (NoSuchFieldError e5) {
}
}
}
static /* synthetic */ boolean qF(String str) {
return !bi.oW(str) && Boolean.TRUE.equals(ffL.get(str));
}
public final a a(com.tencent.mm.plugin.appbrand.appcache.base.a aVar) {
if (ai.class == aVar.getClass() || ad.class == aVar.getClass() || ae.class == aVar.getClass()) {
return new a(aVar, (byte) 0);
}
return null;
}
public static void qE(String str) {
if (!bi.oW(str)) {
ffL.put(str, Boolean.valueOf(true));
}
}
}
|
/*
* Copyright (C) 2015 Hansoo Lab.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hansune.calendarproto.cal;
import java.util.Calendar;
import com.hansune.calendarproto.cal.WeatherInfo.Weather;
/**
* Value object for a day
* @author brownsoo
*
*/
public class OneDayData {
Calendar cal;
Weather weather;
private CharSequence msg = "";
/**
* OneDayData Constructor
*/
public OneDayData() {
this.cal = Calendar.getInstance();
this.weather = Weather.SUNSHINE;
}
/**
* Set day info with given data
* @param year 4 digits of year
* @param month month Calendar.JANUARY ~ Calendar.DECEMBER
* @param day day of month (1~#)
*/
public void setDay(int year, int month, int day) {
cal = Calendar.getInstance();
cal.set(year, month, day);
}
/**
* Set day info with cloning calendar
* @param cal calendar to clone
*/
public void setDay(Calendar cal) {
this.cal = (Calendar) cal.clone();
}
/**
* Get calendar
* @return Calendar instance
*/
public Calendar getDay() {
return cal;
}
/**
* Same function with {@link Calendar#get(int)}<br>
* <br>
*
* Returns the value of the given field after computing the field values by
* calling {@code complete()} first.
*
* @throws IllegalArgumentException
* if the fields are not set, the time is not set, and the
* time cannot be computed from the current field values.
* @throws ArrayIndexOutOfBoundsException
* if the field is not inside the range of possible fields.
* The range is starting at 0 up to {@code FIELD_COUNT}.
*/
public int get(int field) throws IllegalArgumentException, ArrayIndexOutOfBoundsException {
return cal.get(field);
}
/**
* Set weather info
* @param weather Weather instance
*/
public void setWeather(Weather weather) {
this.weather = weather;
}
/**
* Get weather info
* @return
*/
public Weather getWeather() {
return this.weather;
}
/**
* Get message
* @return message
*/
public CharSequence getMessage() {
return msg;
}
/**
* Set message
* @param msg message to display
*/
public void setMessage(CharSequence msg) {
this.msg = msg;
}
}
|
package com.tencent.mm.plugin.appbrand.appcache;
import com.tencent.mm.plugin.appbrand.appcache.h.d;
import java.io.File;
import java.io.FileFilter;
class h$d$1 implements FileFilter {
final /* synthetic */ d ffy;
h$d$1(d dVar) {
this.ffy = dVar;
}
public final boolean accept(File file) {
return file.isFile();
}
}
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Ventana extends JFrame implements ActionListener{
public JPanel panel;
public JTextField num1, num2;
public String con1, con2;
public JButton suma, resta, multi, division;
public float numero1 = 0, numero2 = 0, resultado = 0;
public JLabel result;
public Ventana(){
this.setSize(300, 400);
setLocationRelativeTo(null);
setTitle("Calculadora");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pantalla();
}//Ventana
public void pantalla(){
panel = new JPanel();
panel.setLayout(null);
this.getContentPane().add(panel);
num1 = new JTextField();
num1.setBounds(50, 20, 200, 30);
num1.setText("0");
panel.add(num1);
num2 = new JTextField();
num2.setBounds(50, 70, 200, 30);
num2.setText("0");
panel.add(num2);
result = new JLabel();
result.setOpaque(true);
result.setText("El resultado es " + resultado);
result.setBounds(50, 120, 200, 30);
result.setForeground(Color.WHITE);
panel.add(result);
result.setBackground(Color.BLACK);
suma = new JButton("suma");
suma.setBounds(50, 170, 200, 30);
panel.add(suma);
suma.addActionListener(this);
resta = new JButton("resta");
resta.setBounds(50, 220, 200, 30);
panel.add(resta);
resta.addActionListener(this);
multi = new JButton("multuplicacion");
multi.setBounds(50, 270, 200, 30);
panel.add(multi);
multi.addActionListener(this);
division = new JButton("division");
division.setBounds(50, 320, 200, 30);
panel.add(division);
division.addActionListener(this);
}//Elementos en pantalla
public void actionPerformed(ActionEvent evento){
if(evento.getSource() == suma){
setNums();
resultado = numero1 + numero2;
mostrarResultado();
}
if(evento.getSource() == resta){
setNums();
resultado = numero1 - numero2;
mostrarResultado();
}
if(evento.getSource() == multi){
setNums();
resultado = numero1 * numero2;
mostrarResultado();
}
if(evento.getSource() == division){
setNums();
resultado = numero1 / numero2;
mostrarResultado();
}
}//Eventos
public void setNums(){
con1 = num1.getText();
numero1 = Float.parseFloat(con1);
con2 = num2.getText();
numero2 = Float.parseFloat(con2);
}//Setea los numero al valor actual que hay en las cajas de texto
public void mostrarResultado(){
result.setText("El resultado es " + resultado);
System.out.println("el resultado es " + resultado);
System.out.println("los numeros son " + numero1 + " y " + numero2);
}//Muestra los resultados de la operacion de 2 numeros
}//Clase |
package q3;
public class FindRepeatedNum {
public static <T> int[] FindRepeated(T[] list) {
int[] arr = new int[list.length];
int c=0;
for(int i=0;i<list.length;i++)
{
for(int j=i+1;j<list.length;j++)
if(list[i]==list[j]) {
arr[c]=(int) list[i] ;
System.out.println(arr[c]);
c++;
}
}
return arr;
}
}
|
/*
* Copyright © 2019 The GWT Project Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gwtproject.dom.client;
import org.gwtproject.core.client.JavaScriptObject;
import org.gwtproject.core.client.JsArrayString;
import org.gwtproject.core.client.Scheduler;
import org.gwtproject.core.client.Scheduler.ScheduledCommand;
/**
* Used to add stylesheets to the document. The one-argument versions of {@link #inject}, {@link
* #injectAtEnd}, and {@link #injectAtStart} use {@link Scheduler#scheduleFinally} to minimize the
* number of individual style elements created.
*/
public class StyleInjector {
private static HeadElement head;
private static final JsArrayString toInject = JavaScriptObject.createArray().cast();
private static final JsArrayString toInjectAtEnd = JavaScriptObject.createArray().cast();
private static final JsArrayString toInjectAtStart = JavaScriptObject.createArray().cast();
private static ScheduledCommand flusher =
new ScheduledCommand() {
public void execute() {
if (needsInjection) {
flush(null);
}
}
};
private static boolean needsInjection = false;
/**
* Flushes any pending stylesheets to the document.
*
* <p>This can be useful if you used CssResource.ensureInjected but now in the same event loop
* want to measure widths based on the new styles.
*
* <p>Note that calling this method excessively will decrease performance.
*/
public static void flush() {
inject(true);
}
/**
* Add a stylesheet to the document.
*
* @param css the CSS contents of the stylesheet
*/
public static void inject(String css) {
inject(css, false);
}
/**
* Add a stylesheet to the document.
*
* @param css the CSS contents of the stylesheet
* @param immediate if <code>true</code> the DOM will be updated immediately instead of just
* before returning to the event loop. Using this option excessively will decrease
* performance, especially if used with an inject-css-on-init coding pattern
*/
public static void inject(String css, boolean immediate) {
toInject.push(css);
inject(immediate);
}
/**
* Add stylesheet data to the document as though it were declared after all stylesheets previously
* created by {@link #inject(String)}.
*
* @param css the CSS contents of the stylesheet
*/
public static void injectAtEnd(String css) {
injectAtEnd(css, false);
}
/**
* Add stylesheet data to the document as though it were declared after all stylesheets previously
* created by {@link #inject(String)}.
*
* @param css the CSS contents of the stylesheet
* @param immediate if <code>true</code> the DOM will be updated immediately instead of just
* before returning to the event loop. Using this option excessively will decrease
* performance, especially if used with an inject-css-on-init coding pattern
*/
public static void injectAtEnd(String css, boolean immediate) {
toInjectAtEnd.push(css);
inject(immediate);
}
/**
* Add stylesheet data to the document as though it were declared before all stylesheets
* previously created by {@link #inject(String)}.
*
* @param css the CSS contents of the stylesheet
*/
public static void injectAtStart(String css) {
injectAtStart(css, false);
}
/**
* Add stylesheet data to the document as though it were declared before all stylesheets
* previously created by {@link #inject(String)}.
*
* @param css the CSS contents of the stylesheet
* @param immediate if <code>true</code> the DOM will be updated immediately instead of just
* before returning to the event loop. Using this option excessively will decrease
* performance, especially if used with an inject-css-on-init coding pattern
*/
public static void injectAtStart(String css, boolean immediate) {
toInjectAtStart.unshift(css);
inject(immediate);
}
/**
* Add a stylesheet to the document.
*
* @param contents the CSS contents of the stylesheet
* @return the StyleElement that contains the newly-injected CSS
*/
public static StyleElement injectStylesheet(String contents) {
toInject.push(contents);
return flush(toInject);
}
/**
* Add stylesheet data to the document as though it were declared after all stylesheets previously
* created by {@link #injectStylesheet(String)}.
*
* @param contents the CSS contents of the stylesheet
* @return the StyleElement that contains the newly-injected CSS
*/
public static StyleElement injectStylesheetAtEnd(String contents) {
toInjectAtEnd.push(contents);
return flush(toInjectAtEnd);
}
/**
* Add stylesheet data to the document as though it were declared before any stylesheet previously
* created by {@link #injectStylesheet(String)}.
*
* @param contents the CSS contents of the stylesheet
* @return the StyleElement that contains the newly-injected CSS
*/
public static StyleElement injectStylesheetAtStart(String contents) {
toInjectAtStart.unshift(contents);
return flush(toInjectAtStart);
}
/**
* Replace the contents of a previously-injected stylesheet. Updating the stylesheet in-place is
* typically more efficient than removing a previously-created element and adding a new one.
*
* @param style a StyleElement previously-returned from {@link #injectStylesheet(String)}.
* @param contents the new contents of the stylesheet.
*/
public static void setContents(StyleElement style, String contents) {
style.setInnerText(contents);
}
/** The <code>which</code> parameter is used to support the injectStylesheet API. */
private static StyleElement flush(JavaScriptObject which) {
StyleElement toReturn = null;
StyleElement maybeReturn;
if (toInjectAtStart.length() != 0) {
String css = toInjectAtStart.join("");
maybeReturn = injectStyleSheetAtStart(css);
if (toInjectAtStart == which) {
toReturn = maybeReturn;
}
toInjectAtStart.setLength(0);
}
if (toInject.length() != 0) {
String css = toInject.join("");
maybeReturn = injectStyleSheet(css);
if (toInject == which) {
toReturn = maybeReturn;
}
toInject.setLength(0);
}
if (toInjectAtEnd.length() != 0) {
String css = toInjectAtEnd.join("");
maybeReturn = injectStyleSheetAtEnd(css);
if (toInjectAtEnd == which) {
toReturn = maybeReturn;
}
toInjectAtEnd.setLength(0);
}
needsInjection = false;
return toReturn;
}
private static void inject(boolean immediate) {
if (immediate) {
flush(null);
} else {
schedule();
}
}
private static void schedule() {
if (!needsInjection) {
needsInjection = true;
Scheduler.get().scheduleFinally(flusher);
}
}
private static StyleElement injectStyleSheet(String contents) {
StyleElement style = createElement(contents);
getHead().appendChild(style);
return style;
}
private static StyleElement injectStyleSheetAtEnd(String contents) {
return injectStyleSheet(contents);
}
private static StyleElement injectStyleSheetAtStart(String contents) {
StyleElement style = createElement(contents);
getHead().insertBefore(style, head.getFirstChild());
return style;
}
private static StyleElement createElement(String contents) {
StyleElement style = Document.get().createStyleElement();
style.setPropertyString("language", "text/css");
style.setInnerText(contents);
return style;
}
private static HeadElement getHead() {
if (head == null) {
Element elt = Document.get().getHead();
assert elt != null
: "The host HTML page does not have a <head> element"
+ " which is required by StyleInjector";
head = HeadElement.as(elt);
}
return head;
}
/** Utility class. */
private StyleInjector() {}
}
|
import javax.swing.*;
import java.awt.*;
import java.text.DecimalFormat;
public class Taux extends JPanel{
private JLabel jlTaux;
private boolean couleurInverser;
public Taux(String nom) {
super();
this.couleurInverser = false;
JLabel jlTextTaux = new JLabel(nom);
jlTaux = new JLabel(" ");
this.setLayout(new GridBagLayout());
GridBagConstraints contraintes = new GridBagConstraints();
contraintes.gridx = 0;
contraintes.gridy = 0;
contraintes.gridwidth = 1;
contraintes.gridheight = 1;
contraintes.fill = GridBagConstraints.HORIZONTAL;
contraintes.anchor = GridBagConstraints.NORTH;
contraintes.insets = new Insets(10,10,10,10); // marge sur les cotés
contraintes.weightx=0.0f;
contraintes.weighty=0.0f;
this.add(jlTextTaux, contraintes);
contraintes.gridx = 0;
contraintes.gridy = 1;
contraintes.gridwidth = 1;
contraintes.gridheight = 1;
contraintes.fill = GridBagConstraints.VERTICAL;
contraintes.anchor = GridBagConstraints.CENTER;
contraintes.insets = new Insets(0,5,5,5); // marge sur les cotés
contraintes.weightx=0.0f;
contraintes.weighty=1.0f;
Font font = new Font("Arial",Font.BOLD,20);
jlTaux.setFont(font);
this.add(jlTaux, contraintes);
}
public void setTaux(float nouvelValeur) {
Color clr[] = new Color[4];
if(couleurInverser) {
clr[3] = Color.red;
clr[2] = Color.orange;
clr[1] = new Color(0,100,0);
clr[0] = new Color(0,200,0);
} else {
clr[0] = Color.red;
clr[1] = Color.orange;
clr[2] = new Color(0,100,0);
clr[3] = new Color(0,200,0);
}
System.out.println(couleurInverser);
if(nouvelValeur<=25) {
jlTaux.setForeground(clr[0]);
} else if (nouvelValeur<=50) {
jlTaux.setForeground(clr[1]);
} else if (nouvelValeur<=75) {
jlTaux.setForeground(clr[2]);
} else {
jlTaux.setForeground(clr[3]);
}
DecimalFormat fd = new DecimalFormat("###.##");
jlTaux.setText(""+fd.format(nouvelValeur)+"%");
}
public void setCouleurInverser(boolean d) {
this.couleurInverser = d;
}
}
|
public class GasStation extends Company implements GasService {
// variaveis de instância de GasStation
private double gasPrice;
private String sname;
// construtor default de GasStation
public GasStation() {
}
// construtor de GasStation
public GasStation(double gasPrice, String sname, String name, int vatNumber) {
super(name, vatNumber);
this.gasPrice = gasPrice;
this.sname = sname;
}
@Override
public double getGasPrice() {
return gasPrice;
}
@Override
public void setGasPrice(double p) {
if (p > 0) {
gasPrice = p;
}
}
@Override
public double getGasTotal(double litres) {
double total;
total = litres * gasPrice;
return total;
}
@Override
public String toString() {
String text = "";
text += super.toString();
text += "Station name: " + sname + "\n";
text += "Gas price per litre: " + gasPrice + " €";
return text;
}
}
|
/*
* 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 myobs;
/**
*
* @author egese
*/
public class LetterNote extends UserLogin{
double[] Letters = new double[5]; // Harf Notu için
double[] Kredi = new double[]{6.0,5.0,6.0,6.0,2.0}; // Her bir ders için verilmiş krediler
String Harf ;
public void LetterNote()
{
}
protected String FindLetterNote(int[][][] x,int i) // Notların Harf ve Harf notu karşılığını tespit etmek için kullanılır
{
LetterNote y = new LetterNote();
int toplam = 0;
toplam+= x[i][0][tempID -1]*0.4 +x[i][1][tempID -1]*0.6; // Vize %40 , Final %60 şeklinde
if(toplam<=100 && toplam>=90)
{
Letters[i]= 4.0 ;
Harf = "AA";
}
else if(toplam<=89 && toplam >=80)
{
Letters[i] = 3.5;
Harf= "BA" ;
}
else if(toplam<=79 && toplam>=75) {
Letters[i] =3.0;
Harf = "BB";
}
else if(toplam<=74 && toplam>=70){
Letters[i] =2.5;
Harf = "CB";
}
else if(toplam<=69 && toplam>=65){
Letters[i] =2.0;
Harf = "CC";
}
else if(toplam<=64 && toplam>=60){
Letters[i] =1.5;
Harf = "DC";
}
else if(toplam<=59 && toplam>=55){
Letters[i] =1.0;
Harf = "DD";
}
else if(toplam<=54 && toplam>=35){
Letters[i] =0.5;
Harf = "FD";
}
else if(toplam<=34 && toplam>=0){
Letters[i] = 0.0;
Harf = "FF";
}
return Harf ;
}
}
|
package com.encore.spring.service;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.encore.spring.dao.MemberDAO;
import com.encore.spring.vo.MemberVO;
@Service
public class MemberServiceImpl implements MemberService{
@Autowired
private MemberDAO memberDAO;
@Override
public MemberVO loginCheck(MemberVO vo) throws SQLException {
return memberDAO.loginCheck(vo);
}
@Override
public void add(MemberVO vo) throws Exception {
memberDAO.add(vo);
}
}
|
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class UpdateNomination extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{
HttpSession session=req.getSession(false);
String rollno=(String)session.getAttribute("rollno");
session.setAttribute("rollno1",rollno);
out.println("welcome"+rollno);
out.println("\n");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","system");
Statement stmt= con.createStatement();
ResultSet rs=stmt.executeQuery("select * from studentvoter where rollno='"+rollno+"'");
while(rs.next())
{
String rno=rs.getString(1);
String name=rs.getString(3);
if(rs.getInt(5)==1)
{
ResultSet rs1=stmt.executeQuery("select rollno from nominations where rollno='"+rollno+"'");
if(rs1.next())
{
out.println("already nominated");
}
else
{
String sql1 = "insert into nominations " + "values ('"+rno+"' , '"+name+"', 0)";
stmt.executeUpdate(sql1);
out.println("successfully nominated");
}
}
else
{
out.println("you are not eligible to nominate");
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
} |
package at.fhj.swd.presentation.viewHelper;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.transaction.NotSupportedException;
import at.fhj.swd.data.entity.Community;
import at.fhj.swd.data.entity.User;
import at.fhj.swd.presentation.helper.CookieHelper;
import at.fhj.swd.service.CommunityService;
import at.fhj.swd.service.UserService;
import at.fhj.swd.service.exceptions.ServiceLayerException;
/**
* Community Administration - ViewHelper.
*
* @author Group4
* */
@ManagedBean(name="dtCommunitiesAdminView")
@ViewScoped
public class CommunityAdminView implements Serializable {
private static final long serialVersionUID = 6330672338108028518L;
private transient List<Community> communities = null;
@Inject
private transient Logger logger;
@Inject
private transient CommunityService communityService;
@SuppressWarnings("cdi-ambiguous-dependency")
@Inject
private transient UserService userService;
@Inject
private transient FacesContext facesContext;
private String createCommunity;
private long releaseCommunity;
private boolean userHasAccess;
@PostConstruct
public void init() {
// ensure administrator.
ensureUserHasAccess();
if(getUserHasAccess()) {
communities = communityService.getAllCommunities();
}
}
public List<Community> getCommunities() {
return communities;
}
public void setDeleteCommunity(int id) throws NotSupportedException {
throw new NotSupportedException();
}
public long getReleaseCommunity() {
return releaseCommunity;
}
public void setReleaseCommunity(long id) {
this.releaseCommunity = id;
}
public String getCreateCommunity() {
return this.createCommunity;
}
public void setCreateCommunity(String name) {
this.createCommunity = name;
}
public boolean getUserHasAccess() {
return userHasAccess;
}
public void setUserHasAccess(boolean userHasAccess) {
this.userHasAccess = userHasAccess;
}
public void create() {
System.out.println("create");
if(!getUserHasAccess()) {
facesContext.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_WARN, "You are not signed in as Administrator.", null));
setCreateCommunity(null);
}
else {
try {
// create community.
communityService.createCommunity(createCommunity, false);
// redirection.
ExternalContext ec = facesContext.getExternalContext();
logger.info("path: " + ec.getRequestContextPath() + "/admin/community_list.jsf");
ec.redirect(ec.getRequestContextPath() + "/admin/community_list.jsf");
} catch(ServiceLayerException e) {
facesContext.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_WARN, "Failed to create community.", null));
} catch(IOException e) {
facesContext.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Redirection failed", null));
}
}
}
public void release() {
if(!getUserHasAccess()) {
facesContext.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_WARN, "You are not signed in as Administrator.", null));
setCreateCommunity(null);
return;
}
try {
Long communityId = new Long(releaseCommunity);
Community community = communityService.getCommunityById(communityId.longValue());
communityService.releaseCommunity(communityId, !community.isVisible());
// redirection.
ExternalContext ec = facesContext.getExternalContext();
logger.info("path: " + ec.getRequestContextPath() + "/admin/community_list.jsf");
ec.redirect(ec.getRequestContextPath() + "/admin/community_list.jsf");
} catch(ServiceLayerException e) {
facesContext.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_WARN, "Failed to release community.", null));
} catch(IOException e) {
facesContext.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Redirection failed", null));
}
}
private void ensureUserHasAccess() {
logger.log(Level.INFO, "Calling " + this.getClass().getName() + "::ensureUserIsAdmin()!");
String token = CookieHelper.getAuthTokenValue();
User user = userService.getRegisteredUser(token);
if(user == null) {
setUserHasAccess(false);
} else {
boolean hasAccess = user.getUsername().endsWith("_a");
logger.log(Level.INFO, "Loaded user [" + user + "] hasAccess [" + hasAccess +"]");
setUserHasAccess(hasAccess);
}
}
}
|
package io.pivotal.pccpizza.config;
import org.springframework.cloud.service.BaseServiceInfo;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ServiceInfo extends BaseServiceInfo {
private final Pattern p = Pattern.compile("(.*)\\[(\\d*)\\]");
private URI[] locators;
private User user;
public ServiceInfo(String id, List<String> locators, List<Map<String, String>> users) {
super(id);
parseLocators(locators);
parseUsers(users);
}
private void parseLocators(List<String> locators) {
ArrayList<URI> uris = new ArrayList<URI>(locators.size());
for (String locator : locators) {
uris.add(parseLocator(locator));
}
this.locators = uris.toArray(new URI[uris.size()]);
}
private URI parseLocator(String locator) throws IllegalArgumentException {
Matcher m = p.matcher(locator);
if (!m.find()) {
throw new IllegalArgumentException("Could not parse locator url. Expected format host[port], received: " + locator);
} else {
if (m.groupCount() != 2) {
throw new IllegalArgumentException("Could not parse locator url. Expected format host[port], received: " + locator);
}
try {
return new URI("locator://" + m.group(1) + ":" + m.group(2));
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Malformed URL " + locator);
}
}
}
private void parseUsers(List<Map<String, String>> users) {
if (users == null) return;
for (Map<String, String> map : users) {
User user = new User(map);
if (user.isClusterOperator()) {
this.user = user;
break;
}
}
}
public URI[] getLocators() {
return locators;
}
public String getUsername() {
return user != null ? user.getUsername() : null;
}
public String getPassword() {
return user != null ? user.getPassword() : null;
}
}
|
package com.czx.web.servlet;
import com.czx.framework.annotations.Component;
import com.czx.framework.container.ClassContainer;
import com.czx.framework.container.RegisterMachine;
import com.czx.web.handler.RequestHandler;
import com.czx.web.route.RouteContainer;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Morgan
* @date 2020/12/2 9:46
*/
@WebServlet
@Component
public class DefaultServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
//请求处理
RequestHandler.execute(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
doGet(req, resp);
}
}
|
package org.openfuxml.test.provider;
import org.openfuxml.content.ofx.Document;
import org.openfuxml.content.ofx.Section;
import org.openfuxml.factory.xml.ofx.content.structure.XmlDocumentFactory;
import org.openfuxml.renderer.latex.structure.TestLatexParagraphRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DocumentProvider extends AbstractElementProvider
{
final static Logger logger = LoggerFactory.getLogger(TestLatexParagraphRenderer.class);
public static Document build()
{
Document xml = XmlDocumentFactory.withContent();
xml.getContent().getContent().add(SectionProvider.build());
xml.getContent().getContent().add(SectionProvider.build());
return xml;
}
public static Document buildWithSubcontent()
{
Document xml = XmlDocumentFactory.withContent();
Section s1 = SectionProvider.build();
s1.getContent().add(SectionProvider.buildWithComment());
xml.getContent().getContent().add(s1);
return xml;
}
} |
//package com.zp.controller;
//
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.cloud.context.config.annotation.RefreshScope;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
///**
// * 该类用于模拟,我们要使用共享的那些配置信息做一些事情
// */
//@RestController
//@RequestMapping("/config")
//@RefreshScope
//public class ConfigController {
//
// // 和取本地配置信息一样
// @Value("${lagou.message}")
// private String lagouMessage;
// @Value("${mysql.url}")
// private String mysqlUrl;
//
//
// // 内存级别的配置信息
// // 数据库,redis配置信息
//
// @GetMapping("/viewconfig")
// public String viewconfig() {
// return "lagouMessage==>" + lagouMessage + " mysqlUrl=>" + mysqlUrl;
// }
//}
|
package de.fhb.ott.pagetox.util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
/**
* @author Christoph Ott
*/
public class PropertyLoader {
/**
* load the SystemProperty
*
* @param path to property file
* @return Properties
* @throws IOException
*/
public static Properties loadProperty(String path) throws IOException {
Properties props = new Properties();
ClassLoader loader = PropertyLoader.class.getClassLoader();
InputStream in = loader.getResourceAsStream(path);
props.load(in);
return props;
}
public static void loadPropertyToSystemProp(String path) throws IOException {
Properties properties = loadProperty(path);
for (Object key : properties.keySet()) {
System.setProperty(key.toString(), properties.get(key).toString());
}
}
public static List<String> loadPropertiesAsList(String path) throws IOException {
List<String> list = new ArrayList<>();
ClassLoader loader = PropertyLoader.class.getClassLoader();
URL in = loader.getResource(path);
BufferedReader read;
if (in != null) {
read = new BufferedReader(new FileReader(in.getFile()));
String line;
while ((line = read.readLine()) != null) {
list.addAll(Arrays.asList(line.split(" ")));
}
}
return list;
}
}
|
package de.zarncke.lib.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import de.zarncke.lib.coll.L;
import de.zarncke.lib.coll.Pair;
import de.zarncke.lib.err.Warden;
import de.zarncke.lib.io.StreamWithName;
/**
* Communication with a internet services e.g. a web-server.
*/
public final class NetTools {
// TODO make pass-in parameter
private static final int MAX_HEAD_REQUEST_TIMEOUT_MS = 10000;
public static final String LOCALHOST = "localhost";
public static final String HOSTNAME_ENV_VARIABLE = "env.HOSTNAME";
private NetTools() {
// helper
}
private static final int MAX_REDIRECTS = 8;
private static final String POST_ENCODING = "ISO-8859-1";
/**
* Opens an InputStream from an URL and returns it and its name - either the URL or the last Location header in case
* of redirects.
*
* @param connection != null
* @return StreamWithName which also contains last modification date and header gields as meta information,
* the stream may be null in case the last request/redirect failed
* @throws IOException if unreadable
*/
public static StreamWithName getInputStreamAndName(final URLConnection connection) throws IOException {
URLConnection currentConn = connection;
boolean redir;
int redirects = 0;
String location = currentConn.getURL().getPath();
InputStream in = null;
do {
if (currentConn instanceof HttpURLConnection) {
((HttpURLConnection) currentConn).setInstanceFollowRedirects(false);
}
currentConn.setConnectTimeout(MAX_HEAD_REQUEST_TIMEOUT_MS);
currentConn.setReadTimeout(MAX_HEAD_REQUEST_TIMEOUT_MS);
// We want to open the input stream before getting headers
// because getHeaderField() et al swallow IOExceptions.
in = currentConn.getInputStream();
redir = false;
if (currentConn instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) currentConn;
int stat = http.getResponseCode();
if (stat >= 300 && stat <= 307 && stat != 306 && stat != 304) {
URL base = http.getURL();
String loc = http.getHeaderField("Location");
URL target = null;
if (loc == null) {
throw Warden.spot(new IOException("redirect to " + location + " producted response " + stat
+ " without Location header."));
}
target = new URL(base, loc);
http.disconnect();
checkRedirects(redirects, target);
redir = true;
location = target.getPath();
currentConn = target.openConnection();
redirects++;
}
}
} while (redir);
return new StreamWithName(in, location, currentConn.getHeaderFields()).setTime(new DateTime(currentConn
.getLastModified(), DateTimeZone.UTC));
}
/**
* Opens an URLConnections and returns effective name and time - either the URL or the last Location header in case
* of redirects.
*
* @param connection != null
* @return StreamWithName
* @throws IOException if unreadable or status code != 200 or 204
*/
public static Pair<String, Long> getEffectiveName(final URLConnection connection) throws IOException {
String location = connection.getURL().getPath();
if (!(connection instanceof HttpURLConnection)) {
return Pair.pair(location, Q.l(connection.getLastModified()));
}
HttpURLConnection currentConn = (HttpURLConnection) connection;
boolean redir;
int redirects = 0;
do {
currentConn.setInstanceFollowRedirects(false);
currentConn.setRequestMethod("HEAD");
currentConn.setConnectTimeout(MAX_HEAD_REQUEST_TIMEOUT_MS);
currentConn.setReadTimeout(MAX_HEAD_REQUEST_TIMEOUT_MS);
redir = false;
int stat = currentConn.getResponseCode();
if (stat >= 300 && stat <= 307 && stat != 306 && stat != 304) {
URL base = currentConn.getURL();
String loc = currentConn.getHeaderField("Location");
URL target = null;
if (loc == null) {
throw Warden.spot(new IOException("redirect to " + location + " produced response " + stat
+ " without Location header."));
}
target = new URL(base, loc);
currentConn.disconnect();
checkRedirects(redirects, target);
redir = true;
location = target.getPath();
currentConn = (HttpURLConnection) target.openConnection();
redirects++;
} else if (stat != 200 && stat != 204) {
throw Warden.spot(new IOException("HEAD request to " + location + " produced response " + stat + "."));
}
} while (redir);
return Pair.pair(location, Q.l(currentConn.getLastModified()));
}
private static void checkRedirects(final int redirects, final URL target) {
// Redirection should be allowed only for HTTP and HTTPS
// and should be limited to 8 redirections at most.
if (!(target.getProtocol().equals("http") || target.getProtocol().equals("https"))
|| redirects >= MAX_REDIRECTS) {
throw Warden.spot(new SecurityException("illegal URL redirect"));
}
}
/**
* Local hostname.
*
* @return $HOSTNAME
*/
public static String getHostName() {
String host = Misc.ENVIRONMENT.get().get(HOSTNAME_ENV_VARIABLE);
if (host == null) {
try {
InetAddress addr = InetAddress.getLocalHost();
host = addr.getHostName();
} catch (UnknownHostException e) {
host = LOCALHOST;
}
}
return host;
}
public static Collection<InetAddress> getHostIpAdresses() {
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e1) {
return L.e();
}
try {
String host = addr.getHostName();
return Arrays.asList(InetAddress.getAllByName(host));
} catch (UnknownHostException e) {
return L.l(addr);
}
}
/**
* This method performs a post to the specified URL and delivers its reply.
*
* @param urlString A String representing the URL you want to post to.
* @param post A Reader representing the content you want to post.
* @return A Reader representing the reply after your post.
* @throws MalformedURLException if so
* @throws IOException on connect
*/
public static Reader doPost(final String urlString, final Reader post) throws MalformedURLException, IOException {
Reader result = null;
URLConnection conn = null;
OutputStream urlOutputStream = null;
int tempChar = 0;
nonNullUrl(urlString);
if (post == null) {
throw new IllegalArgumentException("Writer to post is null.");
}
try {
// Establishing connection
URL url = new URL(urlString);
conn = url.openConnection();
/*
* if (conn instanceof HttpsURLConnectionImpl)
* {
* System.out.println("conn "+conn);
* HttpsURLConnectionImpl huc = (HttpsURLConnectionImpl) conn;
* javax.net.ssl.HostnameVerifier hv = new javax.net.ssl.HostnameVerifier()
* {
* public boolean verify(String arg0, SSLSession arg1)
* {
* System.out.println(arg0);
* return true;
* }
* public boolean verify(String arg0, String arg1)
* {
* System.out.println(arg0 + "\n" + arg1);
* return true;
* }
* };
* huc.setHostnameVerifier(hv);
* }
*/
// Preparing post
conn.setDoOutput(true);
urlOutputStream = conn.getOutputStream();
// Posting
while ((tempChar = post.read()) >= 0) {
urlOutputStream.write(tempChar);
}
// Reading reply
result = new InputStreamReader(conn.getInputStream());
} catch (MalformedURLException e) {
throw (MalformedURLException) new MalformedURLException("URL \"" + urlString + "\" is malformed.")
.initCause(e);
} catch (IOException e) {
throw (IOException) new IOException("Error while posting to \"" + urlString + "\".").initCause(e);
}
return result;
}
/**
* This method performs a post to the specified URL and delivers its reply.
*
* @param urlString A String representing the URL you want to post to.
* @param post A String representing the content you want to post.
* @return A String representing the reply after your post.
* @throws java.net.MalformedURLException if so
* @throws java.io.IOException of post
*/
public static String doPost(final String urlString, final String post) throws MalformedURLException, IOException {
String result = null;
URLConnection conn = null;
OutputStream urlOutputStream = null;
InputStream urlInputStream = null;
StringWriter content = new StringWriter();
int tempChar = 0;
int tempByte = 0;
nonNullUrl(urlString);
if (post == null) {
throw new IllegalArgumentException("String to post is null.");
}
try {
StringReader postReader = new StringReader(post);
// Establishing connection
URL url = new URL(urlString);
conn = url.openConnection();
// Preparing post
conn.setDoOutput(true);
urlOutputStream = conn.getOutputStream();
// Posting
while ((tempChar = postReader.read()) >= 0) {
urlOutputStream.write(tempChar);
}
// Reading reply
urlInputStream = conn.getInputStream();
while ((tempByte = urlInputStream.read()) >= 0) {
content.write(tempByte);
}
result = content.toString();
} catch (MalformedURLException e) {
throw (MalformedURLException) new MalformedURLException("URL \"" + urlString + "\" is malformed.")
.initCause(e);
} catch (IOException e) {
throw new IOException("Error while posting to \"" + urlString + "\".", e);
}
return result;
}
private static void nonNullUrl(final String urlString) {
if (urlString == null) {
throw new IllegalArgumentException("URL to post to is null.");
}
}
/**
* This method delivers a reply of the specified URL.
*
* @param urlString A String representing the URL from which you want to get a reply.
* @return A Reader representing the reply from the URL.
* @throws java.net.MalformedURLException
* @throws java.io.IOException
* @see java.io.Reader
*/
public static Reader doGetReader(final String urlString) throws MalformedURLException, IOException {
Reader result = null;
// Checking argument
if (urlString == null) {
throw new IllegalArgumentException("URL to get from is null.");
}
try {
// Establishing connection and reading from it
URL url = new URL(urlString);
result = new InputStreamReader(url.openStream());
} catch (MalformedURLException e) {
throw (MalformedURLException) new MalformedURLException("URL \"" + urlString + "\" is malformed.")
.initCause(e);
} catch (IOException e) {
throw new IOException("Error while opening stream from \"" + urlString + "\".", e);
}
return result;
}
/**
* This method delivers a reply of the specified URL.
*
* @param urlString A String representing the URL from which you want to get a reply.
* @return A String representing the reply from the URL.
* @throws java.net.MalformedURLException URL
* @throws java.io.IOException network
*/
public static String doGetString(final String urlString) throws MalformedURLException, IOException {
String result = null;
InputStream urlInputStream = null;
StringWriter content = new StringWriter();
int tempByte = 0;
// Checking argument
if (urlString == null) {
throw new IllegalArgumentException("URL to get from is null.");
}
try {
// Establishing connection
URL url = new URL(urlString);
urlInputStream = url.openStream();
// Reading from it
while ((tempByte = urlInputStream.read()) >= 0) {
content.write(tempByte);
}
// Converting output
result = content.toString();
} catch (MalformedURLException e) {
throw (MalformedURLException) new MalformedURLException("URL \"" + urlString + "\" is malformed.")
.initCause(e);
} catch (IOException e) {
throw new IOException("Error while reading stream from \"" + urlString + "\".", e);
}
return result;
}
/**
* This method provides the WebClient as command-line tool.
* Its usage will be explained when you enter "-help" as parameter for the WebClient in command-line mode.
*
* @param url to post to
* @param data to post as form parameters
* @return Reader for the response; the caller has the duty to close it
* @throws Exception on any errors
*/
public static Reader doPost(final String url, final Map<?, ?> data) throws Exception {
StringBuffer content = new StringBuffer();
for (Map.Entry<?, ?> element : data.entrySet()) {
content.append(element.getKey()).append("=")
.append(URLEncoder.encode((String) element.getValue(), POST_ENCODING));
content.append("&");
}
content.setLength(content.length() - 1);
Reader reader = new StringReader(content.toString());
return doPost(url, reader);
}
}
|
// assignment 10
// pair p134
// Singh, Bhavneet
// singhb
// Wang, Shiyu
// shiyu
import java.util.ArrayList;
import tester.*;
/** Class to hold examples of data and tests */
public class ExamplesWords {
public ExamplesWords() { }
/** Test Word Classes... */
public void testWords(Tester t) {
String s = "hey";
//test for equals and hashCode
t.checkExpect(new Word("hey").equals(new Word("hey")), true);
t.checkExpect(new Word("hey").equals(new Word("you")), false);
t.checkExpect(new Word("hey").hashCode(), s.hashCode());
//test for countWords and words
WordCounter wc = new WordCounter();
wc.countWords(new StringIterator(new StringBuffer("The Words Are")));
t.checkExpect(wc.words.get(0), new Word("the"));
t.checkExpect(wc.words(), 3);
// test for countWords and words and printWords
WordCounter macbeth = new WordCounter();
macbeth.countWords(new StringIterator("Macbeth.txt"));
macbeth.printWords(10);
t.checkExpect(macbeth.words(), 3198);
}
//test the Iterator
public void testStringIter(Tester t) {
StringIterator wrds = new StringIterator(
new StringBuffer("The Words Are"));
int i = 0;
for (Word w : wrds) {
System.out.println(" Word[" + (i++) + "] :" + w);
}
}
// sample ArrayLists of Integers and Strings
ArrayList<Integer> ilist;
ArrayList<String> slist;
// sample StringComparator
StringComparator scomp = new StringComparator();
// sample IntegerComparator
IntegerComparator icomp = new IntegerComparator();
// reset the data;
public void reset() {
ilist = new ArrayList<Integer> ( );
slist = new ArrayList<String> ( );
}
WordCounter ww = new WordCounter();
WordCounter mm = new WordCounter();
// initialize the data
public void initData() {
reset();
ww.sortedInsert(1, ilist, icomp);
ww.sortedInsert(2, ilist, icomp);
ww.sortedInsert(3, ilist, icomp);
ww.sortedInsert(1, ilist, icomp);
mm.sortedInsert("a", slist, scomp);
mm.sortedInsert("b", slist, scomp);
mm.sortedInsert("c", slist, scomp);
mm.sortedInsert("b", slist, scomp);
}
// intialize the data, unsorted
public void initDataUnsorted() {
reset();
ilist.add(3);
ilist.add(2);
ilist.add(4);
ilist.add(1);
slist.add("b");
slist.add("a");
slist.add("d");
slist.add("c");
ww.insertionSort(slist, scomp);
mm.insertionSort(ilist, icomp);
}
// test all the methods in this class
public void testAll(Tester t) {
// test the method sortedInsert indirectly
reset();
t.checkExpect(ilist.size(), 0);
initData();
t.checkExpect(ilist.size(), 4);
t.checkExpect(ilist.get(0), 1);
t.checkExpect(ilist.get(1), 1);
t.checkExpect(ilist.get(2), 2);
t.checkExpect(ilist.get(3), 3);
reset();
t.checkExpect(slist.size(), 0);
initData();
t.checkExpect(slist.size(), 4);
t.checkExpect(slist.get(0), "a");
t.checkExpect(slist.get(1), "b");
t.checkExpect(slist.get(2), "b");
t.checkExpect(slist.get(3), "c");
// test the method insertionSort indirectly
initDataUnsorted();
t.checkExpect(ilist.size(), 4);
t.checkExpect(ilist.get(0), 1);
t.checkExpect(ilist.get(1), 2);
t.checkExpect(ilist.get(2), 3);
t.checkExpect(ilist.get(3), 4);
t.checkExpect(slist.size(), 4);
t.checkExpect(slist.get(0), "a");
t.checkExpect(slist.get(1), "b");
t.checkExpect(slist.get(2), "c");
t.checkExpect(slist.get(3), "d");
}
}
|
/*******************************************************************************
* Copyright 2020 Grégoire Martinetti
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package org.gmart.devtools.java.serdes.codeGen.javaGen.model.classTypes.fields;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import org.gmart.base.data.structure.tuple.Pair;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.DeserialContext;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.TypeExpression;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.classTypes.AbstractClassDefinition;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.classTypes.AbstractClassDefinition.ReferenceCheckResult;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.containerTypes.AbstractContainerType;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.referenceResolution.AbstractAccessorBuilder;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.referenceResolution.ConstructionArgs;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.referenceResolution.TypeExpressionWithArgs;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.referenceResolution.runtime.DependentInstance;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.referenceResolution.runtime.DependentInstanceSource;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.serialization.SerializableObjectBuilder;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.serialization.SerializerProvider;
import org.gmart.devtools.java.serdes.codeGen.javaLang.JPoetUtil;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.MethodSpec.Builder;
import com.squareup.javapoet.TypeName;
public abstract class AbstractTypedField extends AbstractField {
public abstract TypeExpression getTypeExpression();
public abstract <T extends TypeExpression> void setTypeExpression(T typeExpression);
public AbstractTypedField(String name, boolean isOptional) {
super(name, isOptional);
}
private AbstractClassDefinition hostClassDef;
public AbstractClassDefinition getHostClassDef() {
return hostClassDef;
}
public void setHostClass(AbstractClassDefinition hostClassDef) {
this.hostClassDef = hostClassDef;
}
private boolean isDependent;
public boolean isDependent() {
return isDependent;
}
public void checkReferences_recursive(Object instance, Field javaField, ReferenceCheckResult referenceCheckResult) {
try {
getTypeExpression().checkReferences_recursive(javaField.get(instance), referenceCheckResult);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
//should not happened ...
}
}
List<AbstractAccessorBuilder> accessorBuilders;
public void initDependentField(TypeExpressionWithArgs constrArg) throws Exception {
this.isDependent = true;
if(constrArg != null)
this.accessorBuilders = ConstructionArgs.makeBuilders(getHostClassDef(), constrArg.getInstantiatedType(), constrArg.getPaths());
if(getTypeExpression() instanceof AbstractContainerType) {
((AbstractContainerType)getTypeExpression()).setIsDependent(true);
}
}
public Function<List<Object>, Optional<Object>> makeAccessor(DependentInstanceSource thisHostClassInstance, int argIndex) {
return accessorBuilders.get(argIndex).makeAccessor(thisHostClassInstance);
}
//private static String parentContextId = "parentContext";//InstanceContext parentContext
public MethodSpec.Builder toJPoetSetter(){
Builder jPoetSetter = super.toJPoetSetter();
if(isDependent())
jPoetSetter.addStatement("$L.$L(this)", getNameInCode(), DependentInstance.setParentContextId);
// jPoetSetter.addStatement("(($T)$L).$L(this)", DependentInstance.class, getNameInCode(), DependentInstance.setParentContextId);
return jPoetSetter;
}
public void initJavaObjectField(DeserialContext ctx, Class<?> newInstanceGeneratedClass, Object hostClassNewInstance, Object fieldYamlValue ) throws NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
if(fieldYamlValue == null) {
if(!isOptional())
ctx.getNonOptionalNotInitializedCollection().addNonOptionalFieldNonInitialized(this.getName());
//else nothing todo
} else {
Pair<Class<?>, Object> rez = getTypeExpression().yamlOrJsonToModelValue(ctx, fieldYamlValue, false);
//not necessary (the next setter "invoke" does that):
// if(this.isDependent()) {
// ((InstanceContext)rez.getValue1()).setParentContext(hostClassNewInstance);
// }
newInstanceGeneratedClass.getMethod(JPoetUtil.makeSetterName(this.getNameInCode()), rez.getValue0()).invoke(hostClassNewInstance, rez.getValue1());
}
}
public <T> void addPropertyToObjectSerializer(SerializerProvider<T> provider, SerializableObjectBuilder<T> builder, Class<?> generatedClass, Object toSerialize, List<String> nonOptionalNotInitializedCollection) {
if(this.isDiscriminant())
return;
try {
Class<?> toSerialize_Class = generatedClass;
Field field = toSerialize_Class.getDeclaredField(getNameInCode());
field.setAccessible(true);
Object childToSerialize = field.get(toSerialize);
if(childToSerialize == null) {
if(!isOptional())
nonOptionalNotInitializedCollection.add(this.getName());
else {/* nothing to do */}
} else {
builder.addProperty(getName(), getTypeExpression().makeSerializableValue(provider, childToSerialize));
}
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
public Object get(Object hostInstance) {
try {
Field declaredField = getHostClassDef().getGeneratedClass().getDeclaredField(this.getNameInCode());
declaredField.setAccessible(true);
return declaredField.get(hostInstance);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
e.printStackTrace();
return null;
}
}
@Override
public TypeName getReferenceJPoetType(boolean boxPrimitive){
return getTypeExpression().getReferenceJPoetTypeName(boxPrimitive);
}
public abstract boolean isAbstract();
private boolean isDiscriminant;
public boolean isDiscriminant() {
return isDiscriminant;
}
public void setIsDiscriminant(boolean isDiscriminant) {
this.isDiscriminant = isDiscriminant;
}
}
//public void appendKeyValueToYamlCode(SerialContext ctx, Class<?> generatedClass, Object toSerialize) {
// if(this.isDiscriminant())
// return;
// try {
// Class<?> toSerialize_Class = generatedClass;//((ClassDefinitionOwner)toSerialize).getClassDefinition().getGeneratedClass(); //toSerialize.getClass();
// Field field = toSerialize_Class.getDeclaredField(getNameInCode());
// field.setAccessible(true);
// Object childToSerialize = field.get(toSerialize);
// if(childToSerialize == null) {
// if(!isOptional())
// ctx.getNonOptionalNotInitializedCollection().addNonOptionalFieldNonInitialized(this.getName());
// //assert false: "A required field has not been filled:" + toString();
// else {/* nothing to do */}
// } else {
// appendYaml(ctx, getName(), getTypeExpression(), childToSerialize);
// }
// } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
// e.printStackTrace();
// }
//}
//public static void appendYaml(SerialContext bui, Object key, TypeExpression childType, Object childToSerialize) {
// bui.append(key.toString());
// bui.append(": ");
// bui.indent(() -> {
// Boolean instanceAsPropertyValueOnNewLine = childType.isInstanceAsPropertyValueOnNewLine_nullable(childToSerialize);
// if(instanceAsPropertyValueOnNewLine != null ? instanceAsPropertyValueOnNewLine : YAppender.isOnNewLineWhenPropertyValue(childToSerialize))
// bui.n();
// childType.appendInstanceToYamlCode(bui, childToSerialize);
// });
//}
//public interface YAppendableProperty {
// String getYAppendablePropertyKey();
// void appendPropertyValue();
// default void append(SerialContext bui) {
// bui.append(this.getYAppendablePropertyKey());
// bui.append(": ");
// bui.indent(()->{
// this.appendPropertyValue();
// });
// }
//} |
/**
* ファイル名 : ConfigurationApplication.java
* 作成者 : hung.pd
* 作成日時 : 2018/5/31
* Copyright © 2017-2018 TAU Corporation. All Rights Reserved.
*/
package jp.co.tau.web7.admin.supplier.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
/**
*
* <p>クラス名 : ConfigurationApplication</p>
* <p>説明 : Configuration Application</p>
* @author thien.nv
*/
@Configuration
@PropertySource(value = { "classpath:messages.properties", "classpath:header_csv.properties" }, encoding = "UTF-8")
public class ConfigurationApplication {
/**
*
* <p>説明 : Java8TimeDialect</p>
* @author thien.nv
* @return Java8TimeDialect
*/
@Bean
public Java8TimeDialect java8TimeDialect() {
return new Java8TimeDialect();
}
}
|
package com.tencent.mm.plugin.account.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.plugin.account.ui.LoginSmsUI.1;
class LoginSmsUI$1$2 implements OnClickListener {
final /* synthetic */ 1 eRW;
LoginSmsUI$1$2(1 1) {
this.eRW = 1;
}
public final void onClick(DialogInterface dialogInterface, int i) {
this.eRW.eRV.eRn.reset();
}
}
|
package com.corejava.java8;
public class Order
{
public Order(long orderId, double price, String status) {
super();
this.orderId = orderId;
this.price = price;
this.status = status;
}
private long orderId;
private double price;
private String status;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return "Order [orderId=" + orderId + ", price=" + price + ", status=" + status + "]\n";
}
} |
package br.edu.ifam.saf.api.dto;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class AluguelDTO {
private Integer id;
private UsuarioDTO cliente;
private UsuarioDTO funcionario;
private Date dataHoraRequisicao;
private List<ItemAluguelDTO> itens = new ArrayList<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public UsuarioDTO getCliente() {
return cliente;
}
public void setCliente(UsuarioDTO cliente) {
this.cliente = cliente;
}
public UsuarioDTO getFuncionario() {
return funcionario;
}
public void setFuncionario(UsuarioDTO funcionario) {
this.funcionario = funcionario;
}
public List<ItemAluguelDTO> getItens() {
return Collections.unmodifiableList(itens);
}
public void setItens(List<ItemAluguelDTO> itens) {
this.itens = itens;
}
public Double calcularValorTotal() {
double total = 0.0;
for (ItemAluguelDTO itemAluguel : itens) {
total += itemAluguel.calcularTotal();
}
return total;
}
public void adicionarItem(ItemAluguelDTO itemAluguelDTO) {
if (!itens.contains(itemAluguelDTO)) {
itens.add(itemAluguelDTO);
}
}
public void removerItem(ItemAluguelDTO itemAluguelDTO) {
itens.remove(itemAluguelDTO);
}
public Date getDataHoraRequisicao() {
return dataHoraRequisicao;
}
public void setDataHoraRequisicao(Date dataHoraRequisicao) {
this.dataHoraRequisicao = dataHoraRequisicao;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof AluguelDTO)) return false;
AluguelDTO that = (AluguelDTO) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (cliente != null ? !cliente.equals(that.cliente) : that.cliente != null) return false;
if (funcionario != null ? !funcionario.equals(that.funcionario) : that.funcionario != null)
return false;
return dataHoraRequisicao != null ? dataHoraRequisicao.equals(that.dataHoraRequisicao) : that.dataHoraRequisicao == null;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (cliente != null ? cliente.hashCode() : 0);
result = 31 * result + (funcionario != null ? funcionario.hashCode() : 0);
result = 31 * result + (dataHoraRequisicao != null ? dataHoraRequisicao.hashCode() : 0);
return result;
}
}
|
package Day03_variables;
public class println_vs_print {
//the only characters we can give for a name _and $
public static void main(String[] args) {
System.out.println("Hello World");// prints from a new line every time
System.out.println("School");// println- print the printing to the next line
//in java there is another print statement, print the printing next to each other
//printing takes place where it's left off(no shortcut)
System.out.println("+++++++++++++++++++");
System.out.print("Hello Cybertek");
System.out.print(" School");
System.out.println();
System.out.println("+++++++++++");
System.out.println("Today is");
System.out.print("great day");
System.out.println(" today");
}
}
|
package edu.bluejack19_2.chronotes.home.ui.notes;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Objects;
import edu.bluejack19_2.chronotes.R;
import edu.bluejack19_2.chronotes.controller.NoteController;
import edu.bluejack19_2.chronotes.controller.UserController;
import edu.bluejack19_2.chronotes.home.ui.notes.adapter.CollaboratorNotesAdapter;
import edu.bluejack19_2.chronotes.model.Note;
import edu.bluejack19_2.chronotes.model.User;
import edu.bluejack19_2.chronotes.utils.ProcessStatus;
public class NoteCollaborator extends DialogFragment {
private static final String FRAGMENT_TAG = "Note Collaborator";
private static final String INTENT_DATA = "note";
private RecyclerView recyclerView;
private CollaboratorNotesAdapter collaboratorNotesAdapter;
private UserController userController;
private NoteController noteController;
private Button closeButton;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_notes_collaborator, container);
setUIComponent(view);
closeButton.setOnClickListener(v -> closeDialog());
collaboratorNotesAdapter = new CollaboratorNotesAdapter(this.getActivity());
collaboratorNotesAdapter.setCollaborators(null);
collaboratorNotesAdapter.notifyDataSetChanged();
recyclerView.setAdapter(collaboratorNotesAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
noteController = NoteController.getInstance();
userController = UserController.getInstance();
loadData();
return view;
}
@Override
public void onStart() {
super.onStart();
Dialog dialog = getDialog();
if (dialog != null)
Objects.requireNonNull(Objects.requireNonNull(dialog).getWindow()).setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
private void setUIComponent(View view) {
recyclerView = view.findViewById(R.id.rv_notes_reminders);
closeButton = view.findViewById(R.id.button_notes_close);
}
private void loadData() {
String noteID = requireArguments().getString(INTENT_DATA);
noteController.getNotesByID((notes, processStatusNote) -> {
if (processStatusNote == ProcessStatus.FOUND) {
CollaboratorNotesAdapter.setNote(notes);
ArrayList<String> collaborators = notes.getUsers();
ArrayList<User> usersCollaborators = new ArrayList<>();
for (String c : Objects.requireNonNull(collaborators)) {
userController.getUserByID((user, processStatus) -> {
if (processStatus == ProcessStatus.FOUND){
usersCollaborators.add(user);
collaboratorNotesAdapter.setCollaborators(usersCollaborators);
collaboratorNotesAdapter.notifyDataSetChanged();
} else {
String message = getResources().getString(R.string.notes_message_collaborator_failed);
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
}, c);
}
}
}, noteID);
}
private void closeDialog() {
Fragment fragment = requireFragmentManager().findFragmentByTag(FRAGMENT_TAG);
if (fragment != null) {
DialogFragment df = (DialogFragment) fragment;
df.dismiss();
}
}
}
|
package com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import java.io.Serializable;
class n$b extends BroadcastReceiver implements Serializable {
final /* synthetic */ n nDS;
private n$b(n nVar) {
this.nDS = nVar;
}
/* synthetic */ n$b(n nVar, byte b) {
this(nVar);
}
public final void onReceive(Context context, Intent intent) {
if (intent != null) {
String action = intent.getAction();
Object schemeSpecificPart;
if ("android.intent.action.PACKAGE_ADDED".equals(action)) {
schemeSpecificPart = intent.getData().getSchemeSpecificPart();
if (!TextUtils.isEmpty(schemeSpecificPart) && schemeSpecificPart.equals(n.b(this.nDS).rU)) {
this.nDS.nDO.Dd(3);
}
} else if ("android.intent.action.PACKAGE_REMOVED".equals(action)) {
schemeSpecificPart = intent.getData().getSchemeSpecificPart();
if (!TextUtils.isEmpty(schemeSpecificPart) && schemeSpecificPart.equals(n.b(this.nDS).rU)) {
this.nDS.nDO.Dd(4);
}
}
}
}
}
|
package com.jdyx.app.usermanage;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@Slf4j
@MapperScan("com.jdyx.app.usermanage.mapper") //扫描所有mybatis的mapper接口文件
@SpringBootApplication
public class AppUserInfomanageApplication {
public static void main(String[] args) {
SpringApplication.run(AppUserInfomanageApplication.class, args);
// log.info(new String("测试Slf4j在控制台打印"));
}
}
|
package soft.chess.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JPanel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
public class JsonUtil{
private static final JsonConfig LENIENT_JSONCONFIG=new JsonConfig();
//字符串转对象
public static Object StrParseObject(String str,Class bean_class){
JSONObject getjson=JSONObject.fromObject(str);
return JSONObject.toBean(getjson, bean_class);
}
//字符串转map
public static Object StrParseMap(String str,Class bean_class,Map map){
JSONObject getjson=JSONObject.fromObject(str);
return JSONObject.toBean(getjson, bean_class,map);
}
//字符串转数组,使用泛型进行类型检查
public static <T>List<T> StrParseArray(String str,Class<T> claz){
//获取json对象数组
JSONArray arr=JSONArray.fromObject(str);
return (List<T>) JSONArray.toCollection(arr, claz);
}
//Json对象中的集合转指定集合
public static <T>List<T> JSONArrayParseObjectArray(List arr,Class<T> claz){
JSONArray jarr=JSONArray.fromObject(arr);
return (List<T>) JSONArray.toCollection(jarr, claz);
}
//对象转字符串
public static String ObjectToStr(Object entity){
JSONObject sendjson=JSONObject.fromObject(entity,LenientConfig());
return sendjson.toString();
}
//数组转字符串
public static <E>String ArrayToStr(List<E> list){
JSONArray json=JSONArray.fromObject(list,LenientConfig());
return json.toString();
}
//防止创建Json字符串时的递归调用死循环
public static final JsonConfig LenientConfig(){
LENIENT_JSONCONFIG.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
return LENIENT_JSONCONFIG;
}
}
|
package switch2019.project.controllerLayer.cli;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import switch2019.project.DTO.serializationDTO.GroupDTO;
import switch2019.project.applicationLayer.US004GetFamilyGroupsService;
import java.util.Set;
@Component
public class US004GetFamilyGroupsController {
@Autowired
private US004GetFamilyGroupsService service;
public Set<GroupDTO> getFamilyGroups() {
return service.getFamilyGroups();
}
}
|
package com.org.property.data.server.web;
import java.io.IOException;
import java.util.Vector;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ManagedAsync;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.org.property.data.server.utils.FutureUtils;
import com.org.property.data.server.utils.Json;
@Path("/")
@Singleton
public class Application extends javax.ws.rs.core.Application {
private static final String TARGET_URL = "http://webservice-takehome-1.spookle.xyz/";
private static final String PATH = "/properties";
private static final String PROPERTY = "property";
private static final String PROPERTY_ID = "property_id";
private final WebTarget upstream = ClientBuilder.newClient().target(TARGET_URL);
@Inject
private TaskExecutor executor;
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path(PATH)
@ManagedAsync
public void propertys(@Suspended final AsyncResponse asyncResponse, String requestBody) throws IOException {
JsonNode payload = Json.parse(requestBody);
Vector<CompletableFuture<Response>> upstreamRequests = new Vector<>();
if (!payload.isMissingNode()) {
for (JsonNode node : ((ArrayNode) payload)) {
if (node.isTextual()) {
WebTarget target = upstream.path(PROPERTY).queryParam(PROPERTY_ID, node.asText());
upstreamRequests.add(FutureUtils.toCompletable(target.request().async().get(), executor));
}
}
}
System.out.println("Total number of properties---->" + upstreamRequests.size());
CompletableFuture.allOf(upstreamRequests.toArray(new CompletableFuture[upstreamRequests.size()]))
.thenRunAsync(() -> {
asyncResponse.resume(
upstreamRequests.stream().map(new Function<CompletableFuture<Response>, JsonNode>() {
@Override
public JsonNode apply(CompletableFuture<Response> responseCf) {
try {
return Json.parse(responseCf.get().readEntity(String.class));
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return Json.MISSING_NODE;
}
}).max((leftValue, rightValue) -> {
return Integer.compare(leftValue.path("value").asInt(),
rightValue.path("value").asInt());
}).get().toString());
});
}
}
|
package tree;
public class LBTree<T> implements IBinaryTree<T>{
private IBNode<T> root;
public LBTree() {
}
@Override
public INode<T> root() {
return root;
}
@Override
public INode<T> parent(INode<T> n) {
IBNode<T> e = (IBNode<T>) n;
if(isRoot(e)) {
System.out.println("No parent!");
return null;
}
return e.getParent();
}
@Override
public IIterator<INode<T>> children(INode<T> n) {
return null;
}
@Override
public boolean isExternal(INode<T> n) {
IBNode<T> e = (IBNode<T>) n;
return (hasLeft(e)||hasRight(e));
}
@Override
public boolean isInternal(INode<T> n) {
return false;
}
@Override
public boolean isRoot(INode<T> n) {
IBNode<T> e = (IBNode<T>) n;
return e.getParent() != null;
}
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return root == null;
}
@Override
public IIterator<T> iterator() {
return null;
}
@Override
public IIterator<INode<T>> nodes() {
return null;
}
@Override
public T replace(INode<T> n, T e) {
return null;
}
@Override
public IBNode<T> left(IBNode<T> n) {
if(!hasLeft(n)) {
System.out.println("No left!");
return null;
}
return n.getLeftChild();
}
@Override
public IBNode<T> right(IBNode<T> n) {
if(!hasRight(n)) {
System.out.println("No right!");
return null;
}
return n.getRightChild();
}
@Override
public boolean hasLeft(IBNode<T> n) {
return n.getLeftChild() != null;
}
@Override
public boolean hasRight(IBNode<T> n) {
return n.getRightChild() != null;
}
@Override
public IBNode<T> addRoot(T e) throws Exception {
IBNode<T> n = new IBNode<T>(e);
if(isEmpty()) {
root = n;
return root;
}
else {
throw new Exception("The tree is not empty!");
}
}
@Override
public IBNode<T> insertLeft(IBNode<T> n, T e) throws Exception {
IBNode<T> newNode = new IBNode<T>(e);
if(hasLeft(n)) {
throw new Exception("It already has a left child");
}
n.setLeftChild(newNode);
newNode.setParent(n);
return newNode;
}
@Override
public IBNode<T> insertRight(IBNode<T> n, T e) throws Exception {
IBNode<T> newNode = new IBNode<T>(e);
if(hasRight(n)) {
throw new Exception("It already has a left child");
}
n.setRightChild(newNode);
newNode.setParent(n);
return newNode;
}
@Override
public IBNode<T> remove(IBNode<T> n) throws Exception {
return null;
}
@Override
public void attach(IBNode<T> n, IBinaryTree<T> t1, IBinaryTree<T> t2) throws Exception {
}
}
|
package com.axicik;
import java.math.BigInteger;
import java.sql.*;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonBuilderFactory;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import org.json.*;
/**
* Η κλάση DBManager είναι μια βοηθητική κλάση για τα web services που κάνει αυθεντικοποίηση του χρήστη
* και περιέχει όλες τις μεθόδους που καλούνται απο τα Web Services.
* Επιτρέπετε μόνο ένα αντικείμενο της κλάσης και οι εξωτερικές κλάσεις μπορούν να το χρησιμοποιούν
* καλόντας την static μέθοδο getInstance.
*
* @author Ioulios Tsiko: cs131027
* @author Theofilos Axiotis: cs131011
*/
public class DBManager {
SessionIdentifierGenerator si=new SessionIdentifierGenerator();
String myDatabase="jdbc:mysql://localhost:3306/dikt?user=dikt&password=dikt";
Connection myConnection;
Statement myStatement;
Statement myStatement2;
static DBManager Inst=null;
/**
* Δημιουρεί αντεικήμενο της κλάσης DBManager
* και αρχικοποιεί την κλάση com.mysql.jdbc.Driver
* @throws ClassNotFoundException
* @throws SQLException
*/
private DBManager() throws ClassNotFoundException, SQLException {
deleteKeys();
Class.forName("com.mysql.jdbc.Driver");
}
/**
* Επιστρέφει το αντικείμενο της DBManager, αν δεν υπάρχει το δημιουργεί.
* @return Επιστρέφει το αντικείμενο της DBManager.
* @throws ClassNotFoundException
* @throws SQLException
*/
public static DBManager getInstance() throws ClassNotFoundException, SQLException
{
if (Inst == null)
Inst = new DBManager();
return Inst;
}
/**
* Επιστρέφει τον ρόλο του χρήστη που το Όνομα Χρηστη δίνετε σαν όρισμα.
* @param username Όνομα χρήστη
* @return Ένα String με τον ρόλο του χρήστη.
* @throws SQLException
*/
public String getRole(String username) throws SQLException
{
String res="test";
String result="nulls";
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
//Πέρνει τον κωδικό του ρόλου απο την βάση.
String sql1="select roles_FK from Users where cred_FK='"+username+"'";
ResultSet rs2=myStatement.executeQuery(sql1);
while(rs2.next()){
result=rs2.getString("roles_FK");
}
//Περνει το όνομα του ρόλου.
String sql="select R_name from Roles where R_id='"+result+"'";
ResultSet rs = myStatement.executeQuery(sql);
while(rs.next()){
res=rs.getString("R_name");
}
myStatement.close();
myConnection.close();
return res;
}
/**
* dexetai username/roleName(Admin/Secretary/Student)
* kai afou ektelesei to sqlQuery epistrefei ta services(onomata)
* pou antistoixoun ston sugkekrimeno xristi
* @param username
* @param roleName
* @return
* @throws SQLException
*/
public String getServices(String username,String roleName) throws SQLException{
ArrayList <String> myList=new ArrayList<String>();
String test = null;
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
// εκτελείτε το sql query και επιστρεφει τα ονόματα των services.
String mysql="select S_name from Services where S_id in (select Services_FK from JNCT_Roles_Services,Roles where Roles_FK=Roles.R_id and R_name='"+roleName+"')";
ResultSet rs2=myStatement.executeQuery(mysql);
while(rs2.next()){
myList.add(rs2.getString("S_name"));
}
myStatement.close();
myConnection.close();
return myList.toString();
}
/**
* Κάνει την σύνδεση του χρήστη και δημιουργεί το κλειδί τις συνεδρίας του αν ο Χρήστης υπάρχει.
* @param n1 Όνομα Χρήστη
* @param n2 Κωδικός Χρήστη
* @return String - Κλειδί Χρηστη η "0".
* @throws ClassNotFoundException
* @throws SQLException
*/
public String login(String n1,String n2,String n3) throws ClassNotFoundException, SQLException{
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
String user=n1 ;
String pass=n2 ;
String logedfrom=n3;
int flag1=0;
String sql;
//Ελέγχει αν ο χρήστης υπάρχει και αν έχει δώσει σωστό κωδικό.
sql = "SELECT * FROM Credentials";
ResultSet rs = myStatement.executeQuery(sql);
try{
while(rs.next()){
if(user.equals(rs.getString("Username")) && pass.equals(rs.getString("Password"))){
flag1=1;
}
}
}
catch(SQLException exception1){
flag1=0;
}
//Αν ο χρήστης υπάρχει δημιουργεί κλειδι, το εισάγει στον πίνακα LoginKeys και το επιστρέφει
//Αλλιώς επιστρέφει "0".
if (flag1==1)
{
String key=si.nextSessionId();
String sqlString = "insert into LoginKeys(User_fk,Login_Key,logedfrom)"
+ " values('"+user+"','"+key+"','"+logedfrom+"')";
myStatement.executeUpdate(sqlString);
myStatement.close();
myConnection.close();
return key;
}
else
{
myStatement.close();
myConnection.close();
return "0";
}
}
/**
* Κάνει την αποσύνδεση του χρήστη και διαγράφει το κλειδί τις συνεδρίας του.
* @param n1 Όνομα Χρήστη
* @param n2 Κωδικός Χρήστη
* @return String - Κλειδί Χρηστη η "0".
* @throws ClassNotFoundException
* @throws SQLException
*/
public void logout (String usr,String key) throws SQLException
{
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
//Διαγράφει το κλειδί της συνεδρίας απο την βάση.
String sql;
sql = "DELETE FROM LoginKeys WHERE LoginKeys.User_FK = '"+usr+"'";
myStatement.executeUpdate(sql);
myStatement.close();
myConnection.close();
}
/**
* Ελέγχει αν ο χρήστης είναι συνδεδεμένος και δημιουργεί ένα αντικείμενο User.
* Αν ο χρήστης υπάρχει το αντικείμενο της κλάσης User θα περιέχει στοιχεία του,
* αλλιώς Θα έχει μονο ενα flag UsrExist=false;
* @param username Όνομα Χρήστη
* @param key Κωδικός Χρήστη
* @return Επιστρέφει ένα αντικείμενο User
* @throws SQLException
*/
public User checkKey (String username,String key) throws SQLException
{
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
//Ψάχνει το κλειδί στην βάση.Αν υπάρχει φτιάχνει ένα αντικείμενο User
//με τα στοιχεία του χρήστη και το επιστρέφει
//Αλλιώς ενα κένο User.
String sql;
sql = "SELECT * FROM LoginKeys where Login_Key = '"+key+"'"
+ "AND User_FK ='"+username+"'";
ResultSet rs = myStatement.executeQuery(sql);
if(rs.next())
{
if(rs.getString("Login_Key").equals(key) && rs.getString("User_FK").equals(username))
{
String sqlString = "UPDATE LoginKeys SET timestamp = CURRENT_TIMESTAMP "
+ "WHERE Login_Key = '"+key+"'";
myStatement.executeUpdate(sqlString);
User u=getUser(username);
System.out.println("class user test ---- >"+u.getName()+" "+u.getLast_name());
return u;
}
}
myStatement.close();
myConnection.close();
return new User(false);
}
/**
* Δημιουργεί ένα αντικείμενο User που περιέχει στοιχεία του χρήστη, που δίνετε
* παραμετρικάμ, και τα δικαιώματα του.
* @param username Όνομα Χρήστη
* @return ένα αντικείμενο User.
* @throws SQLException
*/
public User getUser(String username) throws SQLException
{
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
String sql;
//Πέρνει τα δεδομένα του χρήστη απο την βάση.
sql = "SELECT * FROM Users where Cred_FK='"+username+"'";
ResultSet rs = myStatement.executeQuery(sql);
User usr=new User();
int role=0;
//Εισάγει τις τιμές απο την βάση στο αντικείμενο User.
if(rs.next())
{
if(rs.getString("Cred_FK").equals(username))
{
usr.setName(rs.getString("name"));
usr.setLast_name(rs.getString("last_name"));
usr.setUsername(username);
role=rs.getInt("roles_FK");
usr.setRole(role);
usr.setUsrExist(true);
}
}
//Πέρνει τους κωδικούς των webservice, που έχει δικαίωμα να καλέσει ο χρήστης, απο την βάση.
sql = "SELECT * FROM JNCT_Roles_Services where Roles_FK='"+role+"'";
rs = myStatement.executeQuery(sql);
//Εισάγει τους κωδικούς στο αντικείμενο User.
while(rs.next())
{
if(rs.getInt("Roles_FK")==role)
{
usr.srvList.add(rs.getInt("Services_FK"));
}
}
myStatement.close();
myConnection.close();
return usr;
}
/**
* Πέρνει τα στοιχεία του φοιτητή, τα μαθήματα του και τους βαθμούς απο την βάση,
* Τα εισάγει σε ένα αντίκείμενο json και τα μετατρέπει σε String και τα επιστρέφει.
* @param usr Όνομα Χρήστη προς αναζήτηση.
* @return ένα String που περιέχει τα στοιχεία σε μορφη json array.
* Σε περίπτωση σφάλματος ένα μήνυμα που αναφέρει τι πήγε στραβά.
*
* Μορφή json :
* { "PersonalInfo":
* { "name": Ονομα χρήστη,
* "last_name": Επίθετο χρήστη,
* "phone": αριθμός τηλεφόνου,
* "username": Όνομα Χρήστη,
* "registrationNumber": Αριθμό μητρόου,
* "email": email,
* "role": κωδικός ρόλου
* },
* "lessons":
* [{ "name": Ονομα μαθήματος,
* "lessid": κωδικός μαθήματος,
* "grade": βαθμός},
* ... ,
* { "name": Ονομα μαθήματος,
* "lessid": κωδικός μαθήματος,
* "grade": βαθμός}
* ]
* }
*
* @throws SQLException
*/
public String getStudInfo(String usr) throws SQLException
{
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
String sql;
JsonObject myJson;
int id=2;
String grade;
//Αρχικοποιεί το json.
JsonBuilderFactory factory=Json.createBuilderFactory(null);
JsonObjectBuilder jsonB = factory.createObjectBuilder()
.addNull("Initializer");
JsonArrayBuilder jsonA = factory.createArrayBuilder();
//Πέρνει τα δεδομένα του χρήστη απο την βάση.
sql = "SELECT * FROM Users where Cred_FK='"+usr+"'";
ResultSet rs = myStatement.executeQuery(sql);
//Εισάγει τις τιμές απο την βάση στο αντικείμενο Json.
if(rs.next())
{
if(rs.getString("Cred_FK").equals(usr))
{
String role=rs.getString("roles_FK");
//Αν ο χρήστης προς αναζήτηση δεν είναι φοιτιτής κάνει return "Student Doesn't Exists"
if(!role.equals("3"))
{
myStatement.close();
myConnection.close();
return "Student Doesn't Exists";
}
jsonB= jsonB.add("PersonnalInfo", factory.createObjectBuilder()
.add("name", rs.getString("name"))
.add("last_name", rs.getString("last_name"))
.add("email", rs.getString("email"))
.add("phone", rs.getString("phone"))
.add("registrationNumber", rs.getString("RegistrationNo"))
.add("role",role)
.add("username",rs.getString("Cred_FK")));
id=rs.getInt("RegistrationNo");
}
}
else //Αν το rs είναι κενό δεν υπαρχεί ο χρηστης οποτε επιστρέφει καταληλο μήνυμα.
{
myStatement.close();
myConnection.close();
return "Student Doesn't Exists";
}
//Αν ο χρηστης υπάρχει εξάγει απο την βάση τα μαθήματα του και τους βαθμούς του και τα βάζει στο json.
sql = "SELECT * FROM JNCT_Students_Lessons,Lessons WHERE stud_FK='"+id+"' AND les_fk=LessonID";
rs = myStatement.executeQuery(sql);
while(rs.next())
{
if(rs.getString("LessonID")!=null)
{
if (rs.getString("grade")==null)
grade="-";
else
grade=rs.getString("grade");
jsonA= jsonA.add(factory.createObjectBuilder()
.add("name", rs.getString("name"))
.add("lessid", rs.getString("LessonID"))
.add("grade", grade));
}
}
jsonB= jsonB.add("Grades", jsonA);
myJson=jsonB.build();
myStatement.close();
myConnection.close();
return myJson.toString();
}
/**
* Επιστρέφει τα στοιχεία του μαθήματος με κωδικό lessID που δίνετε παραμετρικά.
*
* @param lesID Κωδικός μαθήματος
* @return ένα String που περιέχει τα στοιχεία του μαθήματος σε μορφη json.
* Σε περίπτωση σφάλματος ένα μήνυμα που αναφέρει τι πήγε στραβά
* Μορφή json :
* { "lesson":
* { "name": Ονομα μαθήματος,
* "semester": αριθμός εξαμήνου,
* "lessid": κωδικός μαθήματος,
* "description": περιγραφή
* }
* }
* @throws SQLException
*/
public String getLesson(String lesID) throws SQLException
{
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
String sql;
// Πέρνει τα δεδομένα του μαθήματος απο την βάση.
sql = "SELECT * FROM Lessons WHERE LessonID='"+lesID+"'";
ResultSet rs = myStatement.executeQuery(sql);
//Αρχικοποιεί το json.
JsonBuilderFactory factory=Json.createBuilderFactory(null);
JsonObjectBuilder jsonB = factory.createObjectBuilder()
.addNull("Initializer");
//Αν το μάθημα υπάρχει εισάγει τις τιμές απο την βάση στο αντικείμενο Json και το επιστρέφει.
if(rs.next())
{
if(rs.getString("LessonID").equals(lesID))
{
jsonB= jsonB.add("lesson",factory.createObjectBuilder()
.add("name", rs.getString("Name"))
.add("lessid", rs.getString("LessonID"))
.add("semester", rs.getString("Semester"))
.add("description", rs.getString("Description")));
myStatement.close();
myConnection.close();
return jsonB.build().toString();
}
}
//Αν το μάθημα δεν υπάρχει επιστρέφει ενα String.
myStatement.close();
myConnection.close();
return "Lesson doesn't exist";
}
/**
* Επιστρέφει όλα τα μαθήματα ή μόνο τα μαθήματα ενός φοιτητή.
* @param usr Όνομα χρήστη προς αναζήτηση "0" για όλα τα μαθήματα.
* @return ένα String που περιέχει τα μαθήματα σε μορφη json array. Σε περίπτωση σφάλματος ένα μήνυμα που αναφέρει τι πήγε στραβά.
* Μορφή json :
* { "lessons":
* [{ "name": Ονομα μαθήματος,
* "lessid": κωδικός μαθήματος},
* ... ,
* { "name": Ονομα μαθήματος,
* "lessid": κωδικός μαθήματος}
* ]
* }
* @throws SQLException
*/
public String getLessons(String usr) throws SQLException
{
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
String sql;
//Αν το usr είναι "0" επιστρέφει όλα τα μαθήματα.
//Αλλιώς μονο τα μαθήματα που έχει ο χρήστης usr.
if(usr.equals("0"))
sql = "SELECT * FROM Lessons";
else
sql = "SELECT * FROM Lessons,JNCT_Students_Lessons where Les_FK=LessonID AND Stud_FK='"+usr+"' ";
ResultSet rs = myStatement.executeQuery(sql);
//Αρχικοποιεί το json.
JsonBuilderFactory factory=Json.createBuilderFactory(null);
JsonObjectBuilder jsonB = factory.createObjectBuilder()
.addNull("Initializer");
JsonArrayBuilder jsonA = factory.createArrayBuilder();
while(rs.next())
{
if(rs.getString("LessonID")!=null)
jsonA= jsonA.add(factory.createObjectBuilder()
.add("name", rs.getString("Name"))
.add("lessid", rs.getString("LessonID")));
}
jsonB= jsonB.add("lessons", jsonA);
myStatement.close();
myConnection.close();
return jsonB.build().toString();
}
/**
* Προσθέτει έναν νέο φοιτητή στην βάση δεδομένων.
* @param json Json Κώδικας με τα στοιχεία του φοιτητή
* μορφή json:
* { "student":
* { "name": Ονομα Φοιτητή,
* "last_name": Επίθετο Φοιτητή,
* "phone": "αριθμός τηλεφόνου",
* "username": "Αριθμό μητρόου",
* "password": "Κωδικός"
* }
* }
* @return String - "User Added Successfully"
* @throws SQLException
*/
public String addStudent(String json) throws SQLException
{
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
JSONObject js=new JSONObject(json);
String name =js.getJSONObject("student").getString("name");
String last_name =js.getJSONObject("student").getString("last_name");
String phone =js.getJSONObject("student").getString("phone");
String regNum =js.getJSONObject("student").getString("username");
String pass =js.getJSONObject("student").getString("password");
String username="cs"+regNum;
String email = username+"@teiath.gr";
String sqlString = "insert into Credentials(username,password)"
+ " values('"+username+"','"+pass+"')";
myStatement.executeUpdate(sqlString);
sqlString = "insert into Users(name,RegistrationNo,last_name,roles_FK,cred_FK,email,phone)"
+ " values('"+name+"','"+regNum+"','"+last_name+"',3,'"+username+"','"+email+"','"+phone+"')";
myStatement.executeUpdate(sqlString);
myStatement.close();
myConnection.close();
return "User Added Successfully";
}
/**
* Προσθέτει έναν νέο χρήστη(Διαχειριστή η Γραμματέα) στην βάση δεδομένων.
* @param json Json Κώδικας με τα στοιχεία του νέου χρήστη
* Μορφή json:
* { "student":
* { "name": Ονομα χρήστη,
* "last_name": Επίθετο χρήστη,
* "phone": αριθμός τηλεφόνου,
* "username": Αριθμό μητρόου,
* "password": Κωδικός,
* "role": κωδικός ρόλου
* }
* }
* @return String - "User Added Successfully"
* @throws SQLException
*/
public String addUser(String json) throws SQLException
{
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
JSONObject js=new JSONObject(json);
String name =js.getJSONObject("student").getString("name");
String last_name =js.getJSONObject("student").getString("last_name");
String role =js.getJSONObject("student").getString("role");
String phone =js.getJSONObject("student").getString("phone");
String regNum =js.getJSONObject("student").getString("username");
String pass =js.getJSONObject("student").getString("password");
String username="cs"+regNum;
String email = username+"@teiath.gr";
String sqlString = "insert into Credentials(username,password)"
+ " values('"+username+"','"+pass+"')";
myStatement.executeUpdate(sqlString);
sqlString = "insert into Users(name,RegistrationNo,last_name,roles_FK,cred_FK,email,phone)"
+ " values('"+name+"','"+regNum+"','"+last_name+"','"+role+"','"+username+"','"+email+"','"+phone+"')";
myStatement.executeUpdate(sqlString);
myStatement.close();
myConnection.close();
return "User Added Successfully";
}
/**
* Προσθέτει η αλλάζει τον βαθμό σε έναν ή περισότερουw φοιτητές.
* @param str Κώδικας με τα στοιχεία του νέου χρήστη
* Μορφή json:
* { "lessonID": κωδικός μαθήματος,
* "Grades":
* [{ "am": Αριθμός μητρώου ,
* "grade": βαθμός},
* ... ,
* { "am": Αριθμός μητρώου,
* "grade": βαθμός}
* ]
* }
* @return String - "Grades Added Successfully"
* @throws SQLException
*/
public String putGrades(String str) throws SQLException
{
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
JSONObject userJson=new JSONObject(str);
JSONArray gradesJson=userJson.getJSONArray("Grades");
String lessID=userJson.getString("lessonID");
for (int i=0;i<gradesJson.length();i++)
{
int am=gradesJson.getJSONObject(i).getInt("am");
double grade=gradesJson.getJSONObject(i).getDouble("grade");
String sqlString = "UPDATE JNCT_Students_Lessons SET Grade = '"+grade+"' "
+ "WHERE JNCT_Students_Lessons.Stud_FK = '"+am+"' "
+ "AND JNCT_Students_Lessons.Les_FK = '"+lessID+"'";
myStatement.executeUpdate(sqlString);
}
myStatement.close();
myConnection.close();
return "Grades Added Successfully";
}
/**
* Προσθέτει νέα μαθήματα που επέλεξε ο φοιτητης στα μαθήματα του,
* και αρχικοποιεί τον βαθμό με "-".
* @param jsonA
* @param usr
* @throws SQLException
*/
public void putClasses(String jsonA,String usr) throws SQLException
{
myConnection = DriverManager.getConnection(myDatabase);
myStatement = myConnection.createStatement();
JSONArray json=new JSONArray(jsonA);
String usr2=usr.substring(2,8);
for (int i=0;i<json.length();i++)
{
String lessid=json.getJSONObject(i).getString("lessid");
//Αν το το κύριο κλειδί υπάρχει είδη(δηλαδη το μάθημα υπάρχει) το κάνει update χωρίς να αλλακσει τον βαθμό.
String sqlString = "INSERT INTO `JNCT_Students_Lessons` (`Stud_FK`, `Les_FK`, `Grade`)"
+ " VALUES ('"+usr2+"', '"+lessid+"', NULL)\n"
+"ON DUPLICATE KEY UPDATE Grade=Grade;";
myStatement.executeUpdate(sqlString);
}
myStatement.close();
myConnection.close();
}
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void deleteKeys() throws SQLException,ClassNotFoundException {
final Runnable keyCleaner = new Runnable() {
public void run()
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
System.out.println("driver exeption");
}
String sql;
Timestamp date;
Calendar dt=Calendar.getInstance();
System.out.println("timer test ----> beep ");
dt.add(Calendar.MINUTE, -10);
Calendar dt2=Calendar.getInstance();
try {
String myDatabase="jdbc:mysql://localhost:3306/dikt?user=dikt&password=dikt";
Connection myConnection1 = DriverManager.getConnection(myDatabase);
Statement myStatement1 = myConnection1.createStatement();
sql = "SELECT * FROM LoginKeys";
ResultSet rs = myStatement1.executeQuery(sql);
while(rs.next())
{
if(rs.getString("logedfrom").equals("1"))
{
date=rs.getTimestamp("TimeStamp");
System.out.println("time test ---> "+date.toString());
dt2.setTime(date);
if(dt.after(dt2))
{
sql = "Delete FROM LoginKeys Where Login_Key='"+rs.getString("Login_Key")+"'";
myStatement1.executeUpdate(sql);
}
else
System.out.println("timer test ----> to kleidi yparxei");
}
}
myStatement1.close();
myConnection1.close();
} catch (SQLException ex) {
System.out.println("den uparxoun kleidia apo web efarmogh");
}
}
};
final ScheduledFuture<?> keyCleanerHandle =
scheduler.scheduleAtFixedRate(keyCleaner, 60*2, 60*2, SECONDS);
/*
scheduler.schedule(new Runnable() {
public void run() { System.out.println("scheduler test ----> beep"); keyCleanerHandle.cancel(true); }
}, 60, SECONDS);
*/
}
}
/**
* Περιέχει μια μέθοδο που δειμιουργεί τυχαίους κλειδαρίθμους.
* @author ioulios
*/
final class SessionIdentifierGenerator {
private SecureRandom random = new SecureRandom();
public String nextSessionId() {
return new BigInteger(130, random).toString(32);
}
} |
package edu.hust.se.seckill.service;
import edu.hust.se.seckill.domain.MiaoshaOrder;
import edu.hust.se.seckill.domain.MiaoshaUser;
import edu.hust.se.seckill.domain.OrderInfo;
import edu.hust.se.seckill.vo.GoodsVo;
public interface OrderService {
MiaoshaOrder getMiaoshaOrderByUserIdGoodsId(Long id, long goodsId);
OrderInfo createOrder(MiaoshaUser user, GoodsVo goods);
OrderInfo getOrderById(long orderId);
}
|
package TangramCore;
public class Point2D extends java.awt.geom.Point2D.Double {
static final long serialVersionUID = 24362462L;
public Point2D() {
super();
}
public Point2D(double x, double y){
super(x, y);
}
public Point2D(Point2D p){
this(p.x, p.y);
}
public void copyFrom(Point2D p){
setLocation(p);
}
public void translate(double dx, double dy){
setLocation(x + dx, y + dy);
}
public void translate(Point2D p){
setLocation(x + p.x, y + p.y);
}
public void rotate(double px, double py, double a){
double dx = x - px;
double dy = y - py;
double cosa = Math.cos(a);
double sina = Math.sin(a);
setLocation(dx * cosa - dy * sina + px, dx * sina + dy * cosa + py);
}
public void rotate(Point2D p, double a){
rotate(p.x, p.y, a);
}
public void rotate(double a){
rotate(0, 0, a);
}
}
|
/*
* UniTime 3.2 - 3.5 (University Timetabling Application)
* Copyright (C) 2008 - 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.unitime.commons.web.WebTable;
import org.unitime.timetable.security.SessionContext;
import org.unitime.timetable.security.rights.Right;
import org.unitime.timetable.util.ExportUtils;
import org.unitime.timetable.webutil.PdfWebTable;
import org.unitime.timetable.webutil.TimetableManagerBuilder;
/**
* MyEclipse Struts
* Creation date: 04-11-2005
*
* XDoclet definition:
* @struts:action
* @struts:action-forward name="success" path="schedDeputyListTile" redirect="true"
* @struts:action-forward name="fail" path="/error.jsp" redirect="true"
*
* @author Tomas Muller
*/
@Service("/timetableManagerList")
public class TimetableManagerListAction extends Action {
@Autowired SessionContext sessionContext;
// --------------------------------------------------------- Instance Variables
// --------------------------------------------------------- Methods
/**
* Reads list of schedule deputies and assistants and displays them in the form of a HTML table
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
String errM = "";
// Check permissions
sessionContext.checkPermission(Right.TimetableManagers);
WebTable.setOrder(sessionContext,"timetableManagerList.ord",request.getParameter("order"),1);
PdfWebTable table = new TimetableManagerBuilder().getManagersTable(sessionContext,true);
int order = WebTable.getOrder(sessionContext,"timetableManagerList.ord");
String tblData = (order>=1?table.printTable(order):table.printTable());
if ("Export PDF".equals(request.getParameter("op"))) {
ExportUtils.exportPDF(
new TimetableManagerBuilder().getManagersTable(sessionContext,false),
order, response, "managers");
return null;
}
request.setAttribute("schedDeputyList", errM + tblData);
return mapping.findForward("success");
}
}
|
package cn.com.custom.widgetproject.activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import cn.com.custom.widgetproject.R;
import cn.com.custom.widgetproject.constant.Constant;
/**
* 关于画面
* Created by custom on 2016/6/14.
*/
public class AboutActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
findViewById(R.id.rl_pingjia).setOnClickListener(this);
findViewById(R.id.rl_fankui).setOnClickListener(this);
findViewById(R.id.about_rl_back).setOnClickListener(this);
findViewById(R.id.about_iv_back).setOnClickListener(this);
TextView verson = (TextView) findViewById(R.id.verson);
try {
verson.setText("应用版本:" + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
Intent intent = new Intent(this, WebViewActivity.class);
switch (v.getId()) {
//跳往评价
case R.id.rl_pingjia:
intent.putExtra(Constant.WEB_URL, "http://www.custom.com.cn/");
startActivity(intent);
break;
//跳往邮件,等待详细设计完善
case R.id.rl_fankui:
//Todo 填写邮箱
mailContact("");
break;
case R.id.about_iv_back:
case R.id.about_rl_back:
finish();
break;
default:
break;
}
}
/**
* 打开邮箱应用发送邮件
*
* @param mailAdress
*/
public void mailContact(String mailAdress) {
Uri uri = Uri.parse("mailto:" + mailAdress);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra(Intent.EXTRA_SUBJECT, "请填写主题"); // 主题
intent.putExtra(Intent.EXTRA_TEXT, "请填写你的建议或意见"); // 正文
startActivity(Intent.createChooser(intent, "请选择邮件类应用"));
}
} |
package com.nxtlife.mgs.service;
import java.util.List;
import com.nxtlife.mgs.entity.user.User;
import com.nxtlife.mgs.view.Mail;
import com.nxtlife.mgs.view.MailRequest;
import com.nxtlife.mgs.view.PasswordRequest;
import com.nxtlife.mgs.view.SuccessResponse;
import com.nxtlife.mgs.view.user.UserRequest;
import com.nxtlife.mgs.view.user.UserResponse;
import com.sun.mail.smtp.SMTPSendFailedException;
public interface UserService {
UserResponse getLoggedInUserResponse();
void sendLoginCredentialsByGmailApi(MailRequest request);
Boolean sendLoginCredentialsBySMTP(Mail request) throws SMTPSendFailedException;
SuccessResponse changePassword(PasswordRequest request);
SuccessResponse forgotPassword(String username);
Mail usernamePasswordSendContentBuilder(String username, String password, String mailFrom, String mailTo);
// User createUserForEntity(Object entity);
User createUser(String name, String contactNumber, String email, Long schoolId);
UserResponse save(UserRequest request);
List<UserResponse> findAll();
UserResponse findById(String id);
UserResponse findByAuthentication();
UserResponse update(String userId, UserRequest request);
SuccessResponse matchGeneratedPassword(String username, String generatedPassword);
SuccessResponse changePasswordByGeneratedPassword(PasswordRequest request);
SuccessResponse activate(String id);
SuccessResponse delete(String id);
List<UserResponse> findAllByRoleId(Long roleId);
}
|
package com.tencent.mm.ui.chatting;
public class ChattingSendDataToDeviceUI$c {
String bKv;
String bLU;
String bLZ;
String daA;
String deviceID;
String iconUrl;
int progress;
final /* synthetic */ ChattingSendDataToDeviceUI tLG;
String tLS;
public ChattingSendDataToDeviceUI$c(ChattingSendDataToDeviceUI chattingSendDataToDeviceUI) {
this.tLG = chattingSendDataToDeviceUI;
}
}
|
package org.zxd.spring.boot.config;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import lombok.Data;
@Component
/**
* 导入自定义配置文件,如果指定的配置项在主配置文件中存在,则主配置属性的优先级高。
*/
@PropertySource(value = { "classpath:complex.properties" })
@ConfigurationProperties(prefix = "complex")
@Data
public class ComplexProperties {
private String author;
private Integer age;
private Date birth;
private Boolean sex;
private List<String> hobbies;
private Map<String, Object> extend;
private RemoteServer remoteServer;
@Data
public static class RemoteServer {
private String host;
private Integer port;
}
}
|
package com.taocoder.contentproviderdemo.data;
import androidx.room.RoomDatabase;
import com.taocoder.contentproviderdemo.models.User;
@androidx.room.Database(entities = {User.class}, version = 1)
public abstract class Database extends RoomDatabase {
public abstract UserDao userDao();
public static final String DB_NAME = "providerdemo.db";
} |
package com.screens;
// LibGDX imports
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
// Class imports
import com.kroy.Kroy;
import com.miniGame.MiniGameScreen;
/**
* Displays the main menu screen with selection buttons.
*
* @author Archie
* @author Josh
* @since 23/11/2019
*/
public class MainMenuScreen extends BasicScreen {
protected Texture texture;
/**
* The constructor for the main menu screen. All game logic for the main
* menu screen is contained.
*
* @param game The game object.
*/
public MainMenuScreen(final Kroy game) {
super(game);
}
/**
* Create the button stage.
*/
@Override
public void show() {
// Allow stage to control screen inputs.
Gdx.input.setInputProcessor(stage);
// Create table to arrange buttons.
final Table buttonTable = new Table();
buttonTable.setFillParent(true);
buttonTable.center();
// Create buttons
final TextButton playButton = new TextButton("Play", skin);
final TextButton tutorialButton = new TextButton("Tutorial", skin);
final TextButton leaderboardButton = new TextButton("Leaderboard", skin);
final TextButton storylineButton = new TextButton("Story Line", skin);
final TextButton quitButton = new TextButton("Quit", skin);
final TextButton miniGameButton = new TextButton("MiniGame", skin);
// Increase size of text
playButton.setTransform(true);
playButton.scaleBy(0.25f);
tutorialButton.setTransform(true);
tutorialButton.scaleBy(0.25f);
leaderboardButton.setTransform(true);
leaderboardButton.scaleBy(0.25f);
storylineButton.setTransform(true);
storylineButton.scaleBy(0.25f);
quitButton.setTransform(true);
quitButton.scaleBy(0.25f);
miniGameButton.setTransform(true);
miniGameButton.scaleBy(0.25f);
// Add listeners
playButton.addListener(new ClickListener(){
@Override
//transition to game screen
public void clicked(final InputEvent event, final float x, final float y){
game.setScreen(new GameScreen(game));
dispose();
}
});
tutorialButton.addListener(new ClickListener(){
@Override
//transition to tutorial screen
public void clicked(final InputEvent event, final float x, final float y){
game.setScreen(new TutorialScreen(game));
dispose();
}
});
leaderboardButton.addListener(new ClickListener() {
@Override
public void clicked(final InputEvent event, final float x, final float y) {
game.setScreen(new LeaderboardScreen(game));
dispose();
}
});
storylineButton.addListener(new ClickListener(){
@Override
//transition to storyline screen
public void clicked(final InputEvent event, final float x, final float y){
game.setScreen(new StoryLineScreen(game));
dispose();
}
});
quitButton.addListener(new ClickListener() {
@Override
public void clicked(final InputEvent event, final float x, final float y) {
Gdx.app.exit();
}
});
miniGameButton.addListener(new ClickListener() {
@Override
public void clicked(final InputEvent event, final float x, final float y) {
game.setScreen(new MiniGameScreen (game, new GameScreen(game), 1));
}
});
// Add buttons to table and style them
buttonTable.add(playButton).padBottom(40).padRight(40).width(150).height(40);
buttonTable.row();
buttonTable.add(storylineButton).padBottom(40).padRight(40).width(150).height(40);
buttonTable.row();
buttonTable.add(leaderboardButton).padBottom(40).padRight(40).width(150).height(40);
buttonTable.row();
buttonTable.add(tutorialButton).padBottom(40).padRight(40).width(150).height(40);
buttonTable.row();
buttonTable.add(miniGameButton).padBottom(40).padRight(40).width(150).height(40);
buttonTable.row();
buttonTable.add(quitButton).padBottom(40).padRight(40).width(150).height(40);
// Add table to stage
stage.addActor(buttonTable);
}
}
|
package com.rsm.yuri.projecttaxilivredriver.main;
import android.util.Log;
import com.rsm.yuri.projecttaxilivredriver.historicchatslist.entities.Car;
import com.rsm.yuri.projecttaxilivredriver.historicchatslist.entities.Driver;
import com.rsm.yuri.projecttaxilivredriver.historicchatslist.entities.User;
import com.rsm.yuri.projecttaxilivredriver.lib.base.EventBus;
import com.rsm.yuri.projecttaxilivredriver.main.events.MainEvent;
import com.rsm.yuri.projecttaxilivredriver.main.ui.MainView;
import org.greenrobot.eventbus.Subscribe;
/**
* Created by yuri_ on 15/01/2018.
*/
public class MainPresenterImpl implements MainPresenter {
EventBus eventBus;
MainView mainView;
MainInteractor mainInteractor;
SessionInteractor sessionInteractor;
public MainPresenterImpl(EventBus eventBus, MainView mainView, MainInteractor mainInteractor, SessionInteractor sessionInteractor) {
this.eventBus = eventBus;
this.mainView = mainView;
this.mainInteractor = mainInteractor;
this.sessionInteractor = sessionInteractor;
}
@Override
public void onCreate() {
eventBus.register(this);
}
@Override
public void changeToOnlineStatus() {
sessionInteractor.changeConnectionStatus(User.ONLINE);
}
@Override
public void changeToOfflineStatus() {
sessionInteractor.changeConnectionStatus(User.OFFLINE);
}
@Override
public void startWaitingTravel() {
mainInteractor.changeWaitingTravelStatus(Driver.WAITING_TRAVEL);
}
@Override
public void stopWaitingTravel() {
mainInteractor.changeWaitingTravelStatus(Driver.ONLINE);
}
@Override
public void startInTravelStatus(){
mainInteractor.changeWaitingTravelStatus(Driver.IN_TRAVEL);
}
@Override
public void uploadCompletedTravelStatus(){
mainInteractor.uploadCompletedTravelStatus(Driver.ONLINE);
}
@Override
public void onDestroy() {
mainView = null;
eventBus.unregister(this);
//mainInteractor.destroyDriversListListener();//essa função vai ser implementada por mapfragment
}
@Override
@Subscribe
public void onEventMainThread(MainEvent event) {
switch (event.getEventType()) {
case MainEvent.onSuccessToRecoverSession:
onSuccessToRecoverSession(event.getLoggedUser());
break;
case MainEvent.onFailedToRecoverSession:
//Log.d("d", "onEventMainThread:onFailedToRecoverSession " );
onFailedToRecoverSession();
break;
case MainEvent.onSuccessToRecoverMyCar:
onSuccessToRecoverMyCar(event.getMyCar());
break;
case MainEvent.onFailedToRecoverMyCar:
onFailedToRecoverMyCar(event.getErrorMessage());
break;
case MainEvent.onSucceessToSaveFirebaseTokenInServer:
onSuccessToSaveFirebaseTokenInServer();
break;
case MainEvent.onFailedToSaveFirebaseTokenInServer:
onFailedToSaveFirebaseTokenInServer(event.getErrorMessage());
break;
}
}
private void onSuccessToRecoverSession(Driver loggedUser) {
if (mainView != null) {
mainView.setLoggedUser(loggedUser);
mainView.setUIVisibility(true);
}
}
private void onFailedToRecoverSession() {
if (mainView != null) {
//Log.d("d", "onFailedToRecoverSession() " );
mainView.navigateToLoginScreen();
}
}
private void onSuccessToRecoverMyCar(Car myCar) {
if (mainView != null) {
mainView.setMyCar(myCar);
}
}
private void onFailedToRecoverMyCar(String errorMessage) {
if (mainView != null) {
mainView.onFailedToRecoverMyCar(errorMessage);
}
}
private void onSuccessToSaveFirebaseTokenInServer(){
mainView.onSucceessToSaveFirebaseTokenInServer();
}
private void onFailedToSaveFirebaseTokenInServer(String errorMessage){
mainView.onFailedToSaveFirebaseTokenInServer(errorMessage);
}
@Override
public void logout() {
sessionInteractor.changeConnectionStatus(User.OFFLINE);
sessionInteractor.logout();
}
@Override
public void checkForSession() {
sessionInteractor.checkForSession();
}
@Override
public void getMyCar() {
mainInteractor.getMyCar();
}
/*@Override
public void sendFirebaseNotificationTokenToServer(String firebaseNotificationToken) {
mainInteractor.sendFirebaseNotificationTokenToServer(firebaseNotificationToken);
}*/
@Override
public void verifyToken() {
mainInteractor.verifyToken();
}
}
|
package com.tencent.mm.plugin.appbrand.config;
public interface AppBrandGlobalSystemConfig$a {
public static final int[] fqa = new int[0];
public static final String[] fqb = new String[]{"https://wx.qlogo.cn/"};
}
|
package byow.Core;
import java.util.Random;
public class Room {
public static final int MIN_SIZE = 5;
public static final int MAX_SIZE = 8;
private int xPos;
private int yPos;
private int width;
private int height;
private Random random;
private Hallway incidentHallway;
/**
* Construct a room just by the given random seed.
*/
public Room(Random random) {
this.random = random;
this.xPos = RandomUtils.uniform(this.random, Engine.WIDTH - Room.MAX_SIZE);
this.yPos = RandomUtils.uniform(this.random, Engine.HEIGHT - Room.MAX_SIZE);
this.width = RandomUtils.uniform(this.random, Room.MIN_SIZE, Room.MAX_SIZE);
this.height = RandomUtils.uniform(this.random, Room.MIN_SIZE, Room.MAX_SIZE);
}
/**
* Construct a room at the end of the hallway.
* if there are enough space.
*/
public Room(Hallway hallway, Random random) {
this.random = random;
this.incidentHallway = hallway;
this.generatePosition(hallway);
}
/**
* Generate the position of a room and it's size.
*/
private void generatePosition(Hallway hallway) {
int wid = RandomUtils.uniform(this.random, Room.MIN_SIZE, Room.MAX_SIZE);
int hei = RandomUtils.uniform(this.random, Room.MIN_SIZE, Room.MAX_SIZE);
switch (hallway.getDirection()) {
case North:
hei = Math.min(hei, Engine.HEIGHT - hallway.getEndYPos() - 1);
if (hei >= Room.MIN_SIZE) {
this.setSize(hei, wid);
this.yPos = hallway.getEndYPos() + 1;
this.setXPos(hallway.getStartXPos(), this.getWidth());
} else {
this.clear();
}
break;
case South:
hei = Math.min(hei, hallway.getEndYPos());
if (hei >= Room.MIN_SIZE) {
this.setSize(hei, wid);
this.yPos = hallway.getEndYPos() - this.getHeight();
this.setXPos(hallway.getStartXPos(), this.getWidth());
} else {
this.clear();
}
break;
case East:
wid = Math.min(wid, Engine.WIDTH - hallway.getEndXPos() - 1);
if (wid >= Room.MIN_SIZE) {
this.setSize(hei, wid);
this.xPos = hallway.getEndXPos() + 1;
this.setYPos(hallway.getStartYPos(), this.getHeight());
} else {
this.clear();
}
break;
case West:
wid = Math.min(wid, hallway.getEndXPos());
if (wid >= Room.MIN_SIZE) {
this.setSize(hei, wid);
this.xPos = hallway.getEndXPos() - this.getWidth();
this.setYPos(hallway.getStartYPos(), this.getHeight());
} else {
this.clear();
}
break;
default:
this.clear();
}
}
private void setYPos(int x, int y) {
int alignTo = RandomUtils.uniform(this.random, y - 3);
int yPosition = x - alignTo;
if (yPosition >= 0) {
this.yPos = yPosition;
} else {
this.yPos = 0;
}
}
private void setXPos(int x, int y) {
int alignTo = RandomUtils.uniform(this.random, y - 3);
int xPosition = x - alignTo;
if (xPosition >= 0) {
this.xPos = xPosition;
} else {
this.xPos = 0;
}
}
private void setSize(int hei, int wid) {
this.height = hei;
this.width = wid;
}
private void clear() {
this.width = 0;
this.height = 0;
this.xPos = 0;
this.yPos = 0;
}
public int getXPos() {
return this.xPos;
}
public int getYPos() {
return this.yPos;
}
public int getWidth() {
return this.width;
}
public int getHeight() {
return this.height;
}
public Hallway getIncidentHallway() {
return this.incidentHallway;
}
}
|
package com.isslam.kidsquran;
import com.isslam.kidsquran.controllers.SharedPreferencesManager;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Content extends FragmentActivity {
Context context;
private void playSounds(int position) {
MediaManager mediaManager = MediaManager.getInstance(this);
mediaManager.setContext(this);
mediaManager.playSounds(position, 1);
}
Handler handler;
Runnable runnable;
Animation anim2;
ImageView img_header_bg;
RelativeLayout main_layout;
TextView txt_theker;
@TargetApi(16)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.content_ly);
context = this;
main_layout = (RelativeLayout) findViewById(R.id.main_layout);
// txt_theker = (TextView) findViewById(R.id.txt_theker);
// txt_theker.setVisibility(View.GONE);
String fontPath = "fonts/aref_light.ttf";// kufyan.otf
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
txt_theker.setTypeface(tf);
// txt_theker.setText(athkar_titles);
// txt_theker.setShadowLayer(30, 0, 0, Color.BLACK);
anim2 = AnimationUtils.loadAnimation(this, R.anim.popup_show);
img_header_bg = (ImageView) findViewById(R.id.img_header_bg);
anim2.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation arg0) {
}
@Override
public void onAnimationRepeat(Animation arg0) {
}
@Override
public void onAnimationEnd(Animation arg0) {
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
txt_theker.setVisibility(View.VISIBLE);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(
matrix);
main_layout.getBackground().setColorFilter(filter);
}
});
img_header_bg.setVisibility(View.INVISIBLE);
String image = "img_bg_" + MyPagerAdapter.lastPage;
Context _context = main_layout.getContext();
int id = _context.getResources().getIdentifier(image, "drawable",
_context.getPackageName());
Drawable background = getResources().getDrawable(id);
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
main_layout.setBackgroundDrawable(background);
} else {
main_layout.setBackground(background);
}
if (handler == null)
handler = new Handler();
if (runnable != null)
handler.removeCallbacks(runnable);
runnable = new Runnable() {
@Override
public void run() {
playSounds(MyPagerAdapter.lastPage);
img_header_bg.startAnimation(anim2);
img_header_bg.setVisibility(View.VISIBLE);
}
};
handler.postDelayed(runnable, 600);
final FloatingActionButton btn_share = (FloatingActionButton) findViewById(R.id.btn_share);
btn_share.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
String shareBody = "" + "\n" + getString(R.string.share_extra)
+ "\n"
+ "http://play.google.com/store/apps/details?id="
+ context.getPackageName();
sendIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, ""));
}
});
}
@Override
public void onBackPressed() {
GotoHome();
}
private void GotoHome() {
MediaManager mediaManager = MediaManager.getInstance(this);
mediaManager.setContext(this);
mediaManager.StopSounds();
if (main_layout != null)
main_layout.getBackground().clearColorFilter();
txt_theker.setVisibility(View.GONE);
anim2 = AnimationUtils.loadAnimation(Content.this, R.anim.popup_hide);
anim2.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation arg0) {
}
@Override
public void onAnimationRepeat(Animation arg0) {
}
@Override
public void onAnimationEnd(Animation arg0) {
img_header_bg.setVisibility(View.GONE);
finish();
}
});
img_header_bg.startAnimation(anim2);
img_header_bg.setVisibility(View.VISIBLE);
}
}
|
package com.tencent.mm.plugin.appbrand.widget.input;
import android.text.SpanWatcher;
import android.text.Spannable;
import com.tencent.mm.sdk.platformtools.x;
class x$2 implements SpanWatcher {
final /* synthetic */ x gIT;
x$2(x xVar) {
this.gIT = xVar;
}
public final void onSpanAdded(Spannable spannable, Object obj, int i, int i2) {
if (af.bt(obj)) {
x.d("MicroMsg.EditTextComposingTextDismissedObserver", "[bindInput] onSpanAdded %s, %s", new Object[]{spannable, obj.getClass().getSimpleName()});
}
}
public final void onSpanRemoved(Spannable spannable, Object obj, int i, int i2) {
if (af.bt(obj)) {
x.d("MicroMsg.EditTextComposingTextDismissedObserver", "[bindInput] onSpanRemoved %s, %s", new Object[]{spannable, obj.getClass().getSimpleName()});
this.gIT.guJ.removeCallbacks(this.gIT.gIS);
this.gIT.guJ.postDelayed(this.gIT.gIS, 100);
}
}
public final void onSpanChanged(Spannable spannable, Object obj, int i, int i2, int i3, int i4) {
if (af.bt(obj)) {
x.d("MicroMsg.EditTextComposingTextDismissedObserver", "[bindInput] onSpanChanged %s, %s", new Object[]{spannable, obj.getClass().getSimpleName()});
}
}
}
|
package com.example.tris_meneghetti;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class Design extends View {
private boolean drawXAnimation = false;
private boolean drawYAnimation = false;
private boolean clear = false;
private int endX = 0;
private int endY = 0;
private int angle = 0;
private Paint paintX = new Paint(Paint.ANTI_ALIAS_FLAG) {
{
setDither(true);
setColor(Color.rgb(84, 185, 255));
setStrokeWidth(60);
setStyle(Paint.Style.STROKE);
setStrokeCap(Cap.ROUND);
}
};
private Paint paintO = new Paint(Paint.ANTI_ALIAS_FLAG) {
{
setDither(true);
setColor(Color.rgb(255, 128, 128));
setStrokeWidth(40);
setStyle(Paint.Style.STROKE);
setStrokeCap(Cap.ROUND);
}
};
private Paint paintXWhite = new Paint(Paint.ANTI_ALIAS_FLAG) {
{
setDither(true);
setColor(Color.parseColor("#2A2A2A"));
setStrokeWidth(40);
setStyle(Paint.Style.STROKE);
setStrokeCap(Cap.ROUND);
}
};
public Design(Context context, AttributeSet attrs) {
super(context, attrs);
setClickable(true);
}
public Design(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setClickable(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// CANCELLA TUTTE LE "X" E "O"
if (clear) {
canvas.drawLine(getWidth() / 2, getWidth() / 2, endX + 30, endY + 30, paintXWhite);
if (endX < getWidth() - 110 && endY < getWidth() - 110) {
endY += 5;
endX += 5;
postInvalidateDelayed(5);
} else {
clear = false;
return;
}
}
// DISEGNA UNA "X"
if (drawXAnimation) {
canvas.drawLine(getWidth() / 2, getWidth() / 2, endX + 30, endY + 30, paintX);
canvas.drawLine(getWidth() / 2, getWidth() / 2, getWidth() - 30 - endX, endY + 30, paintX);
canvas.drawLine(getWidth() / 2, getWidth() / 2, endX + 30, getWidth() - 30 - endX, paintX);
canvas.drawLine(getWidth() / 2, getWidth() / 2, getWidth() - 30 - endX, getWidth() - 30 - endX, paintX);
if (endX < getWidth() - 110 && endY < getWidth() - 110) {
endY += 7;
endX += 7;
postInvalidateDelayed(2);
} else {
drawXAnimation = false;
}
}
// DISEGNA UNA "O"
if (drawYAnimation) {
canvas.drawCircle(getWidth() / 2, getHeight() / 2, angle, paintO);
if (angle < getWidth() / 2 - 60) {
angle += 8;
postInvalidateDelayed(3);
} else {
drawYAnimation = false;
}
}
}
public void nuovaPartita() {
clear = true;
invalidate();
}
public void drawX() {
endX = 0;
endY = 0;
drawXAnimation = true;
invalidate();
}
public void drawO() {
angle = 0;
drawYAnimation = true;
invalidate();
}
} |
/** ****************************************************************************
* Copyright (c) The Spray Project.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Spray Dev Team - initial API and implementation
**************************************************************************** */
package org.eclipselabs.spray.runtime.graphiti.features.custom;
import org.eclipse.graphiti.features.IFeatureProvider;
import org.eclipse.graphiti.features.IUpdateFeature;
import org.eclipse.graphiti.features.context.ICustomContext;
import org.eclipse.graphiti.features.context.impl.UpdateContext;
import org.eclipse.graphiti.mm.pictograms.ContainerShape;
import org.eclipse.graphiti.mm.pictograms.PictogramElement;
import org.eclipse.graphiti.mm.pictograms.Shape;
import org.eclipselabs.spray.runtime.graphiti.features.AbstractCustomFeature;
/**
* Updates a pictogram element and all its children.
*
* @author Karsten Thoms (karsten.thoms@itemis.de)
*/
public class UpdateElementsFeature extends AbstractCustomFeature {
public UpdateElementsFeature(IFeatureProvider fp) {
super(fp);
}
@Override
public boolean canExecute(ICustomContext context) {
return true;
}
@Override
public void execute(ICustomContext context) {
if (context.getPictogramElements().length > 0) {
for (PictogramElement pe : context.getPictogramElements())
update(context, pe);
}
}
protected void update(ICustomContext context, PictogramElement pe) {
if (pe instanceof ContainerShape) {
final ContainerShape container = (ContainerShape) pe;
for (Shape child : container.getChildren()) {
update(context, child);
}
}
UpdateContext ctx = new UpdateContext(pe);
IUpdateFeature updateFeature = getFeatureProvider().getUpdateFeature(ctx);
if (updateFeature != null && updateFeature.canUpdate(ctx)) {
updateFeature.update(ctx);
}
}
@Override
public String getName() {
return "Update all elements";
}
}
|
package chapter10.Exercise10_24;
public class Exercise10_24 {
public static void main(String[] args) {
MyCharacter character = new MyCharacter('A');
System.out.println(character.isDigit());
System.out.println(MyCharacter.isDigit('5'));
System.out.println(MyCharacter.isLowerCase(character.charValue()));
System.out.println(MyCharacter.toLowerCase(character.charValue()));
}
}
|
package com.drzewo97.ballotbox.core.model.vote;
import com.drzewo97.ballotbox.core.model.candidate.Candidate;
import com.drzewo97.ballotbox.core.model.poll.Poll;
import javax.persistence.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
@Entity
public class Vote implements IVote {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
private Poll poll;
@OneToMany(mappedBy = "vote", cascade = CascadeType.PERSIST)
private Set<VoteInfo> choices;
public Vote() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Poll getPoll() {
return poll;
}
public void setPoll(Poll poll) {
this.poll = poll;
}
public Set<VoteInfo> getChoices() {
return choices;
}
public void setChoices(Set<VoteInfo> choices) {
this.choices = choices;
}
@Override
public Candidate getMostPreferredCandidate() {
return Collections.min(choices, Comparator.comparing(VoteInfo::getPreferenceNumber)).getCandidate();
}
}
|
package com.rofour.baseball.controller.store;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rofour.baseball.common.JsonUtils;
import com.rofour.baseball.controller.base.BaseController;
import com.rofour.baseball.controller.model.ResultInfo;
import com.rofour.baseball.controller.model.SelectModel;
import com.rofour.baseball.controller.model.store.AxpStoreInfo;
import com.rofour.baseball.controller.model.store.CustomAxpInfo;
import com.rofour.baseball.controller.model.store.CustomStoreInfo;
import com.rofour.baseball.controller.model.store.DelInfo;
import com.rofour.baseball.controller.model.store.ExpStoreInfo;
import com.rofour.baseball.controller.model.store.SearchStoreInfo;
import com.rofour.baseball.controller.model.store.SimpleStoreInfo;
import com.rofour.baseball.controller.model.store.StoreInfo;
import com.rofour.baseball.service.store.StoreService;
/**
* @author WJ
* @author Kevin Zou (zouyong@shzhiduan.com)
*/
@Controller
@RequestMapping(value = "/store/exp", method = RequestMethod.POST)
public class StoreController extends BaseController {
private static final Logger LOG = LoggerFactory.getLogger(StoreController.class);
@Autowired
private StoreService storeService;
@ResponseBody
@RequestMapping("/add")
public ResultInfo add(HttpServletRequest req) {
String data = req.getParameter("data");
LOG.info("开始添加商户信息[data:" + data + "]");
StoreInfo store;
try {
store = JsonUtils.readValue(data, StoreInfo.class);
} catch (Exception e) {
LOG.error("解析商户信息失败");
return new ResultInfo(-1, "1030010001", "读取json参数失败");
}
ResultInfo result;
try {
storeService.add(store);
result = new ResultInfo();
} catch (Exception e) {
LOG.error("添加商户信息失败", e);
result = new ResultInfo(-1, "1030010002", "操作失败");
}
return result;
}
@ResponseBody
@RequestMapping("/delbatch")
public ResultInfo delbatch(HttpServletRequest req) {
String data = req.getParameter("data");
LOG.info("开始批量删除商户信息[data:" + data + "]");
List<Integer> ids = new ArrayList<Integer>();
try {
DelInfo delInfo = JsonUtils.readValue(data, DelInfo.class);
ids = delInfo.getIds();
} catch (Exception e) {
LOG.error("解析商户信息失败");
return new ResultInfo(-1, "1030010001", "读取json参数失败");
}
int num = 0;
try {
if (storeService.existCoo(ids) > 0) {
return new ResultInfo(-1, "", "请解除与COO的挂靠关系后再尝试删除");
}
if (storeService.getStoreUser(ids) > ids.size()) {
return new ResultInfo(-1, "", "站点下不止一个用户不能删除");
}
num = storeService.removeByIds(ids, req);
} catch (Exception e) {
LOG.error("删除商户信息失败", e);
return new ResultInfo(-1, "1030010002", "操作失败");
}
if (num == 0) {
LOG.info("没有此条商户信息");
return new ResultInfo(0, "1030010004", "没有此条记录");
}
LOG.info("删除商户信息成功");
return new ResultInfo(0, "", "OK");
}
@ResponseBody
@RequestMapping("/del")
public ResultInfo del(HttpServletRequest req) {
String data = req.getParameter("data");
LOG.info("开始删除商户信息[data:" + data + "]");
String id;
try {
id = JsonUtils.readValueByName(data, "id");
} catch (Exception e) {
LOG.error("解析商户信息失败");
return new ResultInfo(-1, "1030010001", "读取json参数失败");
}
if (id == null || !id.matches("^\\d+$")) {
LOG.error("传入参数错误");
return new ResultInfo(-1, "1030010003", "传入参数错误");
}
int num = 0;
try {
num = storeService.removeById(Long.valueOf(id));
} catch (Exception e) {
LOG.error("删除商户信息失败", e);
return new ResultInfo(-1, "1030010002", "操作失败");
}
if (num == 0) {
LOG.info("没有此条商户信息");
return new ResultInfo(0, "1030010004", "没有此条记录");
}
LOG.info("删除商户信息成功");
return new ResultInfo(0, "", "OK");
}
@ResponseBody
@RequestMapping("/update")
public ResultInfo update(HttpServletRequest req) {
String data = req.getParameter("data");
LOG.info("开始更新商户信息[data:" + data + "]");
StoreInfo store;
try {
store = JsonUtils.readValue(data, StoreInfo.class);
} catch (Exception e) {
LOG.error("解析商户信息失败");
return new ResultInfo(-1, "1030010001", "读取json参数失败");
}
ResultInfo result;
try {
storeService.update(store);
result = new ResultInfo();
} catch (Exception e) {
LOG.error("更新商户信息失败", e);
result = new ResultInfo(-1, "1030010002", "操作失败");
}
return result;
}
@ResponseBody
@RequestMapping("/getbycollegeid")
public ResultInfo queryByCollegeId(HttpServletRequest req) {
String data = req.getParameter("data");
LOG.info("开始查询商户信息[data:" + data + "]");
String collegeId;
try {
collegeId = JsonUtils.readValueByName(data, "collegeId");
} catch (Exception e) {
return new ResultInfo(-1, "1030010001", "读取json参数失败");
}
if (collegeId == null || !collegeId.matches("^\\d+$")) {
LOG.error("传入参数错误");
return new ResultInfo(-1, "1030010003", "传入参数错误");
}
List<SimpleStoreInfo> list = null;
try {
list = storeService.queryByCollegeId(Long.valueOf(collegeId));
} catch (Exception e) {
LOG.error("查询商户信息失败", e);
return new ResultInfo(-1, "1030010002", "操作失败");
}
LOG.info("查询商户成功");
if (list != null && list.isEmpty()) {
return new ResultInfo(0, "1030010004", "没有此条记录", list);
} else {
return new ResultInfo(0, "", "查询成功", list);
}
}
@ResponseBody
@RequestMapping("/querysite")
public ResultInfo querySite(HttpServletRequest req) {
String data = req.getParameter("data");
LOG.info("开始查询商户信息[data:" + data + "]");
String id;
try {
id = JsonUtils.readValueByName(data, "id");
} catch (Exception e) {
LOG.error("解析参数失败");
return new ResultInfo(-1, "1030010001", "读取json参数失败");
}
if (id == null || !id.matches("^\\d+$")) {
LOG.error("传入参数错误");
return new ResultInfo(-1, "1030010003", "传入参数错误");
}
CustomStoreInfo result = null;
try {
result = storeService.querySiteById(Long.valueOf(id));
if (result == null) {
return new ResultInfo(-1, "1030010004", "没有此条记录");
}
} catch (Exception e) {
LOG.error("查询商户信息失败", e);
return new ResultInfo(-1, "1030010002", "操作失败");
}
LOG.info("查询商户信息成功");
return new ResultInfo(0, "", "查询成功", result);
}
/**
* 按手机号码查询商户信息
*
* @param request
* @return
*/
@ResponseBody
@RequestMapping("/querybyphone")
public ResultInfo selectStoreInfoByPhone(HttpServletRequest request) {
try {
String data = request.getParameter("data");
if (StringUtils.isBlank(data)) {
return new ResultInfo(-1, "1030010003", "参数错误");
}
String phone = JsonUtils.readValueByName(data, "phone");
if (StringUtils.isBlank(phone)) {
return new ResultInfo(-1, "1030010003", "参数错误");
}
SearchStoreInfo result = storeService.selectStoreByPhone(phone);
if (result == null) {
return new ResultInfo(-1, "1030010004", "没有此条记录");
}
return new ResultInfo(0, "", "", result);
} catch (JsonParseException e) {
LOG.error("解析参数异常:", e);
return new ResultInfo(-1, "1030010001", "解析json参数失败");
} catch (JsonMappingException e) {
LOG.error("解析参数异常:", e);
return new ResultInfo(-1, "1030010001", "解析json参数失败");
} catch (Exception e) {
LOG.error("运单查询异常:", e);
return new ResultInfo(-1, "1030010002", "查询失败");
}
}
@ResponseBody
@RequestMapping("/allstoreinfo")
public ResultInfo selectAxpStoreInfo(HttpServletRequest request) {
try {
List<AxpStoreInfo> infoList = storeService.selectAxpStoreInfo();
if (infoList == null || infoList.isEmpty()) {
return new ResultInfo(-1, "1030010004", "没有此条记录");
}
return new ResultInfo(0, "", "", infoList);
} catch (Exception e) {
LOG.error("获取信息异常", e);
return new ResultInfo(-1, "1030010002", "查询失败");
}
}
@ResponseBody
@RequestMapping("/expstoreinfo")
public void selectExpStoreInfo(HttpServletRequest request, HttpServletResponse response) {
try {
List<ExpStoreInfo> infoList = storeService.selectExpStoreInfo();
List<SelectModel> sellist = new ArrayList<>();
SelectModel sel = new SelectModel();
sel.setId(" ");
sel.setText("请选择");
sellist.add(sel);
for (ExpStoreInfo expStoreInfo : infoList) {
SelectModel selectModel = new SelectModel();
selectModel.setId(expStoreInfo.getStoreId().toString());
selectModel.setText(expStoreInfo.getStoreName());
sellist.add(selectModel);
}
writeJson(sellist, response);
} catch (Exception e) {
LOG.error("获取信息异常", e);
}
}
@ResponseBody
@RequestMapping("/storecodeinfo")
public void selectStoreCodeInfo(HttpServletRequest request, HttpServletResponse response) {
try {
List<ExpStoreInfo> infoList = storeService.selectExpStoreInfo();
List<SelectModel> sellist = new ArrayList<>();
SelectModel sel = new SelectModel();
sel.setId(" ");
sel.setText("请选择");
sellist.add(sel);
for (ExpStoreInfo expStoreInfo : infoList) {
SelectModel selectModel = new SelectModel();
selectModel.setId(expStoreInfo.getStoreId().toString());
selectModel.setText(expStoreInfo.getStoreCode());
sellist.add(selectModel);
}
writeJson(sellist, response);
} catch (Exception e) {
LOG.error("获取信息异常", e);
}
}
@RequestMapping(value = "/postExpInfoList")
@ResponseBody
public List<ExpStoreInfo> postExpInfoList(HttpServletRequest request) {
if (request.getSession().getAttribute("user") != null) {
String storeName = request.getParameter("storeName") == null ? "" : request.getParameter("storeName");
String expressCompanyId = request.getParameter("expressCompanyId") == null ? ""
: request.getParameter("expressCompanyId");
String phone = request.getParameter("phone") == null ? "" : request.getParameter("phone");
HashMap<String, Object> map = new HashMap<>();
map.put("storeName", storeName);
map.put("expressCompanyId", expressCompanyId);
map.put("phone", phone);
List<ExpStoreInfo> infoList = storeService.selectExpStoreInfo(map);
return infoList;
} else {
return null;
}
}
@ResponseBody
@RequestMapping("/addaxpinfo")
public ResultInfo addAxpInfo(HttpServletRequest request) {
String data = request.getParameter("data");
LOG.info("开始添加门店信息[data:" + data + "]");
CustomAxpInfo axpInfo;
try {
axpInfo = JsonUtils.readValue(data, CustomAxpInfo.class);
long id = storeService.addAxpInfo(axpInfo);
return new ResultInfo();
} catch (Exception e) {
LOG.error("增加门店异常", e);
return new ResultInfo(-1, "1030010002", "操作失败");
}
}
@ResponseBody
@RequestMapping("/delaxpinfo")
public ResultInfo delAxpInfo(HttpServletRequest request) {
String data = request.getParameter("data");
LOG.info("开始删除门店信息[data:" + data + "]");
try {
String id = JsonUtils.readValueByName(data, "id");
storeService.delete(Long.parseLong(id));
return new ResultInfo();
} catch (Exception e) {
LOG.error("删除门店异常", e);
return new ResultInfo(-1, "1030010002", "操作失败");
}
}
@ResponseBody
@RequestMapping("/updateaxpinfo")
public ResultInfo updateAxpInfo(HttpServletRequest request) {
String data = request.getParameter("data");
LOG.info("开始更新门店信息[data:" + data + "]");
CustomAxpInfo axpInfo;
try {
axpInfo = JsonUtils.readValue(data, CustomAxpInfo.class);
storeService.updateAxpInfo(axpInfo);
return new ResultInfo();
} catch (Exception e) {
LOG.error("更新门店异常", e);
return new ResultInfo(-1, "1030010002", "操作失败");
}
}
@ResponseBody
@RequestMapping("/addexpinfo")
public ResultInfo addExpInfo(HttpServletRequest request) {
String data = request.getParameter("data");
LOG.info("开始添加快递站点信息[data:" + data + "]");
ExpStoreInfo store;
try {
store = JsonUtils.readValue(data, ExpStoreInfo.class);
return storeService.addExpInfo(store, request);
} catch (Exception e) {
LOG.error("增加快递站点异常", e);
return new ResultInfo(-1, "1030010002", "操作失败");
}
}
@ResponseBody
@RequestMapping("/updateexpinfo")
public ResultInfo updateExpInfo(HttpServletRequest request) {
String data = request.getParameter("data");
LOG.info("开始更新快递站点信息[data:" + data + "]");
ExpStoreInfo store;
try {
store = JsonUtils.readValue(data, ExpStoreInfo.class);
return storeService.updateExpInfo(store, request);
} catch (Exception e) {
LOG.error("更新快递站点信息异常", e);
return new ResultInfo(-1, "1030010002", "操作失败");
}
}
/**
* @param @param request
* @param @return 参数
* @return ResultInfo 返回类型
* @throws @author heyi
* @Method: batchCheckPacketMode
* @Description: 开关众包模式
* @date 2016年6月3日 下午3:08:18
*/
@ResponseBody
@RequestMapping("/checkpacketmode")
public ResultInfo batchCheckPacketMode(HttpServletRequest request) {
try {
String ids = request.getParameter("ids");
String mgrMode = request.getParameter("mgrMode");
String sendMode = request.getParameter("sendMode");
LOG.info("开始更改众包模式[data:{" + ids + "," + mgrMode + "," + sendMode + "]");
HashMap<String, Object> map = new HashMap<String, Object>();
String[] array = ids.split("\\,");
map.put("ids", array);
map.put("mgrMode", mgrMode);
map.put("sendMode", sendMode);
int result = storeService.batchCheckPacketMode(map, request);
if (result > 0) {
return new ResultInfo(0, "", "操作成功");
} else {
return new ResultInfo(-1, "", "操作失败");
}
} catch (Exception e) {
LOG.error("更新众包模式发生异常", e);
return new ResultInfo(-1, "", "操作失败");
}
}
}
|
package com.tencent.mm.plugin.collect.b;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.g.a.op;
import com.tencent.mm.kernel.g;
class u$1 implements e {
final /* synthetic */ op hUN;
final /* synthetic */ u hUO;
u$1(u uVar, op opVar) {
this.hUO = uVar;
this.hUN = opVar;
}
public final void a(int i, int i2, String str, l lVar) {
if (this.hUO.eBX != null && this.hUO.eBX.isShowing()) {
this.hUO.eBX.dismiss();
this.hUO.eBX = null;
}
g.DF().b(1800, this);
k kVar = (k) lVar;
kVar.a(new 3(this)).b(new 2(this, kVar)).c(new 1(this));
this.hUN.bZx.bJX.run();
}
}
|
package moe.pinkd.twentyone.core;
import com.sun.istack.internal.Nullable;
import moe.pinkd.twentyone.Config;
import moe.pinkd.twentyone.card.NumberCardPool;
import moe.pinkd.twentyone.player.Player;
import java.util.*;
public class GameManager {
private Player[] players;
private ArrayDeque<Integer> deck = new ArrayDeque<>();//a deck of cards
private HashMap<Player, Boolean> draws = new HashMap<>(2);
private boolean gameOver;
public static final int MAX = 21;
GameManager(Player[] players) {
if (players.length != 2) {
throw new IllegalArgumentException("Player count should be 2");
}
List<Integer> tmpDeck = new ArrayList<>(Arrays.asList(NumberCardPool.NUMBER_CARDS));
this.players = players;
Collections.shuffle(tmpDeck);
deck.addAll(tmpDeck);
gameOver = false;
draws.put(players[0], true);
draws.put(players[1], true);
}
private void getNextCard(Player player) {
Integer card = deck.poll();
if (card != null) {
player.addCard(card, this);
} else {
notifyMessage("No card anymore game over");
gameOver = true;
}
draws.put(player, true);
}
void notifyMessage(String message) {
System.out.println(message);
}
Player getEnemy(Player player) {
return players[0] == player ? players[1] : players[0];
}
boolean getEnemyDrawCard(Player player) {
return draws.get(getEnemy(player));
}
private int getPlayerIndex(Player player) {
return players[0] == player ? 1 : 0;
}
boolean isGameOver() {
return gameOver;
}
void round(OperationExecutor operationExecutor) {
if (draws.get(players[0]) || draws.get(players[1])) {
draws.put(players[0], false);
draws.put(players[1], false);
} else {
gameOver = true;
return;
}
for (Player player : players) {
try {
boolean drawn = player.yourTurn(operationExecutor);
draws.put(player, drawn);
if (drawn) {
getNextCard(player);
}
} catch (Exception e) {
gameOver = true;
for (Integer card : deck) {//花Q
player.addCard(card, this);
}
}
}
}
void init() {
for (Player player : players) {
player.addCard(deck.poll(), this);
player.addCard(deck.poll(), this);
}
}
@Nullable
Player getWinner() {
Player cheater = antiCheat();
if (cheater != null) {
return players[1] == cheater ? players[0] : players[1];
}
int[] sums = new int[2];
for (int i = 0; i < players.length; i++) {
sums[i] = MAX - players[i].getTotalPoint();
if (Config.DEBUG) {
System.out.println(players[i].toString() + ": " + Arrays.toString(players[i].getNumberCards()));
}
}
if (sums[0] == sums[1]) {//draw
return null;
}
if (sums[0] < 0 && sums[1] > 0) {//player 0 bust
return players[1];
}
if (sums[1] < 0 && sums[0] > 0) {//player 1 bust
return players[0];
}
//compare the abs to find out who is closer to 21
return Math.abs(sums[0]) < Math.abs(sums[1]) ? players[0] : players[1];
}
@Nullable
private Player antiCheat() {
for (Player player : players) {
Integer[] numberCards = player.getNumberCards();
for (int i = 1; i < numberCards.length; i++) {
if (deck.contains(numberCards[i])) {
return player;
}
}
}
return null;
}
}
|
package com.example.katakuranatsumi.inventorycheckapp;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;
public class CustomDialogFragment extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
// 今日の日付のカレンダーのインスタンスを取得
final Calendar calendar = Calendar.getInstance();
// ビルダーの生成
DatePickerDialog dateBuilder = new DatePickerDialog(
getActivity(),
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// 選択された年・月・日を整形
String dateStr = year + "年" + (month + 1) + "月" + dayOfMonth + "日";
// MainActivityのインスタンスを取得
// MainActivity mainActivity = (MainActivity) getActivity();
// mainActivity.setTitle(dateStr);
NewInventActivity newInventActivity = (NewInventActivity) getActivity();
EditText editDate = newInventActivity.findViewById(R.id.inventdate);
editDate.setText(dateStr);
}
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
);
return dateBuilder;
}
}
|
package com.example.protokol.create_protokol;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class InsulationActivity extends AppCompatActivity {
DBHelper dbHelper;
private String date = "Дата проведения проверки «__» ___________ _______г. ";
private String zag = "Климатические условия при проведении измерений";
private String uslovia = "Температура воздуха __С. Влажность воздуха __%. Атмосферное давление ___ мм.рт.ст.(бар).";
private String zag2 = "Нормативные и технические документы, на соответствие требованиям которых проведена проверка:";
private String line = "_______________________________________________________________________________________________________________________";
private String proverka = " Проверку провели: _____________________ ___________ _____________" + "\n" +
" (Должность) (Подпись) (Ф.И.О.)" + "\n" + "\n" +
" Проверил: _____________________ ___________ _____________" + "\n" +
" (Должность) (Подпись) (Ф.И.О.)";
private String[] header = {"№\nп/п", "Наименование линий, по проекту", "Рабочее\nнапряжение, В", "Марка провода,\nкабеля", "Количество\nжил, сечение\nпровода,\nкабеля, мм кв.",
"Напряжение\nмегаомметра, В", "Допустимое\nсопротивление\nизоляции, МОм", "Сопротивление изоляции, МОм", "L1-L2\n(A-B)", "L2-L3\n(В-С)", "L3-L1\n(C-A)", "L1-N\n(A-N)\n(PEN)",
"L2-N\n(B-N)\n(PEN)", "L3-N\n(C-N)\n(PEN)", "L1-PE\n(A-PE)", "L2-PE\n(B-PE)", "L3-PE\n(C-PE)", "N-PE", "Вывод о\nсоответствии\nнормативному\nдокументу"};
private TemplatePDF templatePDF;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insulation);
dbHelper = new DBHelper(this);
final SQLiteDatabase database = dbHelper.getWritableDatabase();
final ListView rooms = findViewById(R.id.rooms);
Button addRoom = findViewById(R.id.button9);
Button pdf = findViewById(R.id.button8);
//НАСТРАИВАЕМ ACTIONBAR
getSupportActionBar().setSubtitle("Комнаты");
getSupportActionBar().setTitle("Изоляция");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//ЗАПРОС В БД И ЗАПОЛНЕНИЕ СПИСКА КОМНАТ
addSpisokRooms(database, rooms);
//ДОБАВИТЬ КОМНАТУ
addRoom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(InsulationActivity.this);
View myView = getLayoutInflater().inflate(R.layout.dialog_for_names,null);
alert.setCancelable(false);
alert.setTitle("Введите название комнаты:");
final EditText input = myView.findViewById(R.id.editText);
alert.setPositiveButton("ОК", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String nameRoom = input.getText().toString();
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.LNR_NAME, nameRoom);
database.insert(DBHelper.TABLE_LINE_ROOMS, null, contentValues);
//ЗАПРОС В БД И ЗАПОЛНЕНИЕ СПИСКА КОМНАТ
addSpisokRooms(database, rooms);
Toast toast = Toast.makeText(getApplicationContext(),
"Комната <" + nameRoom + "> добавлена", Toast.LENGTH_SHORT);
toast.show();
}
});
alert.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.setView(myView);
alert.show();
}
});
//ПЕРЕХОД К ЩИТАМ И РЕДАКТОР КОМНАТЫ
rooms.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view, final int position, final long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(InsulationActivity.this);
alert.setTitle(((TextView) view).getText());
String arrayMenu[] = {"Перейти к щитам", "Изменить название", "Удалить комнату"};
alert.setItems(arrayMenu, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//ЗАПРОС В БД ДЛЯ ПОЛУЧЕНИЯ ID НУЖНОЙ КОМНАТЫ
Cursor cursor4 = database.query(DBHelper.TABLE_LINE_ROOMS, new String[] {DBHelper.LNR_ID}, null, null, null, null, null);
cursor4.moveToPosition(position);
int idRoomIndex = cursor4.getColumnIndex(DBHelper.LNR_ID);
final int idRoom = cursor4.getInt(idRoomIndex);
cursor4.close();
//ПЕРЕЙТИ К ЩИТАМ
if (which == 0) {
Intent intent = new Intent("android.intent.action.Insulation2");
intent.putExtra("nameRoom", ((TextView) view).getText().toString());
intent.putExtra("idRoom", idRoom);
startActivity(intent);
}
//ИЗМЕНИТЬ НАЗВАНИЕ
if (which == 1) {
AlertDialog.Builder alert1 = new AlertDialog.Builder(InsulationActivity.this);
alert1.setCancelable(false);
alert1.setTitle("Введите новое название комнаты:");
final EditText input = new EditText(InsulationActivity.this);
alert1.setView(input);
alert1.setPositiveButton("Изменить", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String namer = input.getText().toString();
ContentValues uppname = new ContentValues();
uppname.put(DBHelper.LNR_NAME, namer);
database.update(DBHelper.TABLE_LINE_ROOMS,
uppname,
"_id = ?",
new String[] {String.valueOf(idRoom)});
//ЗАПРОС В БД И ЗАПОЛНЕНИЕ СПИСКА КОМНАТ
addSpisokRooms(database, rooms);
Toast toast1 = Toast.makeText(getApplicationContext(),
"Название изменено: " + namer, Toast.LENGTH_SHORT);
toast1.show();
}
});
alert1.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert1.show();
}
//УДАЛИТЬ КОМНАТУ
if (which == 2) {
//ПОДТВЕРЖДЕНИЕ
AlertDialog.Builder builder4 = new AlertDialog.Builder(InsulationActivity.this);
builder4.setCancelable(false);
builder4.setPositiveButton("ОК", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
database.delete(DBHelper.TABLE_GROUPS, "grlnr_id = ?", new String[] {String.valueOf(idRoom)});
database.delete(DBHelper.TABLE_LINES, "lnr_id = ?", new String[] {String.valueOf(idRoom)});
database.delete(DBHelper.TABLE_LINE_ROOMS, "_id = ?", new String[] {String.valueOf(idRoom)});
//ЗАПРОС В БД И ЗАПОЛНЕНИЕ СПИСКА КОМНАТ
addSpisokRooms(database, rooms);
Toast toast2 = Toast.makeText(getApplicationContext(),
"Комната <" + ((TextView) view).getText() + "> удалена", Toast.LENGTH_SHORT);
toast2.show();
}
});
builder4.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
builder4.setMessage("Вы точно хотите удалить комнату <" + ((TextView) view).getText() + ">?");
AlertDialog dialog4 = builder4.create();
dialog4.show();
}
}
});
alert.show();
}
});
//ОТКРЫТИЕ PDF
pdf.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//ПРОСТО ОТКРЫТЬ ИЛИ С СОХРАНЕНИЕМ?
AlertDialog.Builder builder1 = new AlertDialog.Builder(InsulationActivity.this);
builder1.setPositiveButton("Посмотреть", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//ПРОСТО ПОСМОТРЕТЬ
opPFD(database, null);
}
});
builder1.setNegativeButton("Сохранить", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//ЗАПРАШИВАЕМ НАЗВАНИЕ ФАЙЛА
AlertDialog.Builder alert = new AlertDialog.Builder(InsulationActivity.this);
alert.setCancelable(false);
alert.setTitle("Введите название сохраняемого файла:");
final EditText input = new EditText(InsulationActivity.this);
alert.setView(input);
alert.setPositiveButton("ОК", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String namefile = input.getText().toString();
if (namefile.equals(""))
namefile = null;
opPFD(database, namefile);
}
});
alert.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
});
builder1.setMessage("Хотите просто посмотреть файл или же открыть с дальнейшим сохранением?");
AlertDialog dialog1 = builder1.create();
dialog1.show();
}
});
}
//НАЗАД
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(InsulationActivity.this, MainActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public void start(String namefile) {
templatePDF = new TemplatePDF(getApplicationContext());
templatePDF.openDocument(namefile, true);
templatePDF.addMetaData("Protokol", "Item", "Company");
templatePDF.addTitles_BD("РЕЗУЛЬТАТЫ", "проверки сопротивления изоляции проводов и кабелей", 12);
templatePDF.addParagraph_NotBD(date, 10);
templatePDF.addCenter_BD_NotBefore(zag, 12);
templatePDF.addCenter_NotBD(uslovia, 10);
templatePDF.addCenter_BD_withBefore(zag2, 12);
templatePDF.addCenter_NotBD(line, 10);
templatePDF.createTableInsulation(header);
}
//ОТКРЫТИЕ PDF
public void opPFD(SQLiteDatabase database, String namefile) {
ArrayList<String> group = new ArrayList<>();
ArrayList<ArrayList> groups = new ArrayList<>();
if (namefile == null)
namefile = "TepmlatePDF";
start(namefile);
int roomPrev = 0, linePrev = 0, currentLine = 0, currentRoom = 0;
Cursor cursor = database.rawQuery("select r._id as r_id, l._id as l_id, room, line, lnr_id, grline_id, name_group, u1, " +
"mark, vein, section, u2, r, a_b, b_c, c_a, a_n, b_n, c_n, a_pe, b_pe, c_pe, n_pe, " +
"conclusion from lnrooms as r join `lines` as l on l.lnr_id = r._id join groups as g on g.grline_id = l._id order by r._id, l._id", new String[] { });
if (cursor.moveToFirst()) {
int r_idIndex = cursor.getColumnIndex("r_id");
int nameRoomIndex = cursor.getColumnIndex(DBHelper.LNR_NAME);
int l_idIndex = cursor.getColumnIndex("l_id");
int nameLineIndex = cursor.getColumnIndex(DBHelper.LN_NAME);
int nameGroupIndex = cursor.getColumnIndex(DBHelper.GR_NAME);
int markIndex = cursor.getColumnIndex(DBHelper.GR_MARK);
int veinIndex = cursor. getColumnIndex(DBHelper.GR_VEIN);
int sectionIndex = cursor. getColumnIndex(DBHelper.GR_SECTION);
int workUIndex = cursor. getColumnIndex(DBHelper.GR_U1);
int uIndex = cursor. getColumnIndex(DBHelper.GR_U2);
int rIndex = cursor. getColumnIndex(DBHelper.GR_R);
int a_bIndex = cursor. getColumnIndex(DBHelper.GR_A_B);
int b_cIndex = cursor. getColumnIndex(DBHelper.GR_B_C);
int c_aIndex = cursor. getColumnIndex(DBHelper.GR_C_A);
int a_nIndex = cursor. getColumnIndex(DBHelper.GR_A_N);
int b_nIndex = cursor. getColumnIndex(DBHelper.GR_B_N);
int c_nIndex = cursor. getColumnIndex(DBHelper.GR_C_N);
int a_peIndex = cursor. getColumnIndex(DBHelper.GR_A_PE);
int b_peIndex = cursor. getColumnIndex(DBHelper.GR_B_PE);
int c_peIndex = cursor. getColumnIndex(DBHelper.GR_C_PE);
int n_peIndex = cursor. getColumnIndex(DBHelper.GR_N_PE);
int conclusionIndex = cursor. getColumnIndex(DBHelper.GR_CONCLUSION);
do {
int r_id = cursor.getInt(r_idIndex);
int l_id = cursor.getInt(l_idIndex);
//ЕСЛИ ВСТРЕТИЛАСЬ НОВАЯ КОМНАТА
if ((r_id != roomPrev)){
templatePDF.addGroupsInsulation(groups);
groups = new ArrayList<>();
currentLine = 0;
currentRoom++;
roomPrev = r_id;
templatePDF.addRoomInsulation(String.valueOf(currentRoom) + ". " + cursor.getString(nameRoomIndex));
}
//ЕСЛИ ВСТРЕТИЛСЯ НОВЫЙ ЩИТ
if ((l_id != linePrev)){
templatePDF.addGroupsInsulation(groups);
groups = new ArrayList<>();
linePrev = l_id;
currentLine++;
templatePDF.addLineInsulation(String.valueOf(currentLine) + ". ", " " + cursor.getString(nameLineIndex));
}
String vein = cursor.getString(veinIndex);
group.add(cursor.getString(nameGroupIndex));
group.add(cursor.getString(workUIndex));
group.add(cursor.getString(markIndex));
if (vein.equals("-"))
group.add("-");
else
group.add(vein + "x" + cursor.getString(sectionIndex));
group.add(cursor.getString(uIndex));
group.add(cursor.getString(rIndex));
group.add(cursor.getString(a_bIndex));
group.add(cursor.getString(b_cIndex));
group.add(cursor.getString(c_aIndex));
group.add(cursor.getString(a_nIndex));
group.add(cursor.getString(b_nIndex));
group.add(cursor.getString(c_nIndex));
group.add(cursor.getString(a_peIndex));
group.add(cursor.getString(b_peIndex));
group.add(cursor.getString(c_peIndex));
group.add(cursor.getString(n_peIndex));
group.add(cursor.getString(conclusionIndex));
groups.add(group);
group = new ArrayList<>();
} while (cursor.moveToNext());
templatePDF.addGroupsInsulation(groups);
}
cursor.close();
String end = "Примечание: ___________________________________________________________________________________________________________________";
String end2 = "Заключене: ____________________________________________________________________________________________________________________" + "\n" +
"_______________________________________________________________________________________________________________________________";
templatePDF.addParagraph_BD(end, 12);
templatePDF.addParagraph_BD(end2, 12);
templatePDF.addParagraph_NotBD(proverka, 10);
templatePDF.closeDocument();
templatePDF.appViewPDF(InsulationActivity.this);
}
public void addSpisokRooms(SQLiteDatabase database, ListView rooms) {
final ArrayList<String> spisokRooms = new ArrayList <String>();
Cursor cursor = database.query(DBHelper.TABLE_LINE_ROOMS, new String[] {DBHelper.LNR_NAME}, null, null, null, null, null);
if (cursor.moveToFirst()) {
int nameIndex = cursor.getColumnIndex(DBHelper.LNR_NAME);
do {
spisokRooms.add(cursor.getString(nameIndex));
} while (cursor.moveToNext());
}
cursor.close();
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, spisokRooms);
rooms.setAdapter(adapter);
}
}
|
package com.tencent.mm.r;
import com.tencent.mm.bt.h.d;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.ar;
import com.tencent.mm.model.p;
import com.tencent.mm.r.a.1;
import com.tencent.mm.sdk.platformtools.x;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class i implements ar {
private static HashMap<Integer, d> cVM;
private e diO;
private c diP = new c();
Map<Integer, List<f>> diQ = new HashMap();
static i Cf() {
return (i) p.v(i.class);
}
public static e Cg() {
if (Cf().diO == null) {
Cf().diO = new e(g.Ei().dqq);
}
return Cf().diO;
}
public static c Ch() {
if (Cf().diP == null) {
Cf().diP = new c();
}
return Cf().diP;
}
public static synchronized void a(f fVar) {
synchronized (i.class) {
x.i("MicroMsg.SubCoreFunctionMsg", "removeUpdateCallback, msgType: %s, callback: %s", new Object[]{Integer.valueOf(12399999), fVar});
if (fVar != null) {
List list = (List) Cf().diQ.get(Integer.valueOf(12399999));
if (list != null && list.contains(fVar)) {
list.remove(fVar);
Cf().diQ.put(Integer.valueOf(12399999), list);
}
}
}
}
public static synchronized void b(f fVar) {
synchronized (i.class) {
x.i("MicroMsg.SubCoreFunctionMsg", "addUpdateCallback, msgType: %s, callback: %s", new Object[]{Integer.valueOf(12399999), fVar});
if (fVar != null) {
List list = (List) Cf().diQ.get(Integer.valueOf(12399999));
if (list == null) {
list = new ArrayList();
}
if (!list.contains(fVar)) {
list.add(fVar);
}
Cf().diQ.put(Integer.valueOf(12399999), list);
}
}
}
static {
HashMap hashMap = new HashMap();
cVM = hashMap;
hashMap.put(Integer.valueOf("FunctionMsgItem".hashCode()), new 1());
}
public final HashMap<Integer, d> Ci() {
x.i("MicroMsg.SubCoreFunctionMsg", "getBaseDBFactories");
return cVM;
}
public final void gi(int i) {
}
public final void bn(boolean z) {
x.i("MicroMsg.SubCoreFunctionMsg", "onAccountPostReset");
g.Em().h(new 1(), 10000);
}
public final void bo(boolean z) {
}
public final void onAccountRelease() {
x.d("MicroMsg.SubCoreFunctionMsg", "onAccountRelease");
}
}
|
package java2.servlets.mvc;
import java2.database.AnnouncementRepository;
import java2.domain.Announcement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.logging.Logger;
@Controller
public class UserAnnouncementsController {
private static Logger logger = Logger.getLogger(UserAnnouncementsController.class.getName());
@Autowired
private AnnouncementRepository announcementRepository;
@RequestMapping(value = "userAnnouncements", method = {RequestMethod.GET})
public ModelAndView userAnnouncementsGet(HttpServletRequest request) {
logger.info("userAnnouncements GET called.");
HttpSession session = request.getSession();
if(!session.getAttribute("role").toString().equals("U")) {
return new ModelAndView("userLogin", "model", null);
}
String login = session.getAttribute("login").toString();
List<Announcement> announcements =
announcementRepository.findByLogin(login);
return new ModelAndView("userAnnouncements", "model", announcements);
}
}
|
package testing2;
/**
* Created by joetomjob on 3/21/20.
*/
public class BST {
TreeNode root;
public void traverse() {
inOrder(root);
System.out.print('\n');
}
public void inOrder(TreeNode node) {
if(node == null) {
return;
}
inOrder(node.left);
System.out.print(node.data);
System.out.print('\t');
inOrder(node.right);
}
public void insert(TreeNode a) {
if(root == null) {
root = a;
} else {
insertFrom(root, a);
}
}
public void insertFrom(TreeNode root, TreeNode a) {
if(a.data < root.data) {
if(root.left == null) {
root.left = a;
} else {
insertFrom(root.left, a);
}
} else {
if(root.right == null) {
root.right = a;
} else {
insertFrom(root.right, a);
}
}
}
public int height(){
return heightOfTree(root);
}
public int heightOfTree(TreeNode node) {
if(node == null) {
return 0;
}
int l = heightOfTree(node.left);
int r = heightOfTree(node.right);
return Math.max(l, r) + 1;
}
public static void main(String[] args) {
TreeNode a = new TreeNode(26);
TreeNode b = new TreeNode(33);
TreeNode c = new TreeNode(45);
TreeNode d = new TreeNode(59);
TreeNode e = new TreeNode(61);
TreeNode f = new TreeNode(57);
TreeNode g = new TreeNode(18);
TreeNode h = new TreeNode(99);
TreeNode i = new TreeNode(10);
TreeNode j = new TreeNode(12);
TreeNode k = new TreeNode(63);
BST bst = new BST();
bst.insert(a);
bst.insert(b);
bst.insert(c);
bst.insert(d);
bst.insert(e);
bst.insert(f);
bst.insert(g);
bst.insert(h);
bst.insert(i);
bst.insert(j);
bst.insert(k);
bst.traverse();
System.out.println(bst.height());
}
}
|
package com.yougou.merchant.api.monitor.vo;
import java.io.Serializable;
public class ApiMonitorParameterVo implements Serializable {
private static final long serialVersionUID = 1L;
//单接口日调用超限次数
private String dataFlowRate;
//单接口超限频率
private String frequencyRate;
//锁定接口小时数
private String frequencyOutLockTime;
//单接口日调用次数预警
private String simpleImplOneDayRate;
//单接口频率预警
private String simpleImplFrequencyRate;
//调用成功率预警
private String successRate;
//AppKey日调用次数预警
private String appKeyCallFrequencyRate;
//无效AppKey发送IP
private String invalidAppKeyRequest;
public String getDataFlowRate() {
return dataFlowRate;
}
public void setDataFlowRate(String dataFlowRate) {
this.dataFlowRate = dataFlowRate;
}
public String getFrequencyRate() {
return frequencyRate;
}
public void setFrequencyRate(String frequencyRate) {
this.frequencyRate = frequencyRate;
}
public String getFrequencyOutLockTime() {
return frequencyOutLockTime;
}
public void setFrequencyOutLockTime(String frequencyOutLockTime) {
this.frequencyOutLockTime = frequencyOutLockTime;
}
public String getSimpleImplOneDayRate() {
return simpleImplOneDayRate;
}
public void setSimpleImplOneDayRate(String simpleImplOneDayRate) {
this.simpleImplOneDayRate = simpleImplOneDayRate;
}
public String getSimpleImplFrequencyRate() {
return simpleImplFrequencyRate;
}
public void setSimpleImplFrequencyRate(String simpleImplFrequencyRate) {
this.simpleImplFrequencyRate = simpleImplFrequencyRate;
}
public String getSuccessRate() {
return successRate;
}
public void setSuccessRate(String successRate) {
this.successRate = successRate;
}
public String getAppKeyCallFrequencyRate() {
return appKeyCallFrequencyRate;
}
public void setAppKeyCallFrequencyRate(String appKeyCallFrequencyRate) {
this.appKeyCallFrequencyRate = appKeyCallFrequencyRate;
}
public String getInvalidAppKeyRequest() {
return invalidAppKeyRequest;
}
public void setInvalidAppKeyRequest(String invalidAppKeyRequest) {
this.invalidAppKeyRequest = invalidAppKeyRequest;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.